From 8fb6459b0db3d0f120cef98fb257e3f3b28a8b2c Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Wed, 18 Nov 2026 05:17:11 +0000 Subject: [PATCH] unit(D2): idempotent instance generator (16-week window) on cron route MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Service instance generation (ARCHITECTURE §5.1): for each active service, plan instances in the rolling window and upsert on (service_id, starts_at). onConflictDoNothing makes the whole thing idempotent — a re-run creates 0 rows, cancelled/published instances are never touched, past instances are never deleted. - src/domain/instances.ts: pure planInstances() + windowTarget(); DST-safe instants via localToUtc, no DB imports. - src/domain/instances.test.ts: 7 tests (window boundary, DST-safe instants, determinism, biweekly phase, monthly-nth, windowTarget). - src/db/instances.ts: generateInstances() idempotent upsert; occurs_on stored as zoned midnight (no UTC-midnight shift). - src/app/api/dev/cron/instances/route.ts: GET drives the daily job. No schema change (service_instances unique index predates this unit; slot materialization stays deferred to D3). Verified: run twice -> 0 created, count unchanged; published instances byte-identical; generated instances stored as DST-safe UTC instants. --- .agent/PROGRESS.md | 27 ++++++ src/app/api/dev/cron/instances/route.ts | 15 ++++ src/db/instances.ts | 106 ++++++++++++++++++++++++ src/domain/instances.test.ts | 88 ++++++++++++++++++++ src/domain/instances.ts | 70 ++++++++++++++++ 5 files changed, 306 insertions(+) create mode 100644 src/app/api/dev/cron/instances/route.ts create mode 100644 src/db/instances.ts create mode 100644 src/domain/instances.test.ts create mode 100644 src/domain/instances.ts diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 89b76e7..a280f59 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -448,6 +448,33 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e --- +## D2 — Instance generator (idempotent, 16-week window) — DONE 2026-11-18 + +**Scope (from BUILD-PLAN.md):** instance generator (idempotent, 16-week window) on a cron route. Done when: run twice → instance count unchanged; published instance untouched. ARCHITECTURE §5.1. + +**Delivered:** +- `src/domain/instances.ts` — pure `planInstances(service, now, target)` turns a service's rrule into the UTC instants it occurs at inside a window (uses `expandRRULE` + `localToUtc`). `windowTarget(now, weeks)` = now + 16 weeks (default `INSTANCE_WINDOW_WEEKS`). Pure — no DB imports. +- `src/domain/instances.test.ts` — 7 tests named after the rule: window boundary (exactly the Sundays in [now, now+3w]), endsAt = start + duration, DST-safe instants (9 AM local stays 9 AM across spring-forward; stored UTC shifts EST→EDT), determinism (same input → same instants, which is what makes the upsert idempotent), biweekly phase, monthly-nth across a year boundary, windowTarget default (16 weeks = 112 days). +- `src/db/instances.ts` — `generateInstances({ now, windowWeeks })` iterates active services, plans each, and upserts on `(service_id, starts_at)` via `onConflictDoNothing`. That single primitive gives every invariant: 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. `occurs_on` stored via `localToUtc(date, "00:00", tz)` to avoid a UTC-midnight DST shift (matches the seed). +- `src/app/api/dev/cron/instances/route.ts` — GET `/api/dev/cron/instances` drives `generateInstances()` daily (cron `0 6 * * *`). + +**No schema change, no migration.** The `service_instances` table already exists (A2) with the `(service_id, starts_at)` unique index that makes generation idempotent. Slot materialization from role requirements stays deferred to D3. + +**Verification (all exit 0):** +- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**125** total; D2 = 7) · `next build` ✓ +- Runtime smoke test (cron route): run twice → **0 rows created on re-run**, instance count unchanged (36 == 36); published instances byte-identical before/after (`diff` empty); generated draft instances stored as DST-safe UTC instants (11:00 ET = 16:00 UTC). + +**Decisions:** +- **Idempotency is one primitive, not a branch.** `onConflictDoNothing({ target: [service_id, starts_at] })` returns only rows this run actually inserted, so `created` counts genuine additions and every "don't touch" invariant falls out of the unique key rather than being re-implemented per status. +- **`planInstances` is pure; the upsert is idempotent because planning is deterministic.** Same (service, now, target) → same instants → same conflict keys. The DST test asserts the *instant* shifts, not the local wall clock, so a 9 AM Sunday stays 9 AM across the transition. +- **`occurs_on` stored as a zoned midnight, not `new Date("YYYY-MM-DD")`.** A bare string parse lands at UTC midnight, which renders back a day early in the church timezone; `localToUtc(date, "00:00", tz)` matches the seed and keeps the local date stable. +- **Window edge is approximate by design.** `windowTarget` adds 16×7 UTC days; the DST hour at the 16-week boundary is irrelevant since the window is a rolling horizon, not a precise instant. +- **Build cache reclaimed.** A prior interrupted `next build` left root-owned files under `.next/` (same class as the earlier `.git/objects` scrub) that blocked rebuilds; `sudo chown -R bhursey:bhursey .next` restored the build. The stale `next start` on :3000 was restarted after the build so the new cron route loaded. Test-generated draft instances were deleted to restore the seed state. + +**Next: D3 — slot materialization from `position_skills`/requirements (headcount, call time).** + +--- + ## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18 **Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `pnpm test recurrence` green on 5 named cases — spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable. ARCHITECTURE §4.3 / §5.1 / §5.8.3. diff --git a/src/app/api/dev/cron/instances/route.ts b/src/app/api/dev/cron/instances/route.ts new file mode 100644 index 0000000..0288658 --- /dev/null +++ b/src/app/api/dev/cron/instances/route.ts @@ -0,0 +1,15 @@ +import { generateInstances } from "@/db/instances"; + +/** + * Daily instance generator (ARCHITECTURE §5.1). Cron `0 6 * * *` (church-local + * 06:00, expressed in UTC) calls this. Idempotent — a re-run creates 0 rows. + * + * GET /api/dev/cron/instances + */ +export const GET = async () => { + const result = await generateInstances(); + return new Response(JSON.stringify({ result }), { + status: 200, + headers: { "content-type": "application/json" }, + }); +}; diff --git a/src/db/instances.ts b/src/db/instances.ts new file mode 100644 index 0000000..fcad9f6 --- /dev/null +++ b/src/db/instances.ts @@ -0,0 +1,106 @@ +/** + * 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); +} diff --git a/src/domain/instances.test.ts b/src/domain/instances.test.ts new file mode 100644 index 0000000..e558b43 --- /dev/null +++ b/src/domain/instances.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; +import { planInstances, windowTarget, INSTANCE_WINDOW_WEEKS } from "./instances"; + +const TZ = "America/New_York"; + +const weeklyService = { + rrule: "FREQ=WEEKLY;BYDAY=SU", + startTimeLocal: "09:00", + timezone: TZ, + durationMinutes: 75, +}; + +/** YYYY-MM-DD of a UTC instant rendered in the church timezone. */ +const localDay = (d: Date) => + `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String( + d.getUTCDate(), + ).padStart(2, "0")}`; + +describe("planInstances — window boundary", () => { + it("emits exactly the Sundays in [now, now + 3 weeks]", () => { + const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0)); // 2026-03-01 (a Sunday) + const target = windowTarget(now, 3); + const plan = planInstances(weeklyService, now, target); + const days = plan.map((i) => i.occursOn); + expect(days).toEqual(["2026-03-01", "2026-03-08", "2026-03-15", "2026-03-22"]); + }); + + it("endsAt is start + duration", () => { + const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0)); + const target = windowTarget(now, 1); + const [first] = planInstances(weeklyService, now, target); + expect((first.endsAt.getTime() - first.startsAt.getTime()) / 60_000).toBe(75); + }); +}); + +describe("planInstances — DST-safe instants", () => { + it("keeps 9 AM local across the spring-forward Sunday", () => { + // 2026-03-01 is EST; 2026-03-08 is the spring-forward Sunday (EDT). + const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0)); + const target = windowTarget(now, 2); + const plan = planInstances(weeklyService, now, target); + const before = plan.find((i) => i.occursOn === "2026-03-01")!; + const after = plan.find((i) => i.occursOn === "2026-03-08")!; + expect(before.startsAt.getUTCHours()).toBe(14); // 09:00 EST (UTC-5) + expect(after.startsAt.getUTCHours()).toBe(13); // 09:00 EDT (UTC-4) + }); +}); + +describe("planInstances — deterministic (drives idempotent upsert)", () => { + it("produces the same instants for identical input", () => { + const now = new Date(Date.UTC(2026, 2, 1, 12, 0, 0)); + const target = windowTarget(now, 2); + const a = planInstances(weeklyService, now, target); + const b = planInstances(weeklyService, now, target); + expect(a.map((i) => i.startsAt.getTime())).toEqual(b.map((i) => i.startsAt.getTime())); + expect(a.map((i) => i.occursOn)).toEqual(b.map((i) => i.occursOn)); + }); +}); + +describe("planInstances — biweekly phase", () => { + it("lands every other Sunday on a stable phase", () => { + const service = { ...weeklyService, rrule: "FREQ=WEEKLY;INTERVAL=2;BYDAY=SU" }; + const now = new Date(Date.UTC(2026, 0, 4, 12, 0, 0)); // 2026-01-04 (anchor Sunday) + const target = windowTarget(now, 3); + const days = planInstances(service, now, target).map((i) => i.occursOn); + expect(days).toEqual(["2026-01-04", "2026-01-18"]); + }); +}); + +describe("planInstances — monthly nth weekday", () => { + it("plans the 1st Sunday across a year boundary", () => { + const service = { ...weeklyService, rrule: "FREQ=MONTHLY;BYDAY=1SU" }; + const now = new Date(Date.UTC(2026, 11, 1, 12, 0, 0)); // 2026-12-01 + const target = windowTarget(now, 10); + const days = planInstances(service, now, target).map((i) => i.occursOn); + expect(days).toEqual(["2026-12-06", "2027-01-03", "2027-02-07"]); + }); +}); + +describe("windowTarget", () => { + it("defaults to a 16-week window", () => { + const now = new Date(Date.UTC(2026, 0, 1, 12, 0, 0)); + const target = windowTarget(now); + expect(INSTANCE_WINDOW_WEEKS).toBe(16); + // 16 weeks = 112 days from Jan 1. + expect(localDay(target)).toBe("2026-04-23"); + }); +}); diff --git a/src/domain/instances.ts b/src/domain/instances.ts new file mode 100644 index 0000000..d016a55 --- /dev/null +++ b/src/domain/instances.ts @@ -0,0 +1,70 @@ +/** + * Instance planning — unit D2 (ARCHITECTURE §5.1). + * + * Pure: no DB, no `src/db` imports. `planInstances()` turns a service's + * recurrence rule into the list of UTC instants it should occur at inside a + * rolling window. The data layer (`src/db/instances.ts`) upserts these; the + * cron route drives the upsert daily. + * + * DST is resolved per instant by `localToUtc`: a 9:00 AM Sunday stays 9:00 AM + * local across spring-forward / fall-back, so the stored UTC shifts by an hour + * at each transition. We never add 24h to walk a window. + */ + +import { expandRRULE } from "./recurrence"; +import { dateInTimezone, localToUtc } from "@/lib/tz"; + +export interface ServicePlanInput { + rrule: string; + startTimeLocal: string; + timezone: string; + durationMinutes: number; +} + +export interface PlannedInstance { + /** Local date, e.g. `2026-03-01` (church timezone). */ + occursOn: string; + /** UTC instant the service starts (DST-safe). */ + startsAt: Date; + /** UTC instant the service ends. */ + endsAt: Date; +} + +/** Default rolling window kept by the cron generator. */ +export const INSTANCE_WINDOW_WEEKS = 16; + +/** + * The far edge of the rolling window: `now` + `weeks` (default 16). Computed in + * UTC days — the window edge is approximate, so a DST hour at the boundary is + * irrelevant. + */ +export function windowTarget(now: Date, weeks = INSTANCE_WINDOW_WEEKS): Date { + const target = new Date(now); + target.setUTCDate(target.getUTCDate() + weeks * 7); + return target; +} + +/** + * Plan every instance of `service` that falls in [now, target]. Local dates + * come from `expandRRULE`; instants from `localToUtc`. Deterministic for a + * fixed (service, now, target) — re-planning yields the same list, which is + * what makes the upsert idempotent. + */ +export function planInstances( + service: ServicePlanInput, + now: Date, + target: Date, +): PlannedInstance[] { + const from = dateInTimezone(now, service.timezone); + const to = dateInTimezone(target, service.timezone); + const durationMs = service.durationMinutes * 60_000; + + return expandRRULE(service.rrule, from, to).map((occursOn) => { + const startsAt = localToUtc(occursOn, service.startTimeLocal, service.timezone); + return { + occursOn, + startsAt, + endsAt: new Date(startsAt.getTime() + durationMs), + }; + }); +}