/** * Slot materialization — unit D3 (ARCHITECTURE §5.2). * * `materializeSlots()` turns the seats `planSlots()` computes into `slots` * rows. Idempotent on `(service_instance_id, role_id, slot_index)` via * `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's * assignments on an existing seat. * * Per §5.1, slots are created only for non-published instances: a published * week's slot set is owned by the publish flow, not the generator. */ import { and, gte, ne } from "drizzle-orm"; import { db } from "@/db"; import { roles, serviceInstances, slots } from "@/db/schema"; import { uuidv7 } from "@/lib/uuid"; import { planSlots, type RolePlanInput } from "@/domain/slots"; /** * Materialize the seats for one instance. Returns the number of seats created * this run (0 on a clean re-run). */ export async function materializeSlotsForInstance( serviceInstanceId: string, instanceStartsAt: Date, rolesInput: RolePlanInput[], ): Promise { const plan = planSlots(instanceStartsAt, rolesInput); let created = 0; for (const seat of plan) { const [row] = await db .insert(slots) .values({ id: uuidv7(), serviceInstanceId, eventId: null, roleId: seat.roleId, slotIndex: seat.slotIndex, callTime: seat.callTime, status: "open", }) .onConflictDoNothing({ target: [ slots.serviceInstanceId, slots.roleId, slots.slotIndex, ], }) .returning(); if (row) created++; } return created; } /** * Materialize slots for every non-published instance at or after `now`. * Published instances are left untouched (their slot set is owned by the * publish flow). */ export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> { const reference = now ?? new Date(); const instances = await db .select() .from(serviceInstances) .where( and( gte(serviceInstances.startsAt, reference), ne(serviceInstances.status, "published"), ), ); const roleRows = await db.select().from(roles).orderBy(roles.sortOrder); const rolesInput: RolePlanInput[] = roleRows.map((r) => ({ id: r.id, callTimeOffsetMinutes: r.callTimeOffsetMinutes, defaultHeadcount: r.defaultHeadcount, })); let created = 0; for (const inst of instances) { if (!inst.startsAt) continue; created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput); } return { created, instances: instances.length }; }