import type { Prisma } from "@planarchy/db"; import { CreateRateCardLineSchema, CreateRateCardSchema, UpdateRateCardLineSchema, UpdateRateCardSchema, } from "@planarchy/shared"; import { TRPCError } from "@trpc/server"; import { z } from "zod"; import { findUniqueOrThrow } from "../db/helpers.js"; import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js"; import { ROLE_BRIEF_SELECT } from "../db/selects.js"; const lineSelect = { id: true, rateCardId: true, roleId: true, chapter: true, location: true, seniority: true, workType: true, serviceGroup: true, costRateCents: true, billRateCents: true, machineRateCents: true, attributes: true, role: { select: ROLE_BRIEF_SELECT }, createdAt: true, updatedAt: true, } as const; 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: lineSelect, orderBy: [{ chapter: "asc" }, { seniority: "asc" }, { createdAt: "asc" }], }, }, }), "Rate card", ); return rateCard; }), create: managerProcedure .input(CreateRateCardSchema) .mutation(async ({ ctx, input }) => { const { lines, ...cardData } = input; return 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: lineSelect }, }, }); }), update: managerProcedure .input(z.object({ id: z.string(), data: UpdateRateCardSchema })) .mutation(async ({ ctx, input }) => { await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.id } }), "Rate card", ); return 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 } }, }, }); }), deactivate: managerProcedure .input(z.object({ id: z.string() })) .mutation(async ({ ctx, input }) => { return ctx.db.rateCard.update({ where: { id: input.id }, data: { isActive: false }, }); }), // ─── Line CRUD ───────────────────────────────────────────────────────────── addLine: managerProcedure .input(z.object({ rateCardId: z.string(), line: CreateRateCardLineSchema })) .mutation(async ({ ctx, input }) => { await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }), "Rate card", ); return 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: lineSelect, }); }), updateLine: managerProcedure .input(z.object({ lineId: z.string(), data: UpdateRateCardLineSchema })) .mutation(async ({ ctx, input }) => { 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; return ctx.db.rateCardLine.update({ where: { id: input.lineId }, data: updateData, select: lineSelect, }); }), deleteLine: managerProcedure .input(z.object({ lineId: z.string() })) .mutation(async ({ ctx, input }) => { await findUniqueOrThrow( ctx.db.rateCardLine.findUnique({ where: { id: input.lineId } }), "Rate card line", ); await ctx.db.rateCardLine.delete({ where: { id: input.lineId } }); return { deleted: true }; }), // ─── Batch operations ────────────────────────────────────────────────────── replaceLines: managerProcedure .input(z.object({ rateCardId: z.string(), lines: z.array(CreateRateCardLineSchema), })) .mutation(async ({ ctx, input }) => { await findUniqueOrThrow( ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }), "Rate card", ); return 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: lineSelect, }), ), ); return created; }); }), // ─── Rate resolution ─────────────────────────────────────────────────────── resolveRate: 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: lineSelect, }); if (lines.length === 0) return null; // Score each line by number of matching criteria const scored = lines.map((line) => { let score = 0; let mismatch = false; if (criteria.roleId && line.roleId) { if (line.roleId === criteria.roleId) score += 4; else mismatch = true; } if (criteria.chapter && line.chapter) { if (line.chapter === criteria.chapter) score += 2; else mismatch = true; } if (criteria.location && line.location) { if (line.location === criteria.location) score += 1; else mismatch = true; } if (criteria.seniority && line.seniority) { if (line.seniority === criteria.seniority) score += 1; else mismatch = true; } if (criteria.workType && line.workType) { if (line.workType === criteria.workType) score += 1; else mismatch = true; } return { line, score, mismatch }; }); // Filter out mismatches and find best match const candidates = scored .filter((s) => !s.mismatch) .sort((a, b) => b.score - a.score); const best = candidates[0]; return best ? best.line : null; }), });