import type { Prisma } from "@capakraken/db"; import { CreateRateCardLineSchema, CreateRateCardSchema, UpdateRateCardLineSchema, UpdateRateCardSchema, } from "@capakraken/shared"; import { z } from "zod"; import { findUniqueOrThrow } from "../db/helpers.js"; import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js"; import { createAuditEntry } from "../lib/audit.js"; import { lookupBestRateMatch, rateCardLineSelect, resolveBestRate, resolveBestRateLineMatch, } from "./rate-card-read.js"; export const rateCardRouter = createTRPCRouter({ list: controllerProcedure .input( z.object({ isActive: z.boolean().optional(), search: z.string().optional(), clientId: z.string().optional(), effectiveAt: z.coerce.date().optional(), }).optional(), ) .query(async ({ ctx, input }) => { return ctx.db.rateCard.findMany({ where: { ...(input?.isActive !== undefined ? { isActive: input.isActive } : {}), ...(input?.clientId !== undefined ? { clientId: input.clientId } : {}), ...(input?.search ? { name: { contains: input.search, mode: "insensitive" as const } } : {}), ...(input?.effectiveAt ? { OR: [ { effectiveFrom: null }, { effectiveFrom: { lte: input.effectiveAt } }, ], AND: [ { OR: [ { effectiveTo: null }, { effectiveTo: { gte: input.effectiveAt } }, ], }, ], } : {}), }, include: { _count: { select: { lines: true } }, client: { select: { id: true, name: true, code: true } }, }, orderBy: [{ isActive: "desc" }, { effectiveFrom: "desc" }, { name: "asc" }], }); }), getById: controllerProcedure .input(z.object({ id: z.string() })) .query(async ({ ctx, input }) => { const rateCard = await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.id }, include: { client: { select: { id: true, name: true, code: true } }, lines: { select: rateCardLineSelect, orderBy: [{ chapter: "asc" }, { seniority: "asc" }, { createdAt: "asc" }], }, }, }), "Rate card", ); return rateCard; }), lookupBestMatch: controllerProcedure .input(z.object({ clientId: z.string().optional(), chapter: z.string().optional(), managementLevelId: z.string().optional(), roleName: z.string().optional(), seniority: z.string().optional(), })) .query(async ({ ctx, input }) => lookupBestRateMatch(ctx.db, input)), resolveBestRate: controllerProcedure .input(z.object({ resourceId: z.string().optional(), roleName: z.string().optional(), date: z.coerce.date().optional(), })) .query(async ({ ctx, input }) => resolveBestRate(ctx.db, input)), create: managerProcedure .input(CreateRateCardSchema) .mutation(async ({ ctx, input }) => { const { lines, ...cardData } = input; const rateCard = await ctx.db.rateCard.create({ data: { name: cardData.name, currency: cardData.currency, ...(cardData.effectiveFrom !== undefined ? { effectiveFrom: cardData.effectiveFrom } : {}), ...(cardData.effectiveTo !== undefined ? { effectiveTo: cardData.effectiveTo } : {}), ...(cardData.source !== undefined ? { source: cardData.source } : {}), ...(cardData.clientId !== undefined ? { clientId: cardData.clientId } : {}), lines: { create: lines.map((line) => ({ ...(line.roleId !== undefined ? { roleId: line.roleId } : {}), ...(line.chapter !== undefined ? { chapter: line.chapter } : {}), ...(line.location !== undefined ? { location: line.location } : {}), ...(line.seniority !== undefined ? { seniority: line.seniority } : {}), ...(line.workType !== undefined ? { workType: line.workType } : {}), ...(line.serviceGroup !== undefined ? { serviceGroup: line.serviceGroup } : {}), costRateCents: line.costRateCents, ...(line.billRateCents !== undefined ? { billRateCents: line.billRateCents } : {}), ...(line.machineRateCents !== undefined ? { machineRateCents: line.machineRateCents } : {}), attributes: line.attributes as Prisma.InputJsonValue, })), }, }, include: { lines: { select: rateCardLineSelect }, }, }); void createAuditEntry({ db: ctx.db, entityType: "RateCard", entityId: rateCard.id, entityName: rateCard.name, action: "CREATE", userId: ctx.dbUser?.id, after: { name: cardData.name, currency: cardData.currency, lineCount: lines.length }, source: "ui", }); return rateCard; }), update: managerProcedure .input(z.object({ id: z.string(), data: UpdateRateCardSchema })) .mutation(async ({ ctx, input }) => { const before = await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.id } }), "Rate card", ); const updated = await ctx.db.rateCard.update({ where: { id: input.id }, data: { ...(input.data.name !== undefined ? { name: input.data.name } : {}), ...(input.data.currency !== undefined ? { currency: input.data.currency } : {}), ...(input.data.effectiveFrom !== undefined ? { effectiveFrom: input.data.effectiveFrom } : {}), ...(input.data.effectiveTo !== undefined ? { effectiveTo: input.data.effectiveTo } : {}), ...(input.data.source !== undefined ? { source: input.data.source } : {}), ...(input.data.clientId !== undefined ? { clientId: input.data.clientId } : {}), ...(input.data.isActive !== undefined ? { isActive: input.data.isActive } : {}), }, include: { _count: { select: { lines: true } }, client: { select: { id: true, name: true, code: true } }, }, }); void createAuditEntry({ db: ctx.db, entityType: "RateCard", entityId: input.id, entityName: updated.name, action: "UPDATE", userId: ctx.dbUser?.id, before: before as unknown as Record, after: updated as unknown as Record, source: "ui", }); return updated; }), deactivate: managerProcedure .input(z.object({ id: z.string() })) .mutation(async ({ ctx, input }) => { const deactivated = await ctx.db.rateCard.update({ where: { id: input.id }, data: { isActive: false }, }); void createAuditEntry({ db: ctx.db, entityType: "RateCard", entityId: input.id, entityName: deactivated.name, action: "DELETE", userId: ctx.dbUser?.id, source: "ui", summary: "Deactivated rate card", }); return deactivated; }), // ─── Line CRUD ───────────────────────────────────────────────────────────── addLine: managerProcedure .input(z.object({ rateCardId: z.string(), line: CreateRateCardLineSchema })) .mutation(async ({ ctx, input }) => { const rateCard = await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }), "Rate card", ); const line = await ctx.db.rateCardLine.create({ data: { rateCardId: input.rateCardId, ...(input.line.roleId !== undefined ? { roleId: input.line.roleId } : {}), ...(input.line.chapter !== undefined ? { chapter: input.line.chapter } : {}), ...(input.line.location !== undefined ? { location: input.line.location } : {}), ...(input.line.seniority !== undefined ? { seniority: input.line.seniority } : {}), ...(input.line.workType !== undefined ? { workType: input.line.workType } : {}), ...(input.line.serviceGroup !== undefined ? { serviceGroup: input.line.serviceGroup } : {}), costRateCents: input.line.costRateCents, ...(input.line.billRateCents !== undefined ? { billRateCents: input.line.billRateCents } : {}), ...(input.line.machineRateCents !== undefined ? { machineRateCents: input.line.machineRateCents } : {}), attributes: input.line.attributes as Prisma.InputJsonValue, }, select: rateCardLineSelect, }); void createAuditEntry({ db: ctx.db, entityType: "RateCardLine", entityId: line.id, entityName: `${rateCard.name} — ${input.line.chapter ?? "line"}`, action: "CREATE", userId: ctx.dbUser?.id, after: { rateCardId: input.rateCardId, costRateCents: input.line.costRateCents, billRateCents: input.line.billRateCents }, source: "ui", }); return line; }), updateLine: managerProcedure .input(z.object({ lineId: z.string(), data: UpdateRateCardLineSchema })) .mutation(async ({ ctx, input }) => { const before = await findUniqueOrThrow( ctx.db.rateCardLine.findUnique({ where: { id: input.lineId } }), "Rate card line", ); const updateData: Prisma.RateCardLineUpdateInput = {}; if (input.data.roleId !== undefined) updateData.role = input.data.roleId ? { connect: { id: input.data.roleId } } : { disconnect: true }; if (input.data.chapter !== undefined) updateData.chapter = input.data.chapter; if (input.data.location !== undefined) updateData.location = input.data.location; if (input.data.seniority !== undefined) updateData.seniority = input.data.seniority; if (input.data.workType !== undefined) updateData.workType = input.data.workType; if (input.data.serviceGroup !== undefined) updateData.serviceGroup = input.data.serviceGroup; if (input.data.costRateCents !== undefined) updateData.costRateCents = input.data.costRateCents; if (input.data.billRateCents !== undefined) updateData.billRateCents = input.data.billRateCents; if (input.data.machineRateCents !== undefined) updateData.machineRateCents = input.data.machineRateCents; if (input.data.attributes !== undefined) updateData.attributes = input.data.attributes as Prisma.InputJsonValue; const updated = await ctx.db.rateCardLine.update({ where: { id: input.lineId }, data: updateData, select: rateCardLineSelect, }); void createAuditEntry({ db: ctx.db, entityType: "RateCardLine", entityId: input.lineId, action: "UPDATE", userId: ctx.dbUser?.id, before: before as unknown as Record, after: updated as unknown as Record, source: "ui", }); return updated; }), deleteLine: managerProcedure .input(z.object({ lineId: z.string() })) .mutation(async ({ ctx, input }) => { const line = await findUniqueOrThrow( ctx.db.rateCardLine.findUnique({ where: { id: input.lineId } }), "Rate card line", ); await ctx.db.rateCardLine.delete({ where: { id: input.lineId } }); void createAuditEntry({ db: ctx.db, entityType: "RateCardLine", entityId: input.lineId, action: "DELETE", userId: ctx.dbUser?.id, before: line as unknown as Record, source: "ui", }); return { deleted: true }; }), // ─── Batch operations ────────────────────────────────────────────────────── replaceLines: managerProcedure .input(z.object({ rateCardId: z.string(), lines: z.array(CreateRateCardLineSchema), })) .mutation(async ({ ctx, input }) => { const rateCard = await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }), "Rate card", ); const result = await ctx.db.$transaction(async (tx) => { await tx.rateCardLine.deleteMany({ where: { rateCardId: input.rateCardId } }); const created = await Promise.all( input.lines.map((line) => tx.rateCardLine.create({ data: { rateCardId: input.rateCardId, ...(line.roleId !== undefined ? { roleId: line.roleId } : {}), ...(line.chapter !== undefined ? { chapter: line.chapter } : {}), ...(line.location !== undefined ? { location: line.location } : {}), ...(line.seniority !== undefined ? { seniority: line.seniority } : {}), ...(line.workType !== undefined ? { workType: line.workType } : {}), ...(line.serviceGroup !== undefined ? { serviceGroup: line.serviceGroup } : {}), costRateCents: line.costRateCents, ...(line.billRateCents !== undefined ? { billRateCents: line.billRateCents } : {}), ...(line.machineRateCents !== undefined ? { machineRateCents: line.machineRateCents } : {}), attributes: line.attributes as Prisma.InputJsonValue, }, select: rateCardLineSelect, }), ), ); return created; }); void createAuditEntry({ db: ctx.db, entityType: "RateCard", entityId: input.rateCardId, entityName: rateCard.name, action: "UPDATE", userId: ctx.dbUser?.id, after: { replacedLineCount: result.length }, source: "ui", summary: `Replaced all lines with ${result.length} new lines`, }); return result; }), // ─── Rate resolution ─────────────────────────────────────────────────────── resolveRateLine: controllerProcedure .input(z.object({ rateCardId: z.string(), roleId: z.string().optional(), chapter: z.string().optional(), location: z.string().optional(), seniority: z.string().optional(), workType: z.string().optional(), })) .query(async ({ ctx, input }) => { const { rateCardId, ...criteria } = input; // Find the most specific matching line (most criteria matched wins) const lines = await ctx.db.rateCardLine.findMany({ where: { rateCardId }, select: rateCardLineSelect, }); return resolveBestRateLineMatch(lines, criteria); }), });