/** * Post-service completion — the job that turns yesterday's schedule into * history. Without it nothing ever sets `assignment.completed`, * `user_skills.last_served_on` or `users.last_served_at`, so staleness, * readiness and fairness reports would stay frozen at seed values. * * Runs from `/api/dev/cron/complete`. Idempotent: only `proposed`/`confirmed` * assignments on a published instance that has already ended are touched, and * a completed assignment is never selected again. */ import { and, eq, inArray, isNotNull, lt, sql } from "drizzle-orm"; import { db } from "@/db"; import { assignments, positionSkills, serviceInstances, slots, userSkills, users, } from "@/db/schema"; export interface CompleteSummary { assignmentsCompleted: number; userSkillsUpdated: number; usersUpdated: number; } function isoDateUTC(date: Date | null): string { if (!date) return ""; return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String( date.getUTCDate(), ).padStart(2, "0")}`; } export async function completePastAssignments( opts: { now?: Date } = {}, ): Promise { const now = opts.now ?? new Date(); return db.transaction(async (tx): Promise => { const finished = await tx .select({ assignmentId: assignments.id, userId: assignments.userId, slotId: slots.id, roleId: slots.roleId, occursOn: serviceInstances.occursOn, endsAt: serviceInstances.endsAt, }) .from(assignments) .innerJoin(slots, eq(slots.id, assignments.slotId)) .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId)) .where( and( inArray(assignments.status, ["proposed", "confirmed"]), eq(serviceInstances.status, "published"), isNotNull(serviceInstances.endsAt), lt(serviceInstances.endsAt, now), ), ); if (finished.length === 0) { return { assignmentsCompleted: 0, userSkillsUpdated: 0, usersUpdated: 0 }; } const completed = await tx .update(assignments) .set({ status: "completed" }) .where( inArray( assignments.id, finished.map((row) => row.assignmentId), ), ) .returning({ id: assignments.id }); let userSkillsUpdated = 0; let usersUpdated = 0; for (const row of finished) { const servedOn = isoDateUTC(row.occursOn); if (!servedOn) continue; // Move the served date on every skill the position requires, but only // forward (a later service must not be overwritten by an older one). const skillRows = await tx .select({ skillId: positionSkills.skillId }) .from(positionSkills) .where(eq(positionSkills.positionId, row.roleId)); for (const skill of skillRows) { const updated = await tx .update(userSkills) .set({ lastServedOn: servedOn }) .where( and( eq(userSkills.userId, row.userId), eq(userSkills.skillId, skill.skillId), sql`(${userSkills.lastServedOn} IS NULL OR ${userSkills.lastServedOn} < ${servedOn})`, ), ) .returning({ id: userSkills.id }); userSkillsUpdated += updated.length; } const servedAt = row.endsAt ?? row.occursOn ?? now; const touched = await tx .update(users) .set({ lastServedAt: servedAt, updatedAt: now }) .where( and( eq(users.id, row.userId), sql`(${users.lastServedAt} IS NULL OR ${users.lastServedAt} < ${servedAt})`, ), ) .returning({ id: users.id }); usersUpdated += touched.length; } return { assignmentsCompleted: completed.length, userSkillsUpdated, usersUpdated, }; }); }