761 lines
25 KiB
TypeScript
761 lines
25 KiB
TypeScript
import {
|
|
buildSplitAllocationReadModel,
|
|
createAssignment,
|
|
createDemandRequirement,
|
|
deleteAssignment,
|
|
deleteAllocationEntry,
|
|
deleteDemandRequirement,
|
|
fillOpenDemand,
|
|
loadAllocationEntry,
|
|
updateAllocationEntry,
|
|
updateAssignment,
|
|
updateDemandRequirement,
|
|
} from "@capakraken/application";
|
|
import {
|
|
AllocationStatus,
|
|
CreateAllocationSchema,
|
|
CreateAssignmentSchema,
|
|
CreateDemandRequirementSchema,
|
|
FillDemandRequirementSchema,
|
|
FillOpenDemandByAllocationSchema,
|
|
PermissionKey,
|
|
UpdateAssignmentSchema,
|
|
UpdateAllocationSchema,
|
|
UpdateDemandRequirementSchema,
|
|
} from "@capakraken/shared";
|
|
import { TRPCError } from "@trpc/server";
|
|
import { z } from "zod";
|
|
import { findUniqueOrThrow } from "../db/helpers.js";
|
|
import { anonymizeResource, getAnonymizationDirectory } from "../lib/anonymization.js";
|
|
import { emitAllocationCreated, emitAllocationDeleted, emitAllocationUpdated } from "../sse/event-bus.js";
|
|
import { buildResourceAvailabilitySummary, buildResourceAvailabilityView } from "./allocation-availability.js";
|
|
import {
|
|
checkBudgetThresholdsInBackground,
|
|
createDemandRequirementWithEffects,
|
|
dispatchAllocationWebhookInBackground,
|
|
fillDemandRequirementWithEffects,
|
|
invalidateDashboardCacheInBackground,
|
|
} from "./allocation-effects.js";
|
|
import {
|
|
ASSIGNMENT_INCLUDE,
|
|
DEMAND_INCLUDE,
|
|
toIsoDate,
|
|
} from "./allocation-shared.js";
|
|
import {
|
|
buildCreateDemandRequirementInput,
|
|
findAllocationEntryOrNull,
|
|
getDemandRequirementByIdOrThrow,
|
|
loadAllocationReadModel,
|
|
resolveAssignmentBySelection,
|
|
toAssignmentUpdateInput,
|
|
toDemandRequirementUpdateInput,
|
|
} from "./allocation-support.js";
|
|
import { createTRPCRouter, managerProcedure, planningReadProcedure, requirePermission } from "../trpc.js";
|
|
|
|
export const allocationRouter = createTRPCRouter({
|
|
list: planningReadProcedure
|
|
.input(
|
|
z.object({
|
|
projectId: z.string().optional(),
|
|
resourceId: z.string().optional(),
|
|
status: z.nativeEnum(AllocationStatus).optional(),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => {
|
|
const readModel = await loadAllocationReadModel(ctx.db, input);
|
|
return readModel.allocations;
|
|
}),
|
|
|
|
listView: planningReadProcedure
|
|
.input(
|
|
z.object({
|
|
projectId: z.string().optional(),
|
|
resourceId: z.string().optional(),
|
|
status: z.nativeEnum(AllocationStatus).optional(),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => loadAllocationReadModel(ctx.db, input)),
|
|
|
|
create: managerProcedure
|
|
.input(CreateAllocationSchema)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const allocation = await ctx.db.$transaction(async (tx) => {
|
|
if (!input.resourceId) {
|
|
const demandRequirement = await createDemandRequirement(
|
|
tx as unknown as Parameters<typeof createDemandRequirement>[0],
|
|
{
|
|
projectId: input.projectId,
|
|
startDate: input.startDate,
|
|
endDate: input.endDate,
|
|
hoursPerDay: input.hoursPerDay,
|
|
percentage: input.percentage,
|
|
role: input.role,
|
|
roleId: input.roleId,
|
|
headcount: input.headcount,
|
|
status: input.status,
|
|
metadata: input.metadata,
|
|
},
|
|
);
|
|
|
|
return buildSplitAllocationReadModel({
|
|
demandRequirements: [demandRequirement],
|
|
assignments: [],
|
|
}).allocations[0]!;
|
|
}
|
|
|
|
const assignment = await createAssignment(
|
|
tx as unknown as Parameters<typeof createAssignment>[0],
|
|
{
|
|
resourceId: input.resourceId,
|
|
projectId: input.projectId,
|
|
startDate: input.startDate,
|
|
endDate: input.endDate,
|
|
hoursPerDay: input.hoursPerDay,
|
|
percentage: input.percentage,
|
|
role: input.role,
|
|
roleId: input.roleId,
|
|
status: input.status,
|
|
metadata: input.metadata,
|
|
},
|
|
);
|
|
|
|
return buildSplitAllocationReadModel({
|
|
demandRequirements: [],
|
|
assignments: [assignment],
|
|
}).allocations[0]!;
|
|
});
|
|
|
|
emitAllocationCreated({
|
|
id: allocation.id,
|
|
projectId: allocation.projectId,
|
|
resourceId: allocation.resourceId,
|
|
});
|
|
dispatchAllocationWebhookInBackground(ctx.db, "allocation.created", {
|
|
id: allocation.id,
|
|
projectId: allocation.projectId,
|
|
resourceId: allocation.resourceId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, allocation.projectId);
|
|
return allocation;
|
|
}),
|
|
|
|
listDemands: planningReadProcedure
|
|
.input(
|
|
z.object({
|
|
projectId: z.string().optional(),
|
|
status: z.nativeEnum(AllocationStatus).optional(),
|
|
roleId: z.string().optional(),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => {
|
|
const demands = await ctx.db.demandRequirement.findMany({
|
|
where: {
|
|
...(input.projectId ? { projectId: input.projectId } : {}),
|
|
...(input.status ? { status: input.status } : {}),
|
|
...(input.roleId ? { roleId: input.roleId } : {}),
|
|
},
|
|
include: DEMAND_INCLUDE,
|
|
orderBy: { startDate: "asc" },
|
|
});
|
|
const dir = await getAnonymizationDirectory(ctx.db);
|
|
if (!dir) return demands;
|
|
return demands.map((d) => ({
|
|
...d,
|
|
assignments: d.assignments.map((a) =>
|
|
a.resource ? { ...a, resource: anonymizeResource(a.resource, dir) } : a,
|
|
),
|
|
}));
|
|
}),
|
|
|
|
listAssignments: planningReadProcedure
|
|
.input(
|
|
z.object({
|
|
projectId: z.string().optional(),
|
|
resourceId: z.string().optional(),
|
|
status: z.nativeEnum(AllocationStatus).optional(),
|
|
demandRequirementId: z.string().optional(),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => {
|
|
const assignments = await ctx.db.assignment.findMany({
|
|
where: {
|
|
...(input.projectId ? { projectId: input.projectId } : {}),
|
|
...(input.resourceId ? { resourceId: input.resourceId } : {}),
|
|
...(input.status ? { status: input.status } : {}),
|
|
...(input.demandRequirementId ? { demandRequirementId: input.demandRequirementId } : {}),
|
|
},
|
|
include: ASSIGNMENT_INCLUDE,
|
|
orderBy: { startDate: "asc" },
|
|
});
|
|
const dir = await getAnonymizationDirectory(ctx.db);
|
|
if (!dir) return assignments;
|
|
return assignments.map((a) =>
|
|
a.resource ? { ...a, resource: anonymizeResource(a.resource, dir) } : a,
|
|
);
|
|
}),
|
|
|
|
getAssignmentById: planningReadProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.query(async ({ ctx, input }) => {
|
|
const assignment = await findUniqueOrThrow(
|
|
ctx.db.assignment.findUnique({
|
|
where: { id: input.id },
|
|
include: ASSIGNMENT_INCLUDE,
|
|
}),
|
|
"Assignment",
|
|
);
|
|
const dir = await getAnonymizationDirectory(ctx.db);
|
|
if (!dir || !assignment.resource) {
|
|
return assignment;
|
|
}
|
|
return {
|
|
...assignment,
|
|
resource: anonymizeResource(assignment.resource, dir),
|
|
};
|
|
}),
|
|
|
|
resolveAssignment: planningReadProcedure
|
|
.input(z.object({
|
|
assignmentId: z.string().optional(),
|
|
resourceId: z.string().optional(),
|
|
projectId: z.string().optional(),
|
|
startDate: z.coerce.date().optional(),
|
|
endDate: z.coerce.date().optional(),
|
|
selectionMode: z.enum(["WINDOW", "EXACT_START"]).default("EXACT_START"),
|
|
excludeCancelled: z.boolean().default(false),
|
|
}))
|
|
.query(async ({ ctx, input }) => resolveAssignmentBySelection(ctx.db, input)),
|
|
|
|
getDemandRequirementById: planningReadProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.query(async ({ ctx, input }) => getDemandRequirementByIdOrThrow(ctx.db, input.id)),
|
|
|
|
/**
|
|
* Check a resource's availability for a date range.
|
|
* Returns working days, existing allocations, conflict days, and available capacity.
|
|
*/
|
|
checkResourceAvailability: planningReadProcedure
|
|
.input(z.object({
|
|
resourceId: z.string(),
|
|
startDate: z.coerce.date(),
|
|
endDate: z.coerce.date(),
|
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
|
}))
|
|
.query(async ({ ctx, input }) => {
|
|
const { vacations: _vacations, ...availability } = await buildResourceAvailabilityView(ctx.db, input);
|
|
return availability;
|
|
}),
|
|
|
|
getResourceAvailabilityView: planningReadProcedure
|
|
.input(z.object({
|
|
resourceId: z.string(),
|
|
startDate: z.coerce.date(),
|
|
endDate: z.coerce.date(),
|
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
|
}))
|
|
.query(async ({ ctx, input }) => buildResourceAvailabilityView(ctx.db, input)),
|
|
|
|
getResourceAvailabilitySummary: planningReadProcedure
|
|
.input(z.object({
|
|
resourceId: z.string(),
|
|
startDate: z.coerce.date(),
|
|
endDate: z.coerce.date(),
|
|
hoursPerDay: z.number().min(0.5).max(24).default(8),
|
|
}))
|
|
.query(async ({ ctx, input }) => {
|
|
const availability = await buildResourceAvailabilityView(ctx.db, input);
|
|
return buildResourceAvailabilitySummary(availability, input);
|
|
}),
|
|
|
|
createDemandRequirement: managerProcedure
|
|
.input(CreateDemandRequirementSchema)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
return createDemandRequirementWithEffects(ctx.db, input);
|
|
}),
|
|
|
|
createDemand: managerProcedure
|
|
.input(z.object({
|
|
projectId: z.string(),
|
|
role: z.string().optional(),
|
|
roleId: z.string().optional(),
|
|
headcount: z.number().int().positive().default(1),
|
|
hoursPerDay: z.number().min(0.5).max(24),
|
|
startDate: z.coerce.date(),
|
|
endDate: z.coerce.date(),
|
|
budgetCents: z.number().int().min(0).optional(),
|
|
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
}))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
return createDemandRequirementWithEffects(
|
|
ctx.db,
|
|
buildCreateDemandRequirementInput(input),
|
|
);
|
|
}),
|
|
|
|
updateDemandRequirement: managerProcedure
|
|
.input(z.object({ id: z.string(), data: UpdateDemandRequirementSchema }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const updated = await ctx.db.$transaction(async (tx) => {
|
|
return updateDemandRequirement(
|
|
tx as unknown as Parameters<typeof updateDemandRequirement>[0],
|
|
input.id,
|
|
input.data,
|
|
);
|
|
});
|
|
|
|
emitAllocationUpdated({
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: null,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, updated.projectId);
|
|
|
|
return updated;
|
|
}),
|
|
|
|
createAssignment: managerProcedure
|
|
.input(CreateAssignmentSchema)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const assignment = await ctx.db.$transaction(async (tx) => {
|
|
return createAssignment(
|
|
tx as unknown as Parameters<typeof createAssignment>[0],
|
|
input,
|
|
);
|
|
});
|
|
|
|
emitAllocationCreated({
|
|
id: assignment.id,
|
|
projectId: assignment.projectId,
|
|
resourceId: assignment.resourceId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, assignment.projectId);
|
|
|
|
return assignment;
|
|
}),
|
|
|
|
ensureAssignment: managerProcedure
|
|
.input(z.object({
|
|
resourceId: z.string(),
|
|
projectId: z.string(),
|
|
startDate: z.coerce.date(),
|
|
endDate: z.coerce.date(),
|
|
hoursPerDay: z.number().min(0.5).max(24),
|
|
role: z.string().optional(),
|
|
}))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const existing = (await ctx.db.assignment.findMany({
|
|
where: {
|
|
resourceId: input.resourceId,
|
|
projectId: input.projectId,
|
|
},
|
|
include: ASSIGNMENT_INCLUDE,
|
|
orderBy: { startDate: "asc" },
|
|
})).find((assignment) => (
|
|
toIsoDate(assignment.startDate) === toIsoDate(input.startDate)
|
|
&& toIsoDate(assignment.endDate) === toIsoDate(input.endDate)
|
|
));
|
|
|
|
if (existing) {
|
|
if (existing.status !== AllocationStatus.CANCELLED) {
|
|
throw new TRPCError({
|
|
code: "CONFLICT",
|
|
message: `An allocation already exists for this resource/project/dates with status ${existing.status}.`,
|
|
});
|
|
}
|
|
|
|
const resource = await ctx.db.resource.findUnique({
|
|
where: { id: input.resourceId },
|
|
select: { lcrCents: true },
|
|
});
|
|
if (!resource) {
|
|
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
|
|
}
|
|
|
|
const updated = await ctx.db.$transaction(async (tx) => updateAssignment(
|
|
tx as unknown as Parameters<typeof updateAssignment>[0],
|
|
existing.id,
|
|
{
|
|
status: AllocationStatus.PROPOSED,
|
|
hoursPerDay: input.hoursPerDay,
|
|
percentage: (input.hoursPerDay / 8) * 100,
|
|
dailyCostCents: Math.round(resource.lcrCents * input.hoursPerDay),
|
|
...(input.role ? { role: input.role } : {}),
|
|
},
|
|
));
|
|
|
|
emitAllocationUpdated({
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: updated.resourceId,
|
|
});
|
|
dispatchAllocationWebhookInBackground(ctx.db, "allocation.updated", {
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: updated.resourceId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, updated.projectId);
|
|
|
|
return { assignment: updated, action: "reactivated" as const };
|
|
}
|
|
|
|
const assignment = await ctx.db.$transaction(async (tx) => createAssignment(
|
|
tx as unknown as Parameters<typeof createAssignment>[0],
|
|
{
|
|
resourceId: input.resourceId,
|
|
projectId: input.projectId,
|
|
startDate: input.startDate,
|
|
endDate: input.endDate,
|
|
hoursPerDay: input.hoursPerDay,
|
|
percentage: (input.hoursPerDay / 8) * 100,
|
|
status: AllocationStatus.PROPOSED,
|
|
metadata: {},
|
|
...(input.role ? { role: input.role } : {}),
|
|
},
|
|
));
|
|
|
|
emitAllocationCreated({
|
|
id: assignment.id,
|
|
projectId: assignment.projectId,
|
|
resourceId: assignment.resourceId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, assignment.projectId);
|
|
|
|
return { assignment, action: "created" as const };
|
|
}),
|
|
|
|
updateAssignment: managerProcedure
|
|
.input(z.object({ id: z.string(), data: UpdateAssignmentSchema }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const existing = await findUniqueOrThrow(
|
|
ctx.db.assignment.findUnique({
|
|
where: { id: input.id },
|
|
select: { resourceId: true },
|
|
}),
|
|
"Assignment",
|
|
);
|
|
|
|
const updated = await ctx.db.$transaction(async (tx) => {
|
|
return updateAssignment(
|
|
tx as unknown as Parameters<typeof updateAssignment>[0],
|
|
input.id,
|
|
input.data,
|
|
);
|
|
});
|
|
|
|
emitAllocationUpdated({
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: updated.resourceId,
|
|
resourceIds: [existing.resourceId, updated.resourceId],
|
|
});
|
|
dispatchAllocationWebhookInBackground(ctx.db, "allocation.updated", {
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: updated.resourceId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, updated.projectId);
|
|
|
|
return updated;
|
|
}),
|
|
|
|
deleteDemandRequirement: managerProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const existing = await findUniqueOrThrow(
|
|
ctx.db.demandRequirement.findUnique({
|
|
where: { id: input.id },
|
|
include: DEMAND_INCLUDE,
|
|
}),
|
|
"Demand requirement",
|
|
);
|
|
|
|
await ctx.db.$transaction(async (tx) => {
|
|
await deleteDemandRequirement(
|
|
tx as unknown as Parameters<typeof deleteDemandRequirement>[0],
|
|
input.id,
|
|
);
|
|
|
|
await tx.auditLog.create({
|
|
data: {
|
|
entityType: "DemandRequirement",
|
|
entityId: input.id,
|
|
action: "DELETE",
|
|
changes: { before: existing } as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
});
|
|
|
|
emitAllocationDeleted(existing.id, existing.projectId);
|
|
dispatchAllocationWebhookInBackground(ctx.db, "allocation.deleted", {
|
|
id: existing.id,
|
|
projectId: existing.projectId,
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, existing.projectId);
|
|
|
|
return { success: true };
|
|
}),
|
|
|
|
fillDemandRequirement: managerProcedure
|
|
.input(FillDemandRequirementSchema)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
return fillDemandRequirementWithEffects(ctx.db, input);
|
|
}),
|
|
|
|
assignResourceToDemand: managerProcedure
|
|
.input(z.object({
|
|
demandRequirementId: z.string(),
|
|
resourceId: z.string(),
|
|
}))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const result = await fillDemandRequirementWithEffects(ctx.db, input);
|
|
const demandRequirement = await getDemandRequirementByIdOrThrow(
|
|
ctx.db,
|
|
input.demandRequirementId,
|
|
);
|
|
|
|
return {
|
|
...result,
|
|
demandRequirement,
|
|
};
|
|
}),
|
|
|
|
fillOpenDemandByAllocation: managerProcedure
|
|
.input(FillOpenDemandByAllocationSchema)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const result = await fillOpenDemand(ctx.db, input);
|
|
|
|
emitAllocationCreated(result.createdAllocation);
|
|
|
|
if (result.updatedAllocation) {
|
|
emitAllocationUpdated(result.updatedAllocation);
|
|
}
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, result.createdAllocation.projectId as string);
|
|
|
|
return result;
|
|
}),
|
|
|
|
update: managerProcedure
|
|
.input(z.object({ id: z.string(), data: UpdateAllocationSchema }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const existing = await loadAllocationEntry(ctx.db, input.id);
|
|
|
|
const updated = await ctx.db.$transaction(async (tx) => {
|
|
const { allocation: updatedAllocation } = await updateAllocationEntry(
|
|
tx as unknown as Parameters<typeof updateAllocationEntry>[0],
|
|
{
|
|
id: input.id,
|
|
demandRequirementUpdate:
|
|
existing.kind === "assignment" ? {} : toDemandRequirementUpdateInput(input.data),
|
|
assignmentUpdate:
|
|
existing.kind === "demand" ? {} : toAssignmentUpdateInput(input.data),
|
|
},
|
|
);
|
|
|
|
await tx.auditLog.create({
|
|
data: {
|
|
entityType: "Allocation",
|
|
entityId: input.id,
|
|
action: "UPDATE",
|
|
changes: {
|
|
before: existing.entry,
|
|
after: updatedAllocation,
|
|
} as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
|
|
return updatedAllocation;
|
|
});
|
|
|
|
emitAllocationUpdated({
|
|
id: updated.id,
|
|
projectId: updated.projectId,
|
|
resourceId: updated.resourceId,
|
|
resourceIds: [existing.entry.resourceId, updated.resourceId],
|
|
});
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, updated.projectId);
|
|
|
|
return updated;
|
|
}),
|
|
|
|
deleteAssignment: managerProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
|
|
const existing = await findUniqueOrThrow(
|
|
ctx.db.assignment.findUnique({
|
|
where: { id: input.id },
|
|
include: ASSIGNMENT_INCLUDE,
|
|
}),
|
|
"Assignment",
|
|
);
|
|
|
|
await ctx.db.$transaction(async (tx) => {
|
|
await deleteAssignment(
|
|
tx as unknown as Parameters<typeof deleteAssignment>[0],
|
|
input.id,
|
|
);
|
|
|
|
await tx.auditLog.create({
|
|
data: {
|
|
entityType: "Assignment",
|
|
entityId: input.id,
|
|
action: "DELETE",
|
|
changes: { before: existing } as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
});
|
|
|
|
emitAllocationDeleted(existing.id, existing.projectId, existing.resourceId);
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, existing.projectId);
|
|
|
|
return { success: true };
|
|
}),
|
|
|
|
delete: managerProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const existing = await loadAllocationEntry(ctx.db, input.id);
|
|
|
|
await ctx.db.$transaction(async (tx) => {
|
|
await deleteAllocationEntry(
|
|
tx as unknown as Parameters<typeof deleteAllocationEntry>[0],
|
|
existing,
|
|
);
|
|
|
|
await tx.auditLog.create({
|
|
data: {
|
|
entityType: "Allocation",
|
|
entityId: input.id,
|
|
action: "DELETE",
|
|
changes: { before: existing.entry } as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
});
|
|
|
|
emitAllocationDeleted(existing.entry.id, existing.projectId, existing.entry.resourceId);
|
|
invalidateDashboardCacheInBackground();
|
|
checkBudgetThresholdsInBackground(ctx.db, existing.projectId);
|
|
|
|
return { success: true };
|
|
}),
|
|
|
|
batchDelete: managerProcedure
|
|
.input(z.object({ ids: z.array(z.string()).min(1).max(100) }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const existing = (
|
|
await Promise.all(input.ids.map(async (id) => findAllocationEntryOrNull(ctx.db, id)))
|
|
).filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));
|
|
|
|
await ctx.db.$transaction(async (tx) => {
|
|
for (const allocation of existing) {
|
|
await deleteAllocationEntry(
|
|
tx as unknown as Parameters<typeof deleteAllocationEntry>[0],
|
|
allocation,
|
|
);
|
|
}
|
|
await tx.auditLog.create({
|
|
data: {
|
|
entityType: "Allocation",
|
|
entityId: input.ids.join(","),
|
|
action: "DELETE",
|
|
changes: {
|
|
before: existing.map((a) => ({ id: a.entry.id, projectId: a.projectId })),
|
|
} as unknown as import("@capakraken/db").Prisma.InputJsonValue,
|
|
},
|
|
});
|
|
});
|
|
|
|
for (const a of existing) {
|
|
emitAllocationDeleted(a.entry.id, a.projectId, a.entry.resourceId);
|
|
}
|
|
invalidateDashboardCacheInBackground();
|
|
// Check budget thresholds for each affected project
|
|
const affectedProjectIds = [...new Set(existing.map((a) => a.projectId))];
|
|
for (const pid of affectedProjectIds) {
|
|
checkBudgetThresholdsInBackground(ctx.db, pid);
|
|
}
|
|
|
|
return { count: existing.length };
|
|
}),
|
|
|
|
batchUpdateStatus: managerProcedure
|
|
.input(
|
|
z.object({
|
|
ids: z.array(z.string()).min(1).max(100),
|
|
status: z.nativeEnum(AllocationStatus),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
requirePermission(ctx, PermissionKey.MANAGE_ALLOCATIONS);
|
|
const updated = await ctx.db.$transaction(async (tx) => {
|
|
const updatedAllocations = await Promise.all(
|
|
input.ids.map(async (id) =>
|
|
(
|
|
await updateAllocationEntry(
|
|
tx as unknown as Parameters<typeof updateAllocationEntry>[0],
|
|
{
|
|
id,
|
|
demandRequirementUpdate: { status: input.status },
|
|
assignmentUpdate: { status: input.status },
|
|
},
|
|
)
|
|
).allocation,
|
|
),
|
|
);
|
|
|
|
return updatedAllocations;
|
|
});
|
|
|
|
await ctx.db.auditLog.create({
|
|
data: {
|
|
entityType: "Allocation",
|
|
entityId: input.ids.join(","),
|
|
action: "UPDATE",
|
|
changes: { after: { status: input.status, ids: input.ids } },
|
|
},
|
|
});
|
|
|
|
for (const a of updated) {
|
|
emitAllocationUpdated({ id: a.id, projectId: a.projectId, resourceId: a.resourceId });
|
|
}
|
|
invalidateDashboardCacheInBackground();
|
|
// Check budget thresholds for each affected project
|
|
const affectedProjectIds = [...new Set(updated.map((a) => a.projectId))];
|
|
for (const pid of affectedProjectIds) {
|
|
checkBudgetThresholdsInBackground(ctx.db, pid);
|
|
}
|
|
|
|
return { count: updated.length };
|
|
}),
|
|
});
|