/** * Service instances — unit D2 (ARCHITECTURE §5.1). * * `generateInstances()` is the daily cron job. For each active service it plans * the instances in the rolling window and upserts them on the * `(service_id, starts_at)` key. `onConflictDoNothing` makes the whole thing * idempotent: * * - a re-run finds the existing row and leaves it untouched, * - a `cancelled` instance stays cancelled (never regenerated), * - a `published` instance is never modified here, * - past instances fall outside the window and are never deleted. * * Slot materialization from role requirements is D3; this unit only owns the * instance rows. */ import { and, count, eq, gte } from "drizzle-orm"; import { db } from "@/db"; import { services, serviceInstances } from "@/db/schema"; import { uuidv7 } from "@/lib/uuid"; import { localToUtc } from "@/lib/tz"; import { planInstances, windowTarget, INSTANCE_WINDOW_WEEKS, type ServicePlanInput, } from "@/domain/instances"; export interface GenerateOptions { /** Reference "now". Defaults to the real clock; injectable for tests. */ now?: Date; /** Rolling window in weeks (default 16). */ windowWeeks?: number; } export interface GenerateResult { created: number; windowWeeks: number; from: string; to: string; } /** * Idempotent instance generation. Returns the number of instances created on * this run (0 on a clean re-run). See module doc for the invariants. */ export async function generateInstances(opts: GenerateOptions = {}): Promise { const now = opts.now ?? new Date(); const windowWeeks = opts.windowWeeks ?? INSTANCE_WINDOW_WEEKS; const target = windowTarget(now, windowWeeks); const active = await db.select().from(services).where(eq(services.active, true)); let created = 0; for (const service of active) { const plan: ServicePlanInput = { rrule: service.rrule!, startTimeLocal: service.startTimeLocal, timezone: service.timezone!, durationMinutes: service.durationMinutes, }; for (const inst of planInstances(plan, now, target)) { // onConflictDoNothing + returning() yields only the rows this run // actually inserted, so `created` counts genuine additions. const [row] = await db .insert(serviceInstances) .values({ id: uuidv7(), serviceId: service.id, occursOn: localToUtc(inst.occursOn, "00:00", service.timezone), startsAt: inst.startsAt, endsAt: inst.endsAt, status: "draft", }) .onConflictDoNothing({ target: [serviceInstances.serviceId, serviceInstances.startsAt], }) .returning(); if (row) created++; } } return { created, windowWeeks, from: now.toISOString(), to: target.toISOString(), }; } /** Count instances for a service within the rolling window (audit helper). */ export async function countInstances(serviceId: string, now?: Date): Promise { const start = (now ?? new Date()).toISOString(); const [row] = await db .select({ count: count() }) .from(serviceInstances) .where( and( eq(serviceInstances.serviceId, serviceId), gte(serviceInstances.startsAt, new Date(start)), ), ); return Number(row?.count ?? 0); }