perf(api): eliminate 3 N+1 query patterns

- timeline-holiday-load-support: deduplicate getResolvedCalendarHolidays
  by location key so resources sharing the same country/state/city resolve
  holidays once instead of per-resource
- rate-card-lookup: add lookupRatesBatch that loads rate card lines once
  and scores locally per demand line, replacing per-line DB round-trips
  in estimate-demand-lines autoFillDemandLineRates
- config-readmodels: include _count in utilization-category list query
  instead of calling getById per category for project counts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-11 22:59:45 +02:00
parent dd2c9c0f88
commit 5a4836d292
8 changed files with 727 additions and 571 deletions
@@ -43,17 +43,9 @@ describe("assistant master data management and utilization read tools", () => {
description: "Client work", description: "Client work",
isActive: true, isActive: true,
sortOrder: 1, sortOrder: 1,
_count: { projects: 3 },
}, },
]), ]),
findUnique: vi.fn().mockResolvedValue({
id: "util_billable",
code: "BILLABLE",
name: "Billable",
description: "Client work",
isActive: true,
sortOrder: 1,
_count: { projects: 3 },
}),
}, },
}; };
const ctx = createToolContext(db, { const ctx = createToolContext(db, {
@@ -71,9 +63,6 @@ describe("assistant master data management and utilization read tools", () => {
expect(db.utilizationCategory.findMany).toHaveBeenCalledWith({ expect(db.utilizationCategory.findMany).toHaveBeenCalledWith({
where: {}, where: {},
orderBy: { sortOrder: "asc" }, orderBy: { sortOrder: "asc" },
});
expect(db.utilizationCategory.findUnique).toHaveBeenCalledWith({
where: { id: "util_billable" },
include: { _count: { select: { projects: true } } }, include: { _count: { select: { projects: true } } },
}); });
@@ -37,11 +37,13 @@ function createUnauthenticatedContext(db: Record<string, unknown>) {
describe("master-data router authorization", () => { describe("master-data router authorization", () => {
it("requires planning read access for blueprint summaries with project counts", async () => { it("requires planning read access for blueprint summaries with project counts", async () => {
const findMany = vi.fn(); const findMany = vi.fn();
const caller = createCallerFactory(blueprintRouter)(createProtectedContext({ const caller = createCallerFactory(blueprintRouter)(
createProtectedContext({
blueprint: { blueprint: {
findMany, findMany,
}, },
})); }),
);
await expect(caller.listSummaries()).rejects.toMatchObject({ await expect(caller.listSummaries()).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -59,13 +61,18 @@ describe("master-data router authorization", () => {
_count: { projects: 4 }, _count: { projects: 4 },
}, },
]); ]);
const caller = createCallerFactory(blueprintRouter)(createProtectedContext({ const caller = createCallerFactory(blueprintRouter)(
createProtectedContext(
{
blueprint: { blueprint: {
findMany, findMany,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const result = await caller.listSummaries(); const result = await caller.listSummaries();
@@ -85,19 +92,23 @@ describe("master-data router authorization", () => {
const findMany = vi.fn(); const findMany = vi.fn();
const findUnique = vi.fn(); const findUnique = vi.fn();
const findFirst = vi.fn(); const findFirst = vi.fn();
const caller = createCallerFactory(blueprintRouter)(createProtectedContext({ const caller = createCallerFactory(blueprintRouter)(
createProtectedContext({
blueprint: { blueprint: {
findMany, findMany,
findUnique, findUnique,
findFirst, findFirst,
}, },
})); }),
);
await expect(caller.list({ isActive: true })).rejects.toMatchObject({ await expect(caller.list({ isActive: true })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Planning read access required", message: "Planning read access required",
}); });
await expect(caller.getByIdentifier({ identifier: "Consulting Blueprint" })).rejects.toMatchObject({ await expect(
caller.getByIdentifier({ identifier: "Consulting Blueprint" }),
).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Planning read access required", message: "Planning read access required",
}); });
@@ -121,7 +132,8 @@ describe("master-data router authorization", () => {
isActive: true, isActive: true,
}, },
]); ]);
const getByIdFindUnique = vi.fn() const getByIdFindUnique = vi
.fn()
.mockResolvedValueOnce({ .mockResolvedValueOnce({
id: "bp_1", id: "bp_1",
name: "Consulting Blueprint", name: "Consulting Blueprint",
@@ -145,15 +157,20 @@ describe("master-data router authorization", () => {
rolePresets: [], rolePresets: [],
isActive: true, isActive: true,
}); });
const caller = createCallerFactory(blueprintRouter)(createProtectedContext({ const caller = createCallerFactory(blueprintRouter)(
createProtectedContext(
{
blueprint: { blueprint: {
findMany: listFindMany, findMany: listFindMany,
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
findFirst: getByIdentifierFindFirst, findFirst: getByIdentifierFindFirst,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const listResult = await caller.list({ target: BlueprintTarget.PROJECT, isActive: true }); const listResult = await caller.list({ target: BlueprintTarget.PROJECT, isActive: true });
const byIdResult = await caller.getById({ id: "bp_1" }); const byIdResult = await caller.getById({ id: "bp_1" });
@@ -177,22 +194,30 @@ describe("master-data router authorization", () => {
it("requires authenticated planning access for global blueprint field definitions", async () => { it("requires authenticated planning access for global blueprint field definitions", async () => {
const findMany = vi.fn(); const findMany = vi.fn();
const unauthenticatedCaller = createCallerFactory(blueprintRouter)(createUnauthenticatedContext({ const unauthenticatedCaller = createCallerFactory(blueprintRouter)(
createUnauthenticatedContext({
blueprint: { blueprint: {
findMany, findMany,
}, },
})); }),
const authenticatedCaller = createCallerFactory(blueprintRouter)(createProtectedContext({ );
const authenticatedCaller = createCallerFactory(blueprintRouter)(
createProtectedContext({
blueprint: { blueprint: {
findMany, findMany,
}, },
})); }),
);
await expect(unauthenticatedCaller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT })).rejects.toMatchObject({ await expect(
unauthenticatedCaller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT }),
).rejects.toMatchObject({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Authentication required", message: "Authentication required",
}); });
await expect(authenticatedCaller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT })).rejects.toMatchObject({ await expect(
authenticatedCaller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT }),
).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
message: "Planning read access required", message: "Planning read access required",
}); });
@@ -211,13 +236,18 @@ describe("master-data router authorization", () => {
], ],
}, },
]); ]);
const caller = createCallerFactory(blueprintRouter)(createProtectedContext({ const caller = createCallerFactory(blueprintRouter)(
createProtectedContext(
{
blueprint: { blueprint: {
findMany, findMany,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const result = await caller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT }); const result = await caller.getGlobalFieldDefs({ target: BlueprintTarget.PROJECT });
@@ -254,20 +284,24 @@ describe("master-data router authorization", () => {
metroCities: [{ id: "city_ber", name: "Berlin", countryId: "country_de" }], metroCities: [{ id: "city_ber", name: "Berlin", countryId: "country_de" }],
}, },
]); ]);
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext({
country: { country: {
findMany, findMany,
}, },
})); }),
);
const result = await caller.list({ isActive: true }); const result = await caller.list({ isActive: true });
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ expect(findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { isActive: true }, where: { isActive: true },
include: { metroCities: { orderBy: { name: "asc" } } }, include: { metroCities: { orderBy: { name: "asc" } } },
orderBy: { name: "asc" }, orderBy: { name: "asc" },
})); }),
);
}); });
it("keeps minimal country lookups available to authenticated users", async () => { it("keeps minimal country lookups available to authenticated users", async () => {
@@ -278,12 +312,14 @@ describe("master-data router authorization", () => {
isActive: true, isActive: true,
dailyWorkingHours: 8, dailyWorkingHours: 8,
}); });
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext({
country: { country: {
findUnique: vi.fn().mockResolvedValue(null), findUnique: vi.fn().mockResolvedValue(null),
findFirst, findFirst,
}, },
})); }),
);
const result = await caller.resolveByIdentifier({ identifier: "de" }); const result = await caller.resolveByIdentifier({ identifier: "de" });
@@ -303,11 +339,13 @@ describe("master-data router authorization", () => {
name: "Munich", name: "Munich",
countryId: "country_de", countryId: "country_de",
}); });
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext({
metroCity: { metroCity: {
findUnique, findUnique,
}, },
})); }),
);
const result = await caller.getCityById({ id: "city_muc" }); const result = await caller.getCityById({ id: "city_muc" });
@@ -323,12 +361,14 @@ describe("master-data router authorization", () => {
}); });
it("requires resource overview access for detailed country reads with resource counts", async () => { it("requires resource overview access for detailed country reads with resource counts", async () => {
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext({
country: { country: {
findFirst: vi.fn(), findFirst: vi.fn(),
findUnique: vi.fn(), findUnique: vi.fn(),
}, },
})); }),
);
await expect(caller.getByIdentifier({ identifier: "DE" })).rejects.toMatchObject({ await expect(caller.getByIdentifier({ identifier: "DE" })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -351,24 +391,31 @@ describe("master-data router authorization", () => {
metroCities: [{ id: "city_muc", name: "Munich", countryId: "country_de" }], metroCities: [{ id: "city_muc", name: "Munich", countryId: "country_de" }],
_count: { resources: 12 }, _count: { resources: 12 },
}); });
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext(
{
country: { country: {
findUnique: vi.fn().mockResolvedValue(null), findUnique: vi.fn().mockResolvedValue(null),
findFirst, findFirst,
}, },
}, { },
{
granted: [PermissionKey.VIEW_ALL_RESOURCES], granted: [PermissionKey.VIEW_ALL_RESOURCES],
})); },
),
);
const result = await caller.getByIdentifier({ identifier: "DE" }); const result = await caller.getByIdentifier({ identifier: "DE" });
expect(result._count.resources).toBe(12); expect(result._count.resources).toBe(12);
expect(findFirst).toHaveBeenCalledWith(expect.objectContaining({ expect(findFirst).toHaveBeenCalledWith(
expect.objectContaining({
include: expect.objectContaining({ include: expect.objectContaining({
metroCities: expect.any(Object), metroCities: expect.any(Object),
_count: expect.any(Object), _count: expect.any(Object),
}), }),
})); }),
);
}); });
it("allows detailed country reads for users with manage-resources access", async () => { it("allows detailed country reads for users with manage-resources access", async () => {
@@ -382,13 +429,18 @@ describe("master-data router authorization", () => {
metroCities: [], metroCities: [],
_count: { resources: 4 }, _count: { resources: 4 },
}); });
const caller = createCallerFactory(countryRouter)(createProtectedContext({ const caller = createCallerFactory(countryRouter)(
createProtectedContext(
{
country: { country: {
findUnique, findUnique,
}, },
}, { },
{
granted: [PermissionKey.MANAGE_RESOURCES], granted: [PermissionKey.MANAGE_RESOURCES],
})); },
),
);
const result = await caller.getById({ id: "country_de" }); const result = await caller.getById({ id: "country_de" });
@@ -397,21 +449,21 @@ describe("master-data router authorization", () => {
}); });
it("keeps minimal org-unit lookups available to authenticated users", async () => { it("keeps minimal org-unit lookups available to authenticated users", async () => {
const findFirst = vi.fn() const findFirst = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({
id: "ou_1", id: "ou_1",
name: "Delivery", name: "Delivery",
shortName: "DEL", shortName: "DEL",
level: 5, level: 5,
isActive: true, isActive: true,
}); });
const caller = createCallerFactory(orgUnitRouter)(createProtectedContext({ const caller = createCallerFactory(orgUnitRouter)(
createProtectedContext({
orgUnit: { orgUnit: {
findUnique: vi.fn().mockResolvedValue(null), findUnique: vi.fn().mockResolvedValue(null),
findFirst, findFirst,
}, },
})); }),
);
const result = await caller.resolveByIdentifier({ identifier: "DEL" }); const result = await caller.resolveByIdentifier({ identifier: "DEL" });
@@ -426,11 +478,13 @@ describe("master-data router authorization", () => {
it("requires resource overview access for org-unit list and tree reads", async () => { it("requires resource overview access for org-unit list and tree reads", async () => {
const findMany = vi.fn(); const findMany = vi.fn();
const caller = createCallerFactory(orgUnitRouter)(createProtectedContext({ const caller = createCallerFactory(orgUnitRouter)(
createProtectedContext({
orgUnit: { orgUnit: {
findMany, findMany,
}, },
})); }),
);
await expect(caller.list({ level: 5, isActive: true })).rejects.toMatchObject({ await expect(caller.list({ level: 5, isActive: true })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -445,12 +499,14 @@ describe("master-data router authorization", () => {
}); });
it("requires resource overview access for detailed org-unit reads with staffing counts", async () => { it("requires resource overview access for detailed org-unit reads with staffing counts", async () => {
const caller = createCallerFactory(orgUnitRouter)(createProtectedContext({ const caller = createCallerFactory(orgUnitRouter)(
createProtectedContext({
orgUnit: { orgUnit: {
findFirst: vi.fn(), findFirst: vi.fn(),
findUnique: vi.fn(), findUnique: vi.fn(),
}, },
})); }),
);
await expect(caller.getByIdentifier({ identifier: "Delivery" })).rejects.toMatchObject({ await expect(caller.getByIdentifier({ identifier: "Delivery" })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -473,21 +529,28 @@ describe("master-data router authorization", () => {
isActive: true, isActive: true,
_count: { resources: 7 }, _count: { resources: 7 },
}); });
const caller = createCallerFactory(orgUnitRouter)(createProtectedContext({ const caller = createCallerFactory(orgUnitRouter)(
createProtectedContext(
{
orgUnit: { orgUnit: {
findUnique: vi.fn().mockResolvedValue(null), findUnique: vi.fn().mockResolvedValue(null),
findFirst, findFirst,
}, },
}, { },
{
granted: [PermissionKey.VIEW_ALL_RESOURCES], granted: [PermissionKey.VIEW_ALL_RESOURCES],
})); },
),
);
const result = await caller.getByIdentifier({ identifier: "Delivery" }); const result = await caller.getByIdentifier({ identifier: "Delivery" });
expect(result._count.resources).toBe(7); expect(result._count.resources).toBe(7);
expect(findFirst).toHaveBeenCalledWith(expect.objectContaining({ expect(findFirst).toHaveBeenCalledWith(
expect.objectContaining({
include: { _count: { select: { resources: true } } }, include: { _count: { select: { resources: true } } },
})); }),
);
}); });
it("allows org-unit list and tree reads for users with resource overview access", async () => { it("allows org-unit list and tree reads for users with resource overview access", async () => {
@@ -517,15 +580,21 @@ describe("master-data router authorization", () => {
updatedAt: new Date("2026-03-01T00:00:00.000Z"), updatedAt: new Date("2026-03-01T00:00:00.000Z"),
}, },
]); ]);
const caller = createCallerFactory(orgUnitRouter)(createProtectedContext({ const caller = createCallerFactory(orgUnitRouter)(
createProtectedContext(
{
orgUnit: { orgUnit: {
findMany: vi.fn() findMany: vi
.fn()
.mockImplementationOnce(listFindMany) .mockImplementationOnce(listFindMany)
.mockImplementationOnce(treeFindMany), .mockImplementationOnce(treeFindMany),
}, },
}, { },
{
granted: [PermissionKey.MANAGE_RESOURCES], granted: [PermissionKey.MANAGE_RESOURCES],
})); },
),
);
const listResult = await caller.list({ level: 5, isActive: true }); const listResult = await caller.list({ level: 5, isActive: true });
const treeResult = await caller.getTree({ isActive: true }); const treeResult = await caller.getTree({ isActive: true });
@@ -549,21 +618,21 @@ describe("master-data router authorization", () => {
}); });
it("keeps minimal client lookups available to authenticated users", async () => { it("keeps minimal client lookups available to authenticated users", async () => {
const findUnique = vi.fn() const findUnique = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({
id: "client_1", id: "client_1",
name: "Acme Studios", name: "Acme Studios",
code: "ACME", code: "ACME",
parentId: null, parentId: null,
isActive: true, isActive: true,
}); });
const caller = createCallerFactory(clientRouter)(createProtectedContext({ const caller = createCallerFactory(clientRouter)(
createProtectedContext({
client: { client: {
findUnique, findUnique,
findFirst: vi.fn(), findFirst: vi.fn(),
}, },
})); }),
);
const result = await caller.resolveByIdentifier({ identifier: "ACME" }); const result = await caller.resolveByIdentifier({ identifier: "ACME" });
@@ -578,11 +647,13 @@ describe("master-data router authorization", () => {
it("requires planning read access for client list and tree reads", async () => { it("requires planning read access for client list and tree reads", async () => {
const findMany = vi.fn(); const findMany = vi.fn();
const caller = createCallerFactory(clientRouter)(createProtectedContext({ const caller = createCallerFactory(clientRouter)(
createProtectedContext({
client: { client: {
findMany, findMany,
}, },
})); }),
);
await expect(caller.list({ isActive: true })).rejects.toMatchObject({ await expect(caller.list({ isActive: true })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -597,12 +668,14 @@ describe("master-data router authorization", () => {
}); });
it("requires planning read access for detailed client reads with project counts", async () => { it("requires planning read access for detailed client reads with project counts", async () => {
const caller = createCallerFactory(clientRouter)(createProtectedContext({ const caller = createCallerFactory(clientRouter)(
createProtectedContext({
client: { client: {
findFirst: vi.fn(), findFirst: vi.fn(),
findUnique: vi.fn(), findUnique: vi.fn(),
}, },
})); }),
);
await expect(caller.getByIdentifier({ identifier: "Acme" })).rejects.toMatchObject({ await expect(caller.getByIdentifier({ identifier: "Acme" })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -642,7 +715,8 @@ describe("master-data router authorization", () => {
updatedAt: new Date("2026-03-01T00:00:00.000Z"), updatedAt: new Date("2026-03-01T00:00:00.000Z"),
}, },
]); ]);
const getByIdFindUnique = vi.fn() const getByIdFindUnique = vi
.fn()
.mockResolvedValueOnce({ .mockResolvedValueOnce({
id: "client_1", id: "client_1",
name: "Acme Studios", name: "Acme Studios",
@@ -670,17 +744,23 @@ describe("master-data router authorization", () => {
updatedAt: new Date("2026-03-01T00:00:00.000Z"), updatedAt: new Date("2026-03-01T00:00:00.000Z"),
_count: { children: 1, projects: 4 }, _count: { children: 1, projects: 4 },
}); });
const caller = createCallerFactory(clientRouter)(createProtectedContext({ const caller = createCallerFactory(clientRouter)(
createProtectedContext(
{
client: { client: {
findMany: vi.fn() findMany: vi
.fn()
.mockImplementationOnce(listFindMany) .mockImplementationOnce(listFindMany)
.mockImplementationOnce(treeFindMany), .mockImplementationOnce(treeFindMany),
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
findFirst: getByIdentifierFindFirst, findFirst: getByIdentifierFindFirst,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const listResult = await caller.list({ isActive: true, search: "Acme" }); const listResult = await caller.list({ isActive: true, search: "Acme" });
const treeResult = await caller.getTree({ isActive: true }); const treeResult = await caller.getTree({ isActive: true });
@@ -720,21 +800,25 @@ describe("master-data router authorization", () => {
_count: { select: { projects: true, children: true } }, _count: { select: { projects: true, children: true } },
}, },
}); });
expect(getByIdentifierFindFirst).toHaveBeenCalledWith(expect.objectContaining({ expect(getByIdentifierFindFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { name: { equals: "Acme Studios", mode: "insensitive" } }, where: { name: { equals: "Acme Studios", mode: "insensitive" } },
include: { _count: { select: { projects: true, children: true } } }, include: { _count: { select: { projects: true, children: true } } },
})); }),
);
}); });
it("requires planning read access for utilization-category reads with project counts", async () => { it("requires planning read access for utilization-category reads with project counts", async () => {
const listFindMany = vi.fn(); const listFindMany = vi.fn();
const getByIdFindUnique = vi.fn(); const getByIdFindUnique = vi.fn();
const caller = createCallerFactory(utilizationCategoryRouter)(createProtectedContext({ const caller = createCallerFactory(utilizationCategoryRouter)(
createProtectedContext({
utilizationCategory: { utilizationCategory: {
findMany: listFindMany, findMany: listFindMany,
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
}, },
})); }),
);
await expect(caller.list({ isActive: true })).rejects.toMatchObject({ await expect(caller.list({ isActive: true })).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -771,14 +855,19 @@ describe("master-data router authorization", () => {
isActive: true, isActive: true,
_count: { projects: 12 }, _count: { projects: 12 },
}); });
const caller = createCallerFactory(utilizationCategoryRouter)(createProtectedContext({ const caller = createCallerFactory(utilizationCategoryRouter)(
createProtectedContext(
{
utilizationCategory: { utilizationCategory: {
findMany: listFindMany, findMany: listFindMany,
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const listResult = await caller.list({ isActive: true }); const listResult = await caller.list({ isActive: true });
const byIdResult = await caller.getById({ id: "util_chargeable" }); const byIdResult = await caller.getById({ id: "util_chargeable" });
@@ -788,6 +877,7 @@ describe("master-data router authorization", () => {
expect(listFindMany).toHaveBeenCalledWith({ expect(listFindMany).toHaveBeenCalledWith({
where: { isActive: true }, where: { isActive: true },
orderBy: { sortOrder: "asc" }, orderBy: { sortOrder: "asc" },
include: { _count: { select: { projects: true } } },
}); });
expect(getByIdFindUnique).toHaveBeenCalledWith({ expect(getByIdFindUnique).toHaveBeenCalledWith({
where: { id: "util_chargeable" }, where: { id: "util_chargeable" },
@@ -798,12 +888,14 @@ describe("master-data router authorization", () => {
it("requires planning read access for management-level reads", async () => { it("requires planning read access for management-level reads", async () => {
const listFindMany = vi.fn(); const listFindMany = vi.fn();
const getByIdFindUnique = vi.fn(); const getByIdFindUnique = vi.fn();
const caller = createCallerFactory(managementLevelRouter)(createProtectedContext({ const caller = createCallerFactory(managementLevelRouter)(
createProtectedContext({
managementLevelGroup: { managementLevelGroup: {
findMany: listFindMany, findMany: listFindMany,
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
}, },
})); }),
);
await expect(caller.listGroups()).rejects.toMatchObject({ await expect(caller.listGroups()).rejects.toMatchObject({
code: "FORBIDDEN", code: "FORBIDDEN",
@@ -836,14 +928,19 @@ describe("master-data router authorization", () => {
levels: [{ id: "mgmt_level_1", name: "Senior Team Lead" }], levels: [{ id: "mgmt_level_1", name: "Senior Team Lead" }],
_count: { resources: 6 }, _count: { resources: 6 },
}); });
const caller = createCallerFactory(managementLevelRouter)(createProtectedContext({ const caller = createCallerFactory(managementLevelRouter)(
createProtectedContext(
{
managementLevelGroup: { managementLevelGroup: {
findMany: listFindMany, findMany: listFindMany,
findUnique: getByIdFindUnique, findUnique: getByIdFindUnique,
}, },
}, { },
{
granted: [PermissionKey.VIEW_PLANNING], granted: [PermissionKey.VIEW_PLANNING],
})); },
),
);
const listResult = await caller.listGroups(); const listResult = await caller.listGroups();
const detailResult = await caller.getGroupById({ id: "mgmt_group_1" }); const detailResult = await caller.getGroupById({ id: "mgmt_group_1" });
@@ -48,6 +48,7 @@ describe("utilization category router", () => {
expect(findMany).toHaveBeenCalledWith({ expect(findMany).toHaveBeenCalledWith({
where: { isActive: true }, where: { isActive: true },
orderBy: { sortOrder: "asc" }, orderBy: { sortOrder: "asc" },
include: { _count: { select: { projects: true } } },
}); });
}); });
+97 -76
View File
@@ -13,13 +13,13 @@
*/ */
export interface RateCardLookupParams { export interface RateCardLookupParams {
clientId?: string | null; clientId?: string | null | undefined;
chapter?: string | null; chapter?: string | null | undefined;
roleId?: string | null; roleId?: string | null | undefined;
seniority?: string | null; seniority?: string | null | undefined;
location?: string | null; location?: string | null | undefined;
workType?: string | null; workType?: string | null | undefined;
effectiveDate?: Date | null; effectiveDate?: Date | null | undefined;
} }
export interface RateCardLookupResult { export interface RateCardLookupResult {
@@ -49,46 +49,7 @@ interface RateCardLineRow {
}; };
} }
/** const RATE_CARD_LINE_SELECT = {
* Look up the best-matching rate card line for a given set of criteria.
* Returns null when no active rate card line matches.
*/
export async function lookupRate(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
db: any,
params: RateCardLookupParams,
): Promise<RateCardLookupResult | null> {
const effectiveDate = params.effectiveDate ?? new Date();
// Build rate card filter: active cards, within effective date range
const rateCardWhere: Record<string, unknown> = {
isActive: true,
OR: [
{ effectiveFrom: null },
{ effectiveFrom: { lte: effectiveDate } },
],
AND: [
{
OR: [
{ effectiveTo: null },
{ effectiveTo: { gte: effectiveDate } },
],
},
],
};
// If we have a clientId, look for both client-specific and default (null client) cards
if (params.clientId) {
rateCardWhere.clientId = { in: [params.clientId, null] };
}
// If no clientId, only look at default (null client) cards
// (don't pass clientId filter at all to keep the OR above valid)
const lines = (await db.rateCardLine.findMany({
where: {
rateCard: rateCardWhere,
},
select: {
id: true, id: true,
rateCardId: true, rateCardId: true,
roleId: true, roleId: true,
@@ -106,73 +67,133 @@ export async function lookupRate(
clientId: true, clientId: true,
}, },
}, },
}, } as const;
})) as RateCardLineRow[];
if (lines.length === 0) return null; function scoreLine(
line: RateCardLineRow,
// Score each line. Higher = better match. params: RateCardLookupParams,
type ScoredLine = { line: RateCardLineRow; score: number; mismatch: boolean }; ): { score: number; mismatch: boolean } {
const scored: ScoredLine[] = lines.map((line) => {
let score = 0; let score = 0;
let mismatch = false; let mismatch = false;
// Client specificity: client-specific cards get a large bonus
if (params.clientId && line.rateCard.clientId === params.clientId) { if (params.clientId && line.rateCard.clientId === params.clientId) {
score += 100; score += 100;
} else if (params.clientId && line.rateCard.clientId != null) { } else if (params.clientId && line.rateCard.clientId != null) {
// Different client entirely => disqualify
mismatch = true; mismatch = true;
} }
// Default card (null client) gets no bonus but is a valid fallback
// Role match
if (params.roleId && line.roleId) { if (params.roleId && line.roleId) {
if (line.roleId === params.roleId) score += 16; if (line.roleId === params.roleId) score += 16;
else mismatch = true; else mismatch = true;
} }
// Chapter match
if (params.chapter && line.chapter) { if (params.chapter && line.chapter) {
if (line.chapter === params.chapter) score += 8; if (line.chapter === params.chapter) score += 8;
else mismatch = true; else mismatch = true;
} }
// Seniority match
if (params.seniority && line.seniority) { if (params.seniority && line.seniority) {
if (line.seniority === params.seniority) score += 4; if (line.seniority === params.seniority) score += 4;
else mismatch = true; else mismatch = true;
} }
// Location match
if (params.location && line.location) { if (params.location && line.location) {
if (line.location === params.location) score += 2; if (line.location === params.location) score += 2;
else mismatch = true; else mismatch = true;
} }
// Work type match
if (params.workType && line.workType) { if (params.workType && line.workType) {
if (line.workType === params.workType) score += 1; if (line.workType === params.workType) score += 1;
else mismatch = true; else mismatch = true;
} }
return { line, score, mismatch }; return { score, mismatch };
}); }
// Filter out mismatched lines and sort by score descending function findBestMatch(
const candidates = scored lines: RateCardLineRow[],
.filter((s) => !s.mismatch) params: RateCardLookupParams,
.sort((a, b) => b.score - a.score); ): RateCardLookupResult | null {
if (lines.length === 0) return null;
const best = candidates[0]; let bestLine: RateCardLineRow | null = null;
if (!best) return null; let bestScore = -1;
for (const line of lines) {
const { score, mismatch } = scoreLine(line, params);
if (!mismatch && score > bestScore) {
bestScore = score;
bestLine = line;
}
}
if (!bestLine) return null;
return { return {
costRateCents: best.line.costRateCents, costRateCents: bestLine.costRateCents,
billRateCents: best.line.billRateCents ?? 0, billRateCents: bestLine.billRateCents ?? 0,
currency: best.line.rateCard.currency, currency: bestLine.rateCard.currency,
rateCardId: best.line.rateCard.id, rateCardId: bestLine.rateCard.id,
rateCardLineId: best.line.id, rateCardLineId: bestLine.id,
rateCardName: best.line.rateCard.name, rateCardName: bestLine.rateCard.name,
}; };
} }
function buildRateCardWhere(
clientId: string | null | undefined,
effectiveDate: Date,
): Record<string, unknown> {
const where: Record<string, unknown> = {
isActive: true,
OR: [{ effectiveFrom: null }, { effectiveFrom: { lte: effectiveDate } }],
AND: [
{
OR: [{ effectiveTo: null }, { effectiveTo: { gte: effectiveDate } }],
},
],
};
if (clientId) {
where.clientId = { in: [clientId, null] };
}
return where;
}
/**
* Look up the best-matching rate card line for a given set of criteria.
* Returns null when no active rate card line matches.
*/
export async function lookupRate(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
db: any,
params: RateCardLookupParams,
): Promise<RateCardLookupResult | null> {
const effectiveDate = params.effectiveDate ?? new Date();
const lines = (await db.rateCardLine.findMany({
where: { rateCard: buildRateCardWhere(params.clientId, effectiveDate) },
select: RATE_CARD_LINE_SELECT,
})) as RateCardLineRow[];
return findBestMatch(lines, params);
}
/**
* Batch-optimized rate lookup: loads rate card lines once, then scores
* each param set against the cached lines. Use this when looking up rates
* for multiple demand lines sharing the same clientId/effectiveDate.
*/
export async function lookupRatesBatch(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
db: any,
clientId: string | null | undefined,
paramsList: RateCardLookupParams[],
): Promise<(RateCardLookupResult | null)[]> {
if (paramsList.length === 0) return [];
const effectiveDate = paramsList[0]?.effectiveDate ?? new Date();
const lines = (await db.rateCardLine.findMany({
where: { rateCard: buildRateCardWhere(clientId, effectiveDate) },
select: RATE_CARD_LINE_SELECT,
})) as RateCardLineRow[];
return paramsList.map((params) => findBestMatch(lines, { ...params, clientId }));
}
@@ -4,26 +4,29 @@ import { withToolAccess, type ToolContext, type ToolDef, type ToolExecutor } fro
type ConfigReadmodelsDeps = { type ConfigReadmodelsDeps = {
createManagementLevelCaller: (ctx: TRPCContext) => { createManagementLevelCaller: (ctx: TRPCContext) => {
listGroups: () => Promise<Array<{ listGroups: () => Promise<
Array<{
id: string; id: string;
name: string; name: string;
targetPercentage: number | null; targetPercentage: number | null;
levels: Array<{ id: string; name: string }>; levels: Array<{ id: string; name: string }>;
}>>; }>
>;
}; };
createUtilizationCategoryCaller: (ctx: TRPCContext) => { createUtilizationCategoryCaller: (ctx: TRPCContext) => {
list: () => Promise<Array<{ list: () => Promise<
Array<{
id: string; id: string;
code: string; code: string;
name: string; name: string;
description: string | null; description: string | null;
}>>;
getById: (params: { id: string }) => Promise<{
_count: { projects: number }; _count: { projects: number };
}>; }>
>;
}; };
createCalculationRuleCaller: (ctx: TRPCContext) => { createCalculationRuleCaller: (ctx: TRPCContext) => {
list: () => Promise<Array<{ list: () => Promise<
Array<{
id: string; id: string;
name: string; name: string;
description: string | null; description: string | null;
@@ -39,10 +42,12 @@ type ConfigReadmodelsDeps = {
name: string; name: string;
shortCode: string; shortCode: string;
} | null; } | null;
}>>; }>
>;
}; };
createEffortRuleCaller: (ctx: TRPCContext) => { createEffortRuleCaller: (ctx: TRPCContext) => {
list: () => Promise<Array<{ list: () => Promise<
Array<{
name: string; name: string;
isDefault: boolean; isDefault: boolean;
rules: Array<{ rules: Array<{
@@ -55,10 +60,12 @@ type ConfigReadmodelsDeps = {
hoursPerUnit: number; hoursPerUnit: number;
sortOrder: number; sortOrder: number;
}>; }>;
}>>; }>
>;
}; };
createExperienceMultiplierCaller: (ctx: TRPCContext) => { createExperienceMultiplierCaller: (ctx: TRPCContext) => {
list: () => Promise<Array<{ list: () => Promise<
Array<{
name: string; name: string;
isDefault: boolean; isDefault: boolean;
rules: Array<{ rules: Array<{
@@ -73,12 +80,14 @@ type ConfigReadmodelsDeps = {
additionalEffortRatio: number | null; additionalEffortRatio: number | null;
sortOrder: number; sortOrder: number;
}>; }>;
}>>; }>
>;
}; };
createScopedCallerContext: (ctx: ToolContext) => TRPCContext; createScopedCallerContext: (ctx: ToolContext) => TRPCContext;
}; };
export const configReadmodelToolDefinitions: ToolDef[] = withToolAccess([ export const configReadmodelToolDefinitions: ToolDef[] = withToolAccess(
[
{ {
type: "function", type: "function",
function: { function: {
@@ -119,7 +128,8 @@ export const configReadmodelToolDefinitions: ToolDef[] = withToolAccess([
parameters: { type: "object", properties: {} }, parameters: { type: "object", properties: {} },
}, },
}, },
], { ],
{
list_management_levels: { list_management_levels: {
requiresPlanningRead: true, requiresPlanningRead: true,
}, },
@@ -135,7 +145,8 @@ export const configReadmodelToolDefinitions: ToolDef[] = withToolAccess([
list_experience_multipliers: { list_experience_multipliers: {
allowedSystemRoles: [SystemRole.ADMIN, SystemRole.MANAGER, SystemRole.CONTROLLER], allowedSystemRoles: [SystemRole.ADMIN, SystemRole.MANAGER, SystemRole.CONTROLLER],
}, },
}); },
);
export function createConfigReadmodelExecutors( export function createConfigReadmodelExecutors(
deps: ConfigReadmodelsDeps, deps: ConfigReadmodelsDeps,
@@ -155,19 +166,13 @@ export function createConfigReadmodelExecutors(
async list_utilization_categories(_params: Record<string, never>, ctx: ToolContext) { async list_utilization_categories(_params: Record<string, never>, ctx: ToolContext) {
const caller = deps.createUtilizationCategoryCaller(deps.createScopedCallerContext(ctx)); const caller = deps.createUtilizationCategoryCaller(deps.createScopedCallerContext(ctx));
const categories = await caller.list(); const categories = await caller.list();
const categoriesWithCounts = await Promise.all(
categories.map(async (category) => ({
category,
projectCount: (await caller.getById({ id: category.id }))._count.projects,
})),
);
return categoriesWithCounts.map(({ category, projectCount }) => ({ return categories.map((category) => ({
id: category.id, id: category.id,
code: category.code, code: category.code,
name: category.name, name: category.name,
description: category.description, description: category.description,
projectCount, projectCount: category._count.projects,
})); }));
}, },
@@ -198,7 +203,8 @@ export function createConfigReadmodelExecutors(
async list_effort_rules(_params: Record<string, never>, ctx: ToolContext) { async list_effort_rules(_params: Record<string, never>, ctx: ToolContext) {
const caller = deps.createEffortRuleCaller(deps.createScopedCallerContext(ctx)); const caller = deps.createEffortRuleCaller(deps.createScopedCallerContext(ctx));
const ruleSets = await caller.list(); const ruleSets = await caller.list();
return ruleSets.flatMap((ruleSet) => ruleSet.rules.map((rule) => ({ return ruleSets.flatMap((ruleSet) =>
ruleSet.rules.map((rule) => ({
id: rule.id, id: rule.id,
description: rule.description, description: rule.description,
scopeType: rule.scopeType, scopeType: rule.scopeType,
@@ -211,13 +217,15 @@ export function createConfigReadmodelExecutors(
name: ruleSet.name, name: ruleSet.name,
isDefault: ruleSet.isDefault, isDefault: ruleSet.isDefault,
}, },
}))); })),
);
}, },
async list_experience_multipliers(_params: Record<string, never>, ctx: ToolContext) { async list_experience_multipliers(_params: Record<string, never>, ctx: ToolContext) {
const caller = deps.createExperienceMultiplierCaller(deps.createScopedCallerContext(ctx)); const caller = deps.createExperienceMultiplierCaller(deps.createScopedCallerContext(ctx));
const multiplierSets = await caller.list(); const multiplierSets = await caller.list();
return multiplierSets.flatMap((multiplierSet) => multiplierSet.rules.map((rule) => ({ return multiplierSets.flatMap((multiplierSet) =>
multiplierSet.rules.map((rule) => ({
id: rule.id, id: rule.id,
description: rule.description, description: rule.description,
chapter: rule.chapter, chapter: rule.chapter,
@@ -232,7 +240,8 @@ export function createConfigReadmodelExecutors(
name: multiplierSet.name, name: multiplierSet.name,
isDefault: multiplierSet.isDefault, isDefault: multiplierSet.isDefault,
}, },
}))); })),
);
}, },
}; };
} }
@@ -1,11 +1,9 @@
import { normalizeEstimateDemandLine, summarizeEstimateDemandLines } from "@capakraken/engine"; import { normalizeEstimateDemandLine, summarizeEstimateDemandLines } from "@capakraken/engine";
import { CreateEstimateSchema } from "@capakraken/shared"; import { CreateEstimateSchema } from "@capakraken/shared";
import { z } from "zod"; import { z } from "zod";
import { lookupRate } from "../lib/rate-card-lookup.js"; import { lookupRatesBatch } from "../lib/rate-card-lookup.js";
function buildComputedMetrics( function buildComputedMetrics(demandLines: z.infer<typeof CreateEstimateSchema>["demandLines"]) {
demandLines: z.infer<typeof CreateEstimateSchema>["demandLines"],
) {
const summary = summarizeEstimateDemandLines(demandLines); const summary = summarizeEstimateDemandLines(demandLines);
return [ return [
@@ -62,7 +60,9 @@ function normalizeDemandLines<
const snapshotsByResourceId = new Map( const snapshotsByResourceId = new Map(
input.resourceSnapshots input.resourceSnapshots
.filter( .filter(
(snapshot): snapshot is (typeof input.resourceSnapshots)[number] & { (
snapshot,
): snapshot is (typeof input.resourceSnapshots)[number] & {
resourceId: string; resourceId: string;
} => typeof snapshot.resourceId === "string" && snapshot.resourceId.length > 0, } => typeof snapshot.resourceId === "string" && snapshot.resourceId.length > 0,
) )
@@ -71,8 +71,7 @@ function normalizeDemandLines<
return input.demandLines.map((line) => return input.demandLines.map((line) =>
normalizeEstimateDemandLine(line, { normalizeEstimateDemandLine(line, {
resourceSnapshot: resourceSnapshot: line.resourceId != null ? snapshotsByResourceId.get(line.resourceId) : null,
line.resourceId != null ? snapshotsByResourceId.get(line.resourceId) : null,
defaultCurrency: baseCurrency, defaultCurrency: baseCurrency,
}), }),
); );
@@ -117,27 +116,44 @@ export async function autoFillDemandLineRates(
clientId = project?.clientId ?? null; clientId = project?.clientId ?? null;
} }
const autoFilledIndices: number[] = []; // Identify which lines need auto-fill and collect their lookup params
const enriched = await Promise.all( const needsLookup: {
demandLines.map(async (line, index) => { index: number;
params: { chapter: string | null; roleId: string | null };
}[] = [];
for (let i = 0; i < demandLines.length; i++) {
const line = demandLines[i]!;
const isDefaultRate = line.costRateCents === 0 && line.billRateCents === 0; const isDefaultRate = line.costRateCents === 0 && line.billRateCents === 0;
const hasExplicitSource = line.rateSource != null && line.rateSource.length > 0; const hasExplicitSource = line.rateSource != null && line.rateSource.length > 0;
if (!isDefaultRate || hasExplicitSource) { if (isDefaultRate && !hasExplicitSource) {
return line; needsLookup.push({
} index: i,
params: { chapter: line.chapter ?? null, roleId: line.roleId ?? null },
const result = await lookupRate(db, {
clientId,
chapter: line.chapter ?? null,
roleId: line.roleId ?? null,
}); });
if (!result) { }
return line;
} }
if (needsLookup.length === 0) {
return { demandLines, autoFilledIndices: [] };
}
// Single DB query for all rate card lines, scored locally per demand line
const results = await lookupRatesBatch(
db,
clientId,
needsLookup.map((entry) => entry.params),
);
const autoFilledIndices: number[] = [];
const enriched = [...demandLines];
for (let i = 0; i < needsLookup.length; i++) {
const result = results[i];
if (!result) continue;
const { index } = needsLookup[i]!;
autoFilledIndices.push(index); autoFilledIndices.push(index);
const line = demandLines[index]!;
const existingMetadata = (line.metadata ?? {}) as Record<string, unknown>; const existingMetadata = (line.metadata ?? {}) as Record<string, unknown>;
return { enriched[index] = {
...line, ...line,
costRateCents: result.costRateCents, costRateCents: result.costRateCents,
billRateCents: result.billRateCents, billRateCents: result.billRateCents,
@@ -153,8 +169,7 @@ export async function autoFillDemandLineRates(
}, },
}, },
}; };
}), }
);
return { demandLines: enriched, autoFilledIndices }; return { demandLines: enriched, autoFilledIndices };
} }
@@ -57,23 +57,43 @@ export async function loadTimelineHolidayOverlaysForReadModel(
}, },
}); });
// Group resources by location key to deduplicate holiday resolution.
// Resources sharing the same (countryId, federalState, metroCityId) get
// identical holidays, so we resolve once per location instead of once per resource.
const locationGroups = new Map<
string,
{ locationResource: (typeof resources)[0]; resourceIds: string[] }
>();
for (const resource of resources) {
const key = `${resource.countryId ?? ""}:${resource.federalState ?? ""}:${resource.metroCityId ?? ""}`;
const existing = locationGroups.get(key);
if (existing) {
existing.resourceIds.push(resource.id);
} else {
locationGroups.set(key, { locationResource: resource, resourceIds: [resource.id] });
}
}
const resolverDb = asHolidayResolverDb(db);
const overlays = await Promise.all( const overlays = await Promise.all(
resources.map(async (resource) => { [...locationGroups.values()].map(async ({ locationResource, resourceIds }) => {
const holidays = await getResolvedCalendarHolidays(asHolidayResolverDb(db), { const holidays = await getResolvedCalendarHolidays(resolverDb, {
periodStart: input.startDate, periodStart: input.startDate,
periodEnd: input.endDate, periodEnd: input.endDate,
countryId: resource.countryId, countryId: locationResource.countryId,
countryCode: resource.country?.code ?? null, countryCode: locationResource.country?.code ?? null,
federalState: resource.federalState, federalState: locationResource.federalState,
metroCityId: resource.metroCityId, metroCityId: locationResource.metroCityId,
metroCityName: resource.metroCity?.name ?? null, metroCityName: locationResource.metroCity?.name ?? null,
}); });
return resourceIds.flatMap((resourceId) => {
const resource = resources.find((r) => r.id === resourceId)!;
return holidays.map((holiday) => { return holidays.map((holiday) => {
const holidayDate = new Date(`${holiday.date}T00:00:00.000Z`); const holidayDate = new Date(`${holiday.date}T00:00:00.000Z`);
return { return {
id: `calendar-holiday:${resource.id}:${holiday.date}`, id: `calendar-holiday:${resourceId}:${holiday.date}`,
resourceId: resource.id, resourceId,
type: VacationType.PUBLIC_HOLIDAY, type: VacationType.PUBLIC_HOLIDAY,
status: "APPROVED" as const, status: "APPROVED" as const,
startDate: holidayDate, startDate: holidayDate,
@@ -88,6 +108,7 @@ export async function loadTimelineHolidayOverlaysForReadModel(
metroCityName: resource.metroCity?.name ?? null, metroCityName: resource.metroCity?.name ?? null,
}; };
}); });
});
}), }),
); );
@@ -14,9 +14,11 @@ import {
unsetDefaultUtilizationCategory, unsetDefaultUtilizationCategory,
} from "./utilization-category-support.js"; } from "./utilization-category-support.js";
export const UtilizationCategoryListInputSchema = z.object({ export const UtilizationCategoryListInputSchema = z
.object({
isActive: z.boolean().optional(), isActive: z.boolean().optional(),
}).optional(); })
.optional();
export const UtilizationCategoryByIdInputSchema = z.object({ export const UtilizationCategoryByIdInputSchema = z.object({
id: z.string(), id: z.string(),
@@ -38,6 +40,7 @@ export async function listUtilizationCategories(
return ctx.db.utilizationCategory.findMany({ return ctx.db.utilizationCategory.findMany({
where: buildUtilizationCategoryListWhere(input ?? {}), where: buildUtilizationCategoryListWhere(input ?? {}),
orderBy: { sortOrder: "asc" }, orderBy: { sortOrder: "asc" },
include: { _count: { select: { projects: true } } },
}); });
} }