feat(platform): harden access scoping and delivery baseline

This commit is contained in:
2026-03-30 00:27:31 +02:00
parent 00b936fa1f
commit 819345acfa
109 changed files with 26142 additions and 8081 deletions
+239 -1
View File
@@ -11,6 +11,7 @@ import { findUniqueOrThrow } from "../db/helpers.js";
import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js";
import { ROLE_BRIEF_SELECT } from "../db/selects.js";
import { createAuditEntry } from "../lib/audit.js";
import { fmtEur } from "../lib/format-utils.js";
const lineSelect = {
id: true,
@@ -30,6 +31,118 @@ const lineSelect = {
updatedAt: true,
} as const;
async function lookupBestRateMatch(
db: Pick<import("@capakraken/db").PrismaClient, "rateCard" | "role">,
input: {
clientId?: string | undefined;
chapter?: string | undefined;
managementLevelId?: string | undefined;
roleName?: string | undefined;
seniority?: string | undefined;
},
) {
const rateCardWhere: Prisma.RateCardWhereInput = { isActive: true };
if (input.clientId) {
rateCardWhere.OR = [
{ clientId: input.clientId },
{ clientId: null },
];
}
const rateCards = await db.rateCard.findMany({
where: rateCardWhere,
include: {
lines: {
select: {
id: true,
chapter: true,
seniority: true,
costRateCents: true,
billRateCents: true,
role: { select: { id: true, name: true } },
},
},
client: { select: { id: true, name: true } },
},
orderBy: [{ effectiveFrom: "desc" }],
});
if (rateCards.length === 0) {
return {
bestMatch: null,
alternatives: [],
totalCandidates: 0,
message: "No active rate cards found.",
};
}
let roleId: string | undefined;
if (input.roleName) {
const role = await db.role.findFirst({
where: { name: { contains: input.roleName, mode: "insensitive" } },
select: { id: true },
});
if (role) roleId = role.id;
}
const scoredLines: Array<{
rateCardName: string;
clientId: string | null;
clientName: string | null;
lineId: string;
chapter: string | null;
seniority: string | null;
roleName: string | null;
costRateCents: number;
billRateCents: number | null;
score: number;
}> = [];
for (const card of rateCards) {
for (const line of card.lines) {
let score = 0;
let mismatch = false;
if (roleId && line.role) {
if (line.role.id === roleId) score += 4;
else mismatch = true;
}
if (input.chapter && line.chapter) {
if (line.chapter.toLowerCase() === input.chapter.toLowerCase()) score += 2;
else mismatch = true;
}
if (input.seniority && line.seniority) {
if (line.seniority.toLowerCase() === input.seniority.toLowerCase()) score += 1;
else mismatch = true;
}
if (input.clientId && card.client?.id === input.clientId) score += 3;
if (!mismatch) {
scoredLines.push({
rateCardName: card.name,
clientId: card.client?.id ?? null,
clientName: card.client?.name ?? null,
lineId: line.id,
chapter: line.chapter,
seniority: line.seniority,
roleName: line.role?.name ?? null,
costRateCents: line.costRateCents,
billRateCents: line.billRateCents ?? null,
score,
});
}
}
}
scoredLines.sort((a, b) => b.score - a.score);
return {
bestMatch: scoredLines[0] ?? null,
alternatives: scoredLines.slice(1, 4),
totalCandidates: scoredLines.length,
};
}
export const rateCardRouter = createTRPCRouter({
list: controllerProcedure
.input(
@@ -92,6 +205,131 @@ export const rateCardRouter = createTRPCRouter({
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 }) => {
const effectiveAt = input.date ?? new Date();
if (input.resourceId) {
const resource = await findUniqueOrThrow(
ctx.db.resource.findUnique({
where: { id: input.resourceId },
select: {
id: true,
displayName: true,
chapter: true,
areaRole: { select: { name: true } },
},
}),
"Resource",
);
const resolved = await lookupBestRateMatch(ctx.db, {
...(resource.chapter ? { chapter: resource.chapter } : {}),
...(resource.areaRole?.name ? { roleName: resource.areaRole.name } : {}),
});
if (resolved.bestMatch) {
return {
rateCard: resolved.bestMatch.rateCardName,
resource: resource.displayName,
rate: fmtEur(resolved.bestMatch.costRateCents),
rateCents: resolved.bestMatch.costRateCents,
matchedBy: resolved.bestMatch.roleName ? `role: ${resolved.bestMatch.roleName}` : "best_match",
};
}
}
if (input.roleName) {
const match = await lookupBestRateMatch(ctx.db, { roleName: input.roleName });
if (match.bestMatch) {
return {
rateCard: match.bestMatch.rateCardName,
rate: fmtEur(match.bestMatch.costRateCents),
rateCents: match.bestMatch.costRateCents,
matchedBy: match.bestMatch.roleName ? `role: ${match.bestMatch.roleName}` : "best_match",
alternatives: match.alternatives.map((alternative) => ({
rateCard: alternative.rateCardName,
role: alternative.roleName,
chapter: alternative.chapter,
seniority: alternative.seniority,
costRate: fmtEur(alternative.costRateCents),
billRate: alternative.billRateCents != null ? fmtEur(alternative.billRateCents) : null,
})),
};
}
if (match.totalCandidates === 0) {
return { error: "No matching rate card line found." };
}
}
const cards = await ctx.db.rateCard.findMany({
where: {
isActive: true,
OR: [
{ effectiveFrom: null },
{ effectiveFrom: { lte: effectiveAt } },
],
AND: [
{
OR: [
{ effectiveTo: null },
{ effectiveTo: { gte: effectiveAt } },
],
},
],
},
include: {
_count: { select: { lines: true } },
client: { select: { id: true, name: true, code: true } },
},
orderBy: [{ isActive: "desc" }, { effectiveFrom: "desc" }, { name: "asc" }],
});
const card = cards[0];
if (!card) {
return { error: "No active rate card found for the given date." };
}
const detail = await findUniqueOrThrow(
ctx.db.rateCard.findUnique({
where: { id: card.id },
include: {
client: { select: { id: true, name: true, code: true } },
lines: {
select: lineSelect,
orderBy: [{ chapter: "asc" }, { seniority: "asc" }, { createdAt: "asc" }],
},
},
}),
"Rate card",
);
return {
rateCard: detail.name,
lines: detail.lines.map((line) => ({
role: line.role?.name ?? null,
seniority: line.seniority,
chapter: line.chapter,
location: line.location,
costRate: fmtEur(line.costRateCents),
billRate: line.billRateCents != null ? fmtEur(line.billRateCents) : null,
})),
};
}),
create: managerProcedure
.input(CreateRateCardSchema)
.mutation(async ({ ctx, input }) => {
@@ -362,7 +600,7 @@ export const rateCardRouter = createTRPCRouter({
// ─── Rate resolution ───────────────────────────────────────────────────────
resolveRate: controllerProcedure
resolveRateLine: controllerProcedure
.input(z.object({
rateCardId: z.string(),
roleId: z.string().optional(),