perf(db): add missing indexes, fix N+1 batch delete, add pagination limits
- Add indexes on Resource(blueprintId, roleId), DemandRequirement(roleId),
Assignment(roleId) — commonly filtered FK columns that were missing indexes
- Replace N+1 batch delete pattern (2N queries) with findAllocationEntries()
that does 2 total queries via findMany({ id: { in: ids } })
- Add take/skip pagination with default limit of 500 to listDemands and
listAssignments to prevent unbounded result sets
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,11 @@
|
|||||||
import { AllocationStatus, PermissionKey, SystemRole } from "@capakraken/shared";
|
import { AllocationStatus, PermissionKey, SystemRole } from "@capakraken/shared";
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { allocationRouter } from "../router/allocation/index.js";
|
import { allocationRouter } from "../router/allocation/index.js";
|
||||||
import { emitAllocationCreated, emitAllocationDeleted, emitNotificationCreated } from "../sse/event-bus.js";
|
import {
|
||||||
|
emitAllocationCreated,
|
||||||
|
emitAllocationDeleted,
|
||||||
|
emitNotificationCreated,
|
||||||
|
} from "../sse/event-bus.js";
|
||||||
import { checkBudgetThresholds } from "../lib/budget-alerts.js";
|
import { checkBudgetThresholds } from "../lib/budget-alerts.js";
|
||||||
import { generateAutoSuggestions } from "../lib/auto-staffing.js";
|
import { generateAutoSuggestions } from "../lib/auto-staffing.js";
|
||||||
import { invalidateDashboardCache } from "../lib/cache.js";
|
import { invalidateDashboardCache } from "../lib/cache.js";
|
||||||
@@ -155,6 +159,8 @@ describe("allocation router authorization", () => {
|
|||||||
where: {},
|
where: {},
|
||||||
include: expect.any(Object),
|
include: expect.any(Object),
|
||||||
orderBy: { startDate: "asc" },
|
orderBy: { startDate: "asc" },
|
||||||
|
take: 500,
|
||||||
|
skip: 0,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -196,9 +202,12 @@ describe("allocation router authorization", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("does not treat viewCosts as a substitute for viewPlanning on planning reads", async () => {
|
it("does not treat viewCosts as a substitute for viewPlanning on planning reads", async () => {
|
||||||
const caller = createProtectedCallerWithOverrides({}, {
|
const caller = createProtectedCallerWithOverrides(
|
||||||
|
{},
|
||||||
|
{
|
||||||
granted: [PermissionKey.VIEW_COSTS],
|
granted: [PermissionKey.VIEW_COSTS],
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
await expect(caller.listAssignments({})).rejects.toMatchObject({
|
await expect(caller.listAssignments({})).rejects.toMatchObject({
|
||||||
code: "FORBIDDEN",
|
code: "FORBIDDEN",
|
||||||
@@ -208,32 +217,47 @@ describe("allocation router authorization", () => {
|
|||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
{ name: "list", invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.list({}) },
|
{ name: "list", invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.list({}) },
|
||||||
{ name: "listView", invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listView({}) },
|
{
|
||||||
{ name: "listDemands", invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listDemands({}) },
|
name: "listView",
|
||||||
{ name: "listAssignments", invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listAssignments({}) },
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listView({}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "listDemands",
|
||||||
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listDemands({}),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "listAssignments",
|
||||||
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.listAssignments({}),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "getAssignmentById",
|
name: "getAssignmentById",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.getAssignmentById({ id: "assignment_1" }),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.getAssignmentById({ id: "assignment_1" }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "resolveAssignment",
|
name: "resolveAssignment",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.resolveAssignment({ assignmentId: "assignment_1" }),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.resolveAssignment({ assignmentId: "assignment_1" }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "getDemandRequirementById",
|
name: "getDemandRequirementById",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.getDemandRequirementById({ id: "demand_1" }),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.getDemandRequirementById({ id: "demand_1" }),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "checkResourceAvailability",
|
name: "checkResourceAvailability",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.checkResourceAvailability(planningWindow),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.checkResourceAvailability(planningWindow),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "getResourceAvailabilityView",
|
name: "getResourceAvailabilityView",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.getResourceAvailabilityView(planningWindow),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.getResourceAvailabilityView(planningWindow),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "getResourceAvailabilitySummary",
|
name: "getResourceAvailabilitySummary",
|
||||||
invoke: (caller: ReturnType<typeof createProtectedCaller>) => caller.getResourceAvailabilitySummary(planningWindow),
|
invoke: (caller: ReturnType<typeof createProtectedCaller>) =>
|
||||||
|
caller.getResourceAvailabilitySummary(planningWindow),
|
||||||
},
|
},
|
||||||
])("requires planning read access for $name", async ({ invoke }) => {
|
])("requires planning read access for $name", async ({ invoke }) => {
|
||||||
const caller = createProtectedCaller({});
|
const caller = createProtectedCaller({});
|
||||||
@@ -708,7 +732,9 @@ describe("allocation entry resolution router", () => {
|
|||||||
it("logs and swallows background side-effect failures during demand creation", async () => {
|
it("logs and swallows background side-effect failures during demand creation", async () => {
|
||||||
vi.mocked(invalidateDashboardCache).mockRejectedValueOnce(new Error("redis unavailable"));
|
vi.mocked(invalidateDashboardCache).mockRejectedValueOnce(new Error("redis unavailable"));
|
||||||
vi.mocked(checkBudgetThresholds).mockRejectedValueOnce(new Error("budget alerts unavailable"));
|
vi.mocked(checkBudgetThresholds).mockRejectedValueOnce(new Error("budget alerts unavailable"));
|
||||||
vi.mocked(generateAutoSuggestions).mockRejectedValueOnce(new Error("auto suggestions unavailable"));
|
vi.mocked(generateAutoSuggestions).mockRejectedValueOnce(
|
||||||
|
new Error("auto suggestions unavailable"),
|
||||||
|
);
|
||||||
|
|
||||||
const createdDemandRequirement = {
|
const createdDemandRequirement = {
|
||||||
id: "demand_safe_1",
|
id: "demand_safe_1",
|
||||||
@@ -761,7 +787,10 @@ describe("allocation entry resolution router", () => {
|
|||||||
"Allocation background side effect failed",
|
"Allocation background side effect failed",
|
||||||
);
|
);
|
||||||
expect(vi.mocked(logger.error)).toHaveBeenCalledWith(
|
expect(vi.mocked(logger.error)).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({ effectName: "generateAutoSuggestions", demandRequirementId: "demand_safe_1" }),
|
expect.objectContaining({
|
||||||
|
effectName: "generateAutoSuggestions",
|
||||||
|
demandRequirementId: "demand_safe_1",
|
||||||
|
}),
|
||||||
"Allocation background side effect failed",
|
"Allocation background side effect failed",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -1017,7 +1046,8 @@ describe("allocation entry resolution router", () => {
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
demandRequirement: {
|
demandRequirement: {
|
||||||
findUnique: vi.fn()
|
findUnique: vi
|
||||||
|
.fn()
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
id: "demand_1",
|
id: "demand_1",
|
||||||
projectId: "project_1",
|
projectId: "project_1",
|
||||||
@@ -1182,7 +1212,11 @@ describe("allocation entry resolution router", () => {
|
|||||||
expect(db.assignment.delete).toHaveBeenCalledWith({
|
expect(db.assignment.delete).toHaveBeenCalledWith({
|
||||||
where: { id: "assignment_explicit_1" },
|
where: { id: "assignment_explicit_1" },
|
||||||
});
|
});
|
||||||
expect(emitAllocationDeleted).toHaveBeenCalledWith("assignment_explicit_1", "project_1", "resource_1");
|
expect(emitAllocationDeleted).toHaveBeenCalledWith(
|
||||||
|
"assignment_explicit_1",
|
||||||
|
"project_1",
|
||||||
|
"resource_1",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("updates an explicit demand row through allocation.update", async () => {
|
it("updates an explicit demand row through allocation.update", async () => {
|
||||||
@@ -1276,15 +1310,13 @@ describe("allocation entry resolution router", () => {
|
|||||||
|
|
||||||
const db = {
|
const db = {
|
||||||
demandRequirement: {
|
demandRequirement: {
|
||||||
findUnique: vi.fn().mockImplementation(
|
findUnique: vi.fn().mockImplementation(({ where }: { where: { id?: string } }) => {
|
||||||
({ where }: { where: { id?: string } }) => {
|
|
||||||
if (where.id === "demand_stale") {
|
if (where.id === "demand_stale") {
|
||||||
return existingDemand;
|
return existingDemand;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
},
|
}),
|
||||||
),
|
|
||||||
update: vi.fn().mockResolvedValue(updatedDemand),
|
update: vi.fn().mockResolvedValue(updatedDemand),
|
||||||
},
|
},
|
||||||
assignment: {
|
assignment: {
|
||||||
@@ -1360,15 +1392,29 @@ describe("allocation entry resolution router", () => {
|
|||||||
findUnique: vi.fn().mockResolvedValue(null),
|
findUnique: vi.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
demandRequirement: {
|
demandRequirement: {
|
||||||
findUnique: vi.fn().mockImplementation(({ where }: { where: { id: string } }) =>
|
findUnique: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(({ where }: { where: { id: string } }) =>
|
||||||
where.id === "demand_1" ? explicitDemand : null,
|
where.id === "demand_1" ? explicitDemand : null,
|
||||||
),
|
),
|
||||||
|
findMany: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(({ where }: { where: { id: { in: string[] } } }) =>
|
||||||
|
[explicitDemand].filter((d) => where.id.in.includes(d.id)),
|
||||||
|
),
|
||||||
delete: vi.fn().mockResolvedValue({}),
|
delete: vi.fn().mockResolvedValue({}),
|
||||||
},
|
},
|
||||||
assignment: {
|
assignment: {
|
||||||
findUnique: vi.fn().mockImplementation(({ where }: { where: { id: string } }) =>
|
findUnique: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(({ where }: { where: { id: string } }) =>
|
||||||
where.id === "assignment_1" ? explicitAssignment : null,
|
where.id === "assignment_1" ? explicitAssignment : null,
|
||||||
),
|
),
|
||||||
|
findMany: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(({ where }: { where: { id: { in: string[] } } }) =>
|
||||||
|
[explicitAssignment].filter((a) => where.id.in.includes(a.id)),
|
||||||
|
),
|
||||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||||
delete: vi.fn().mockResolvedValue({}),
|
delete: vi.fn().mockResolvedValue({}),
|
||||||
},
|
},
|
||||||
@@ -1424,15 +1470,13 @@ describe("allocation entry resolution router", () => {
|
|||||||
findUnique: vi.fn().mockResolvedValue(null),
|
findUnique: vi.fn().mockResolvedValue(null),
|
||||||
},
|
},
|
||||||
assignment: {
|
assignment: {
|
||||||
findUnique: vi.fn().mockImplementation(
|
findUnique: vi.fn().mockImplementation(({ where }: { where: { id?: string } }) => {
|
||||||
({ where }: { where: { id?: string } }) => {
|
|
||||||
if (where.id === "assignment_stale") {
|
if (where.id === "assignment_stale") {
|
||||||
return existingAssignment;
|
return existingAssignment;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
},
|
}),
|
||||||
),
|
|
||||||
delete: vi.fn().mockResolvedValue({}),
|
delete: vi.fn().mockResolvedValue({}),
|
||||||
},
|
},
|
||||||
auditLog: {
|
auditLog: {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
createDemandRequirement,
|
createDemandRequirement,
|
||||||
deleteAllocationEntry,
|
deleteAllocationEntry,
|
||||||
deleteAssignment,
|
deleteAssignment,
|
||||||
|
findAllocationEntries,
|
||||||
loadAllocationEntry,
|
loadAllocationEntry,
|
||||||
updateAllocationEntry,
|
updateAllocationEntry,
|
||||||
updateAssignment,
|
updateAssignment,
|
||||||
@@ -68,9 +69,7 @@ export async function createAllocationReadModelEntry(
|
|||||||
}).allocations[0]!;
|
}).allocations[0]!;
|
||||||
}
|
}
|
||||||
|
|
||||||
const assignment = await createAssignment(
|
const assignment = await createAssignment(tx, {
|
||||||
tx,
|
|
||||||
{
|
|
||||||
resourceId: input.resourceId,
|
resourceId: input.resourceId,
|
||||||
projectId: input.projectId,
|
projectId: input.projectId,
|
||||||
startDate: input.startDate,
|
startDate: input.startDate,
|
||||||
@@ -81,8 +80,7 @@ export async function createAllocationReadModelEntry(
|
|||||||
roleId: input.roleId,
|
roleId: input.roleId,
|
||||||
status: input.status,
|
status: input.status,
|
||||||
metadata: input.metadata,
|
metadata: input.metadata,
|
||||||
},
|
});
|
||||||
);
|
|
||||||
|
|
||||||
return buildSplitAllocationReadModel({
|
return buildSplitAllocationReadModel({
|
||||||
demandRequirements: [],
|
demandRequirements: [],
|
||||||
@@ -94,17 +92,20 @@ export async function ensureAssignmentRecord(
|
|||||||
db: Pick<PrismaClient, "$transaction" | "assignment" | "resource">,
|
db: Pick<PrismaClient, "$transaction" | "assignment" | "resource">,
|
||||||
input: EnsureAssignmentInput,
|
input: EnsureAssignmentInput,
|
||||||
) {
|
) {
|
||||||
const existing = (await db.assignment.findMany({
|
const existing = (
|
||||||
|
await db.assignment.findMany({
|
||||||
where: {
|
where: {
|
||||||
resourceId: input.resourceId,
|
resourceId: input.resourceId,
|
||||||
projectId: input.projectId,
|
projectId: input.projectId,
|
||||||
},
|
},
|
||||||
include: ASSIGNMENT_INCLUDE,
|
include: ASSIGNMENT_INCLUDE,
|
||||||
orderBy: { startDate: "asc" },
|
orderBy: { startDate: "asc" },
|
||||||
})).find((assignment) => (
|
})
|
||||||
toIsoDate(assignment.startDate) === toIsoDate(input.startDate)
|
).find(
|
||||||
&& toIsoDate(assignment.endDate) === toIsoDate(input.endDate)
|
(assignment) =>
|
||||||
));
|
toIsoDate(assignment.startDate) === toIsoDate(input.startDate) &&
|
||||||
|
toIsoDate(assignment.endDate) === toIsoDate(input.endDate),
|
||||||
|
);
|
||||||
|
|
||||||
if (existing) {
|
if (existing) {
|
||||||
if (existing.status !== AllocationStatus.CANCELLED) {
|
if (existing.status !== AllocationStatus.CANCELLED) {
|
||||||
@@ -122,24 +123,21 @@ export async function ensureAssignmentRecord(
|
|||||||
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
|
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated = await db.$transaction(async (tx) => updateAssignment(
|
const updated = await db.$transaction(async (tx) =>
|
||||||
tx as Parameters<typeof updateAssignment>[0],
|
updateAssignment(tx as Parameters<typeof updateAssignment>[0], existing.id, {
|
||||||
existing.id,
|
|
||||||
{
|
|
||||||
status: AllocationStatus.PROPOSED,
|
status: AllocationStatus.PROPOSED,
|
||||||
hoursPerDay: input.hoursPerDay,
|
hoursPerDay: input.hoursPerDay,
|
||||||
percentage: (input.hoursPerDay / 8) * 100,
|
percentage: (input.hoursPerDay / 8) * 100,
|
||||||
dailyCostCents: Math.round(resource.lcrCents * input.hoursPerDay),
|
dailyCostCents: Math.round(resource.lcrCents * input.hoursPerDay),
|
||||||
...(input.role ? { role: input.role } : {}),
|
...(input.role ? { role: input.role } : {}),
|
||||||
},
|
}),
|
||||||
));
|
);
|
||||||
|
|
||||||
return { assignment: updated, action: "reactivated" as const };
|
return { assignment: updated, action: "reactivated" as const };
|
||||||
}
|
}
|
||||||
|
|
||||||
const assignment = await db.$transaction(async (tx) => createAssignment(
|
const assignment = await db.$transaction(async (tx) =>
|
||||||
tx as Parameters<typeof createAssignment>[0],
|
createAssignment(tx as Parameters<typeof createAssignment>[0], {
|
||||||
{
|
|
||||||
resourceId: input.resourceId,
|
resourceId: input.resourceId,
|
||||||
projectId: input.projectId,
|
projectId: input.projectId,
|
||||||
startDate: input.startDate,
|
startDate: input.startDate,
|
||||||
@@ -149,8 +147,8 @@ export async function ensureAssignmentRecord(
|
|||||||
status: AllocationStatus.PROPOSED,
|
status: AllocationStatus.PROPOSED,
|
||||||
metadata: {},
|
metadata: {},
|
||||||
...(input.role ? { role: input.role } : {}),
|
...(input.role ? { role: input.role } : {}),
|
||||||
},
|
}),
|
||||||
));
|
);
|
||||||
|
|
||||||
return { assignment, action: "created" as const };
|
return { assignment, action: "created" as const };
|
||||||
}
|
}
|
||||||
@@ -168,8 +166,7 @@ export async function updateAllocationWithAudit(
|
|||||||
id,
|
id,
|
||||||
demandRequirementUpdate:
|
demandRequirementUpdate:
|
||||||
existing.kind === "assignment" ? {} : toDemandRequirementUpdateInput(data),
|
existing.kind === "assignment" ? {} : toDemandRequirementUpdateInput(data),
|
||||||
assignmentUpdate:
|
assignmentUpdate: existing.kind === "demand" ? {} : toAssignmentUpdateInput(data),
|
||||||
existing.kind === "demand" ? {} : toAssignmentUpdateInput(data),
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -191,10 +188,7 @@ export async function updateAllocationWithAudit(
|
|||||||
return { existing, updated };
|
return { existing, updated };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteAssignmentWithAudit(
|
export async function deleteAssignmentWithAudit(db: AllocationMutationDb, id: string) {
|
||||||
db: AllocationMutationDb,
|
|
||||||
id: string,
|
|
||||||
) {
|
|
||||||
const existing = await findUniqueOrThrow(
|
const existing = await findUniqueOrThrow(
|
||||||
db.assignment.findUnique({
|
db.assignment.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -204,10 +198,7 @@ export async function deleteAssignmentWithAudit(
|
|||||||
);
|
);
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await deleteAssignment(
|
await deleteAssignment(tx as Parameters<typeof deleteAssignment>[0], id);
|
||||||
tx as Parameters<typeof deleteAssignment>[0],
|
|
||||||
id,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tx.auditLog.create({
|
await tx.auditLog.create({
|
||||||
data: {
|
data: {
|
||||||
@@ -222,24 +213,20 @@ export async function deleteAssignmentWithAudit(
|
|||||||
return existing;
|
return existing;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteAllocationWithAudit(
|
export async function deleteAllocationWithAudit(db: AllocationMutationDb, id: string) {
|
||||||
db: AllocationMutationDb,
|
|
||||||
id: string,
|
|
||||||
) {
|
|
||||||
const existing = await loadAllocationEntry(db, id);
|
const existing = await loadAllocationEntry(db, id);
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await deleteAllocationEntry(
|
await deleteAllocationEntry(tx as Parameters<typeof deleteAllocationEntry>[0], existing);
|
||||||
tx as Parameters<typeof deleteAllocationEntry>[0],
|
|
||||||
existing,
|
|
||||||
);
|
|
||||||
|
|
||||||
await tx.auditLog.create({
|
await tx.auditLog.create({
|
||||||
data: {
|
data: {
|
||||||
entityType: "Allocation",
|
entityType: "Allocation",
|
||||||
entityId: id,
|
entityId: id,
|
||||||
action: "DELETE",
|
action: "DELETE",
|
||||||
changes: { before: existing.entry } as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
changes: {
|
||||||
|
before: existing.entry,
|
||||||
|
} as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -247,20 +234,13 @@ export async function deleteAllocationWithAudit(
|
|||||||
return existing;
|
return existing;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function batchDeleteAllocationsWithAudit(
|
export async function batchDeleteAllocationsWithAudit(db: AllocationMutationDb, ids: string[]) {
|
||||||
db: AllocationMutationDb,
|
// Batch-load in 2 queries (demand + assignment) instead of 2N individual lookups
|
||||||
ids: string[],
|
const existing = await findAllocationEntries(db, ids);
|
||||||
) {
|
|
||||||
const existing = (
|
|
||||||
await Promise.all(ids.map(async (id) => findAllocationEntryOrNull(db, id)))
|
|
||||||
).filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
|
|
||||||
|
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
for (const allocation of existing) {
|
for (const allocation of existing) {
|
||||||
await deleteAllocationEntry(
|
await deleteAllocationEntry(tx as Parameters<typeof deleteAllocationEntry>[0], allocation);
|
||||||
tx as Parameters<typeof deleteAllocationEntry>[0],
|
|
||||||
allocation,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await tx.auditLog.create({
|
await tx.auditLog.create({
|
||||||
@@ -290,16 +270,16 @@ export async function batchUpdateAllocationStatusWithAudit(
|
|||||||
) {
|
) {
|
||||||
const updated = await db.$transaction(async (tx) => {
|
const updated = await db.$transaction(async (tx) => {
|
||||||
const updatedAllocations = await Promise.all(
|
const updatedAllocations = await Promise.all(
|
||||||
input.ids.map(async (id) => (
|
input.ids.map(
|
||||||
await updateAllocationEntry(
|
async (id) =>
|
||||||
tx as Parameters<typeof updateAllocationEntry>[0],
|
(
|
||||||
{
|
await updateAllocationEntry(tx as Parameters<typeof updateAllocationEntry>[0], {
|
||||||
id,
|
id,
|
||||||
demandRequirementUpdate: { status: input.status },
|
demandRequirementUpdate: { status: input.status },
|
||||||
assignmentUpdate: { status: input.status },
|
assignmentUpdate: { status: input.status },
|
||||||
},
|
})
|
||||||
)
|
).allocation,
|
||||||
).allocation),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
await tx.auditLog.create({
|
await tx.auditLog.create({
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import { anonymizeResource, getAnonymizationDirectory } from "../../lib/anonymiz
|
|||||||
import { planningReadProcedure } from "../../trpc.js";
|
import { planningReadProcedure } from "../../trpc.js";
|
||||||
import { buildResourceAvailabilitySummary, buildResourceAvailabilityView } from "./availability.js";
|
import { buildResourceAvailabilitySummary, buildResourceAvailabilityView } from "./availability.js";
|
||||||
import { ASSIGNMENT_INCLUDE, DEMAND_INCLUDE } from "./shared.js";
|
import { ASSIGNMENT_INCLUDE, DEMAND_INCLUDE } from "./shared.js";
|
||||||
import { getDemandRequirementByIdOrThrow, loadAllocationReadModel, resolveAssignmentBySelection } from "./support.js";
|
import {
|
||||||
|
getDemandRequirementByIdOrThrow,
|
||||||
|
loadAllocationReadModel,
|
||||||
|
resolveAssignmentBySelection,
|
||||||
|
} from "./support.js";
|
||||||
|
|
||||||
export const allocationReadProcedures = {
|
export const allocationReadProcedures = {
|
||||||
list: planningReadProcedure
|
list: planningReadProcedure
|
||||||
@@ -37,6 +41,8 @@ export const allocationReadProcedures = {
|
|||||||
projectId: z.string().optional(),
|
projectId: z.string().optional(),
|
||||||
status: z.nativeEnum(AllocationStatus).optional(),
|
status: z.nativeEnum(AllocationStatus).optional(),
|
||||||
roleId: z.string().optional(),
|
roleId: z.string().optional(),
|
||||||
|
take: z.number().int().min(1).max(1000).default(500),
|
||||||
|
skip: z.number().int().min(0).default(0),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
@@ -48,6 +54,8 @@ export const allocationReadProcedures = {
|
|||||||
},
|
},
|
||||||
include: DEMAND_INCLUDE,
|
include: DEMAND_INCLUDE,
|
||||||
orderBy: { startDate: "asc" },
|
orderBy: { startDate: "asc" },
|
||||||
|
take: input.take,
|
||||||
|
skip: input.skip,
|
||||||
});
|
});
|
||||||
const directory = await getAnonymizationDirectory(ctx.db);
|
const directory = await getAnonymizationDirectory(ctx.db);
|
||||||
if (!directory) {
|
if (!directory) {
|
||||||
@@ -55,11 +63,11 @@ export const allocationReadProcedures = {
|
|||||||
}
|
}
|
||||||
return demands.map((demand) => ({
|
return demands.map((demand) => ({
|
||||||
...demand,
|
...demand,
|
||||||
assignments: demand.assignments.map((assignment) => (
|
assignments: demand.assignments.map((assignment) =>
|
||||||
assignment.resource
|
assignment.resource
|
||||||
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
||||||
: assignment
|
: assignment,
|
||||||
)),
|
),
|
||||||
}));
|
}));
|
||||||
}),
|
}),
|
||||||
|
|
||||||
@@ -70,6 +78,8 @@ export const allocationReadProcedures = {
|
|||||||
resourceId: z.string().optional(),
|
resourceId: z.string().optional(),
|
||||||
status: z.nativeEnum(AllocationStatus).optional(),
|
status: z.nativeEnum(AllocationStatus).optional(),
|
||||||
demandRequirementId: z.string().optional(),
|
demandRequirementId: z.string().optional(),
|
||||||
|
take: z.number().int().min(1).max(1000).default(500),
|
||||||
|
skip: z.number().int().min(0).default(0),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
@@ -82,16 +92,18 @@ export const allocationReadProcedures = {
|
|||||||
},
|
},
|
||||||
include: ASSIGNMENT_INCLUDE,
|
include: ASSIGNMENT_INCLUDE,
|
||||||
orderBy: { startDate: "asc" },
|
orderBy: { startDate: "asc" },
|
||||||
|
take: input.take,
|
||||||
|
skip: input.skip,
|
||||||
});
|
});
|
||||||
const directory = await getAnonymizationDirectory(ctx.db);
|
const directory = await getAnonymizationDirectory(ctx.db);
|
||||||
if (!directory) {
|
if (!directory) {
|
||||||
return assignments;
|
return assignments;
|
||||||
}
|
}
|
||||||
return assignments.map((assignment) => (
|
return assignments.map((assignment) =>
|
||||||
assignment.resource
|
assignment.resource
|
||||||
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
? { ...assignment, resource: anonymizeResource(assignment.resource, directory) }
|
||||||
: assignment
|
: assignment,
|
||||||
));
|
);
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getAssignmentById: planningReadProcedure
|
getAssignmentById: planningReadProcedure
|
||||||
@@ -115,7 +127,8 @@ export const allocationReadProcedures = {
|
|||||||
}),
|
}),
|
||||||
|
|
||||||
resolveAssignment: planningReadProcedure
|
resolveAssignment: planningReadProcedure
|
||||||
.input(z.object({
|
.input(
|
||||||
|
z.object({
|
||||||
assignmentId: z.string().optional(),
|
assignmentId: z.string().optional(),
|
||||||
resourceId: z.string().optional(),
|
resourceId: z.string().optional(),
|
||||||
projectId: z.string().optional(),
|
projectId: z.string().optional(),
|
||||||
@@ -123,7 +136,8 @@ export const allocationReadProcedures = {
|
|||||||
endDate: z.coerce.date().optional(),
|
endDate: z.coerce.date().optional(),
|
||||||
selectionMode: z.enum(["WINDOW", "EXACT_START"]).default("EXACT_START"),
|
selectionMode: z.enum(["WINDOW", "EXACT_START"]).default("EXACT_START"),
|
||||||
excludeCancelled: z.boolean().default(false),
|
excludeCancelled: z.boolean().default(false),
|
||||||
}))
|
}),
|
||||||
|
)
|
||||||
.query(async ({ ctx, input }) => resolveAssignmentBySelection(ctx.db, input)),
|
.query(async ({ ctx, input }) => resolveAssignmentBySelection(ctx.db, input)),
|
||||||
|
|
||||||
getDemandRequirementById: planningReadProcedure
|
getDemandRequirementById: planningReadProcedure
|
||||||
@@ -131,33 +145,42 @@ export const allocationReadProcedures = {
|
|||||||
.query(async ({ ctx, input }) => getDemandRequirementByIdOrThrow(ctx.db, input.id)),
|
.query(async ({ ctx, input }) => getDemandRequirementByIdOrThrow(ctx.db, input.id)),
|
||||||
|
|
||||||
checkResourceAvailability: planningReadProcedure
|
checkResourceAvailability: planningReadProcedure
|
||||||
.input(z.object({
|
.input(
|
||||||
|
z.object({
|
||||||
resourceId: z.string(),
|
resourceId: z.string(),
|
||||||
startDate: z.coerce.date(),
|
startDate: z.coerce.date(),
|
||||||
endDate: z.coerce.date(),
|
endDate: z.coerce.date(),
|
||||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||||
}))
|
}),
|
||||||
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const { vacations: _vacations, ...availability } = await buildResourceAvailabilityView(ctx.db, input);
|
const { vacations: _vacations, ...availability } = await buildResourceAvailabilityView(
|
||||||
|
ctx.db,
|
||||||
|
input,
|
||||||
|
);
|
||||||
return availability;
|
return availability;
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getResourceAvailabilityView: planningReadProcedure
|
getResourceAvailabilityView: planningReadProcedure
|
||||||
.input(z.object({
|
.input(
|
||||||
|
z.object({
|
||||||
resourceId: z.string(),
|
resourceId: z.string(),
|
||||||
startDate: z.coerce.date(),
|
startDate: z.coerce.date(),
|
||||||
endDate: z.coerce.date(),
|
endDate: z.coerce.date(),
|
||||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||||
}))
|
}),
|
||||||
|
)
|
||||||
.query(async ({ ctx, input }) => buildResourceAvailabilityView(ctx.db, input)),
|
.query(async ({ ctx, input }) => buildResourceAvailabilityView(ctx.db, input)),
|
||||||
|
|
||||||
getResourceAvailabilitySummary: planningReadProcedure
|
getResourceAvailabilitySummary: planningReadProcedure
|
||||||
.input(z.object({
|
.input(
|
||||||
|
z.object({
|
||||||
resourceId: z.string(),
|
resourceId: z.string(),
|
||||||
startDate: z.coerce.date(),
|
startDate: z.coerce.date(),
|
||||||
endDate: z.coerce.date(),
|
endDate: z.coerce.date(),
|
||||||
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
||||||
}))
|
}),
|
||||||
|
)
|
||||||
.query(async ({ ctx, input }) => {
|
.query(async ({ ctx, input }) => {
|
||||||
const availability = await buildResourceAvailabilityView(ctx.db, input);
|
const availability = await buildResourceAvailabilityView(ctx.db, input);
|
||||||
return buildResourceAvailabilitySummary(availability, input);
|
return buildResourceAvailabilitySummary(availability, input);
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export {
|
|||||||
|
|
||||||
export {
|
export {
|
||||||
findAllocationEntry,
|
findAllocationEntry,
|
||||||
|
findAllocationEntries,
|
||||||
loadAllocationEntry,
|
loadAllocationEntry,
|
||||||
type AllocationEntryResolution,
|
type AllocationEntryResolution,
|
||||||
} from "./use-cases/allocation/load-allocation-entry.js";
|
} from "./use-cases/allocation/load-allocation-entry.js";
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ import type { Prisma, PrismaClient } from "@capakraken/db";
|
|||||||
import type { AllocationWithDetails } from "@capakraken/shared";
|
import type { AllocationWithDetails } from "@capakraken/shared";
|
||||||
import { TRPCError } from "@trpc/server";
|
import { TRPCError } from "@trpc/server";
|
||||||
import { buildSplitAllocationReadModel } from "./build-split-allocation-read-model.js";
|
import { buildSplitAllocationReadModel } from "./build-split-allocation-read-model.js";
|
||||||
import {
|
import { ASSIGNMENT_RELATIONS_INCLUDE, type AssignmentWithRelations } from "./create-assignment.js";
|
||||||
ASSIGNMENT_RELATIONS_INCLUDE,
|
|
||||||
type AssignmentWithRelations,
|
|
||||||
} from "./create-assignment.js";
|
|
||||||
import {
|
import {
|
||||||
DEMAND_REQUIREMENT_RELATIONS_INCLUDE,
|
DEMAND_REQUIREMENT_RELATIONS_INCLUDE,
|
||||||
type DemandRequirementWithRelations,
|
type DemandRequirementWithRelations,
|
||||||
@@ -40,9 +37,7 @@ function toDemandAllocationEntry(
|
|||||||
}).allocations[0] as AllocationWithDetails;
|
}).allocations[0] as AllocationWithDetails;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toAssignmentAllocationEntry(
|
function toAssignmentAllocationEntry(assignment: AssignmentWithRelations): AllocationWithDetails {
|
||||||
assignment: AssignmentWithRelations,
|
|
||||||
): AllocationWithDetails {
|
|
||||||
return buildSplitAllocationReadModel({
|
return buildSplitAllocationReadModel({
|
||||||
demandRequirements: [],
|
demandRequirements: [],
|
||||||
assignments: [assignment],
|
assignments: [assignment],
|
||||||
@@ -115,3 +110,50 @@ export async function loadAllocationEntry(
|
|||||||
|
|
||||||
return resolved;
|
return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Batch-loads allocation entries by ID (2 queries total instead of 2N).
|
||||||
|
* Each ID is resolved against both demand_requirements and assignments.
|
||||||
|
* IDs that don't match either table are silently skipped.
|
||||||
|
*/
|
||||||
|
export async function findAllocationEntries(
|
||||||
|
db: DbClient,
|
||||||
|
ids: string[],
|
||||||
|
): Promise<AllocationEntryResolution[]> {
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
|
||||||
|
const [demandRequirements, assignments] = await Promise.all([
|
||||||
|
db.demandRequirement.findMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
include: DEMAND_REQUIREMENT_RELATIONS_INCLUDE,
|
||||||
|
}),
|
||||||
|
db.assignment.findMany({
|
||||||
|
where: { id: { in: ids } },
|
||||||
|
include: ASSIGNMENT_RELATIONS_INCLUDE,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const results: AllocationEntryResolution[] = [];
|
||||||
|
|
||||||
|
for (const dr of demandRequirements) {
|
||||||
|
results.push({
|
||||||
|
kind: "demand",
|
||||||
|
entry: toDemandAllocationEntry(dr),
|
||||||
|
demandRequirement: dr,
|
||||||
|
projectId: dr.projectId,
|
||||||
|
resourceId: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const a of assignments) {
|
||||||
|
results.push({
|
||||||
|
kind: "assignment",
|
||||||
|
entry: toAssignmentAllocationEntry(a),
|
||||||
|
assignment: a,
|
||||||
|
projectId: a.projectId,
|
||||||
|
resourceId: a.resourceId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- Add missing indexes on foreign key columns used in filtering/joining.
|
||||||
|
-- These are CREATE INDEX IF NOT EXISTS so they are safe to re-run.
|
||||||
|
|
||||||
|
-- Resource: blueprintId and roleId are used in resource filtering and joins
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "resources_blueprintId_idx" ON "resources" ("blueprintId");
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "resources_roleId_idx" ON "resources" ("roleId");
|
||||||
|
|
||||||
|
-- DemandRequirement: roleId is used in role-based demand queries
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "demand_requirements_roleId_idx" ON "demand_requirements" ("roleId");
|
||||||
|
|
||||||
|
-- Assignment: roleId is used in role-based assignment queries
|
||||||
|
CREATE INDEX CONCURRENTLY IF NOT EXISTS "assignments_roleId_idx" ON "assignments" ("roleId");
|
||||||
@@ -914,6 +914,8 @@ model Resource {
|
|||||||
@@index([orgUnitId])
|
@@index([orgUnitId])
|
||||||
@@index([resourceType])
|
@@index([resourceType])
|
||||||
@@index([managementLevelGroupId])
|
@@index([managementLevelGroupId])
|
||||||
|
@@index([blueprintId])
|
||||||
|
@@index([roleId])
|
||||||
@@map("resources")
|
@@map("resources")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1323,6 +1325,7 @@ model DemandRequirement {
|
|||||||
@@index([startDate, endDate])
|
@@index([startDate, endDate])
|
||||||
@@index([status])
|
@@index([status])
|
||||||
@@index([projectId, status, startDate])
|
@@index([projectId, status, startDate])
|
||||||
|
@@index([roleId])
|
||||||
@@map("demand_requirements")
|
@@map("demand_requirements")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1362,6 +1365,7 @@ model Assignment {
|
|||||||
@@index([projectId, status, startDate, endDate])
|
@@index([projectId, status, startDate, endDate])
|
||||||
@@index([resourceId, status, endDate])
|
@@index([resourceId, status, endDate])
|
||||||
@@index([projectId, status, endDate])
|
@@index([projectId, status, endDate])
|
||||||
|
@@index([roleId])
|
||||||
@@map("assignments")
|
@@map("assignments")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user