Files
CapaKraken/packages/api/src/__tests__/staffing-router.test.ts
T

477 lines
14 KiB
TypeScript

import { SystemRole } from "@capakraken/shared";
import { describe, expect, it, vi } from "vitest";
import { staffingRouter } from "../router/staffing.js";
import { createCallerFactory } from "../trpc.js";
// Mock the pure-logic packages — we focus on the router/DB layer
vi.mock("@capakraken/staffing", () => ({
rankResources: vi.fn().mockImplementation((input: { resources: { id: string }[] }) =>
input.resources.map((r: { id: string }, i: number) => ({
resourceId: r.id,
score: 80 - i * 10,
breakdown: {
skillScore: 70,
availabilityScore: 90,
costScore: 80,
utilizationScore: 75,
},
})),
),
}));
vi.mock("@capakraken/application", () => ({
listAssignmentBookings: vi.fn().mockResolvedValue([]),
}));
const createCaller = createCallerFactory(staffingRouter);
// ── Caller factories ─────────────────────────────────────────────────────────
function createProtectedCaller(db: Record<string, unknown>) {
return createCaller({
session: {
user: { email: "user@example.com", name: "User", image: null },
expires: "2099-01-01T00:00:00.000Z",
},
db: db as never,
dbUser: {
id: "user_1",
systemRole: SystemRole.USER,
permissionOverrides: null,
},
});
}
// ── Sample data ──────────────────────────────────────────────────────────────
function sampleResource(overrides: Record<string, unknown> = {}) {
return {
id: "res_1",
displayName: "Alice",
eid: "alice",
lcrCents: 7500,
chargeabilityTarget: 80,
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
skills: [
{ skill: "Compositing", proficiency: 4, isMainSkill: true },
{ skill: "Nuke", proficiency: 3, isMainSkill: false, category: "Software" },
],
isActive: true,
valueScore: 85,
chapter: "VFX",
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
...overrides,
};
}
// ─── getSuggestions ──────────────────────────────────────────────────────────
describe("staffing.getSuggestions", () => {
it("returns ranked suggestions for a staffing demand", async () => {
const resources = [
sampleResource(),
sampleResource({ id: "res_2", displayName: "Bob", eid: "bob", valueScore: 70 }),
];
const db = {
resource: {
findMany: vi.fn().mockResolvedValue(resources),
},
};
const caller = createProtectedCaller(db);
const result = await caller.getSuggestions({
requiredSkills: ["Compositing"],
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
hoursPerDay: 8,
});
expect(result).toHaveLength(2);
expect(result[0]).toHaveProperty("resourceId");
expect(result[0]).toHaveProperty("score");
expect(result[0]).toMatchObject({
resourceName: "Alice",
eid: "alice",
location: {
countryCode: "DE",
federalState: "BY",
},
capacity: expect.objectContaining({
requestedHoursPerDay: 8,
baseAvailableHours: expect.any(Number),
effectiveAvailableHours: expect.any(Number),
remainingHoursPerDay: expect.any(Number),
holidayHoursDeduction: expect.any(Number),
}),
conflicts: {
count: expect.any(Number),
conflictDays: expect.any(Array),
details: expect.any(Array),
},
ranking: expect.objectContaining({
rank: 1,
components: expect.any(Array),
}),
});
});
it("filters resources by chapter when provided", async () => {
const db = {
resource: {
findMany: vi.fn().mockResolvedValue([]),
},
};
const caller = createProtectedCaller(db);
await caller.getSuggestions({
requiredSkills: ["Compositing"],
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
hoursPerDay: 8,
chapter: "VFX",
});
expect(db.resource.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
isActive: true,
chapter: "VFX",
}),
}),
);
});
it("returns empty array when no resources match", async () => {
const db = {
resource: {
findMany: vi.fn().mockResolvedValue([]),
},
};
const caller = createProtectedCaller(db);
const result = await caller.getSuggestions({
requiredSkills: ["Compositing"],
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
hoursPerDay: 8,
});
expect(result).toHaveLength(0);
});
it("passes budget constraint to ranking", async () => {
const resources = [sampleResource()];
const db = {
resource: {
findMany: vi.fn().mockResolvedValue(resources),
},
};
const { rankResources } = await import("@capakraken/staffing");
const caller = createProtectedCaller(db);
await caller.getSuggestions({
requiredSkills: ["Compositing"],
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
hoursPerDay: 8,
budgetLcrCentsPerHour: 10000,
});
expect(rankResources).toHaveBeenCalledWith(
expect.objectContaining({
budgetLcrCentsPerHour: 10000,
}),
);
});
it("uses value score as a transparent tiebreaker within two score points", async () => {
const resources = [
sampleResource({ id: "res_1", displayName: "Alice", eid: "alice", valueScore: 60 }),
sampleResource({ id: "res_2", displayName: "Bob", eid: "bob", valueScore: 95 }),
];
const db = {
resource: {
findMany: vi.fn().mockResolvedValue(resources),
},
};
const { rankResources } = await import("@capakraken/staffing");
vi.mocked(rankResources).mockImplementationOnce((input: { resources: Array<{ id: string }> }) => ([
{
resourceId: input.resources[0]!.id,
score: 80,
breakdown: {
skillScore: 80,
availabilityScore: 80,
costScore: 80,
utilizationScore: 80,
},
},
{
resourceId: input.resources[1]!.id,
score: 79,
breakdown: {
skillScore: 79,
availabilityScore: 79,
costScore: 79,
utilizationScore: 79,
},
},
]));
const caller = createProtectedCaller(db);
const result = await caller.getSuggestions({
requiredSkills: ["Compositing"],
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
hoursPerDay: 8,
});
expect(result[0]?.resourceId).toBe("res_2");
expect(result[0]?.ranking).toMatchObject({
rank: 1,
baseRank: 2,
tieBreakerApplied: true,
});
expect(result[0]?.ranking.tieBreakerReason).toContain("value score");
});
});
// ─── analyzeUtilization ──────────────────────────────────────────────────────
describe("staffing.analyzeUtilization", () => {
it("returns utilization analysis for an existing resource", async () => {
const resource = {
id: "res_1",
displayName: "Alice",
chargeabilityTarget: 80,
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
};
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(resource),
},
};
const caller = createProtectedCaller(db);
const result = await caller.analyzeUtilization({
resourceId: "res_1",
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
});
expect(result).toHaveProperty("currentChargeability");
expect(result.resourceId).toBe("res_1");
});
it("excludes Bavarian public holidays from chargeability analysis", async () => {
const resource = {
id: "res_1",
displayName: "Alice",
chargeabilityTarget: 80,
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
};
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(resource),
},
};
const { listAssignmentBookings } = await import("@capakraken/application");
vi.mocked(listAssignmentBookings).mockResolvedValue([
{
id: "a1",
projectId: "project_1",
resourceId: "res_1",
startDate: new Date("2026-01-05T00:00:00.000Z"),
endDate: new Date("2026-01-06T00:00:00.000Z"),
hoursPerDay: 8,
dailyCostCents: 0,
status: "CONFIRMED",
project: { id: "project_1", name: "Chargeable", shortCode: "CHG", status: "ACTIVE", orderType: "CHARGEABLE", clientId: null, dynamicFields: null },
resource: { id: "res_1", displayName: "Alice", chapter: "VFX" },
},
]);
const caller = createProtectedCaller(db);
const result = await caller.analyzeUtilization({
resourceId: "res_1",
startDate: new Date("2026-01-05T00:00:00.000Z"),
endDate: new Date("2026-01-06T00:00:00.000Z"),
});
expect(result.currentChargeability).toBe(100);
expect(result.overallocatedDays).toEqual([]);
expect(result.underutilizedDays).toEqual([]);
});
it("throws NOT_FOUND when resource does not exist", async () => {
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(null),
},
};
const caller = createProtectedCaller(db);
await expect(
caller.analyzeUtilization({
resourceId: "nonexistent",
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
}),
).rejects.toThrow("Resource not found");
});
});
// ─── findCapacity ────────────────────────────────────────────────────────────
describe("staffing.findCapacity", () => {
it("returns capacity windows for an existing resource", async () => {
const resource = {
id: "res_1",
displayName: "Alice",
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
};
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(resource),
},
};
const caller = createProtectedCaller(db);
const result = await caller.findCapacity({
resourceId: "res_1",
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
});
expect(result.length).toBeGreaterThan(0);
expect(result[0]).toHaveProperty("availableHoursPerDay");
expect(result.every((window) => window.availableHoursPerDay > 0)).toBe(true);
expect(result.reduce((sum, window) => sum + window.availableDays, 0)).toBeGreaterThan(0);
});
it("splits capacity windows around Bavarian public holidays", async () => {
const resource = {
id: "res_1",
displayName: "Alice",
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
};
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(resource),
},
};
const { listAssignmentBookings } = await import("@capakraken/application");
vi.mocked(listAssignmentBookings).mockResolvedValue([]);
const caller = createProtectedCaller(db);
const result = await caller.findCapacity({
resourceId: "res_1",
startDate: new Date("2026-01-05T00:00:00.000Z"),
endDate: new Date("2026-01-07T00:00:00.000Z"),
minAvailableHoursPerDay: 4,
});
expect(result).toHaveLength(2);
expect(result[0]).toEqual(
expect.objectContaining({
startDate: new Date("2026-01-05T00:00:00.000Z"),
endDate: new Date("2026-01-05T00:00:00.000Z"),
}),
);
expect(result[1]).toEqual(
expect.objectContaining({
startDate: new Date("2026-01-07T00:00:00.000Z"),
endDate: new Date("2026-01-07T00:00:00.000Z"),
}),
);
});
it("throws NOT_FOUND when resource does not exist", async () => {
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(null),
},
};
const caller = createProtectedCaller(db);
await expect(
caller.findCapacity({
resourceId: "nonexistent",
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
}),
).rejects.toThrow("Resource not found");
});
it("honors minAvailableHoursPerDay when computing holiday-aware windows", async () => {
const resource = {
id: "res_1",
displayName: "Alice",
availability: { monday: 8, tuesday: 8, wednesday: 8, thursday: 8, friday: 8 },
countryId: "country_de",
federalState: "BY",
metroCityId: null,
country: { code: "DE" },
metroCity: null,
};
const db = {
resource: {
findUnique: vi.fn().mockResolvedValue(resource),
},
};
const { listAssignmentBookings } = await import("@capakraken/application");
vi.mocked(listAssignmentBookings).mockResolvedValue([
{
id: "a1",
projectId: "project_1",
resourceId: "res_1",
startDate: new Date("2026-04-01T00:00:00.000Z"),
endDate: new Date("2026-04-30T00:00:00.000Z"),
hoursPerDay: 3,
dailyCostCents: 0,
status: "CONFIRMED",
project: { id: "project_1", name: "Project", shortCode: "PRJ", status: "ACTIVE", orderType: "CHARGEABLE", clientId: null, dynamicFields: null },
resource: { id: "res_1", displayName: "Alice", chapter: "VFX" },
},
]);
const caller = createProtectedCaller(db);
const result = await caller.findCapacity({
resourceId: "res_1",
startDate: new Date("2026-04-01"),
endDate: new Date("2026-04-30"),
minAvailableHoursPerDay: 6,
});
expect(result.every((window) => window.availableHoursPerDay >= 6)).toBe(true);
});
});