unit(D2): idempotent instance generator (16-week window) on cron route

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.
This commit is contained in:
Tiel Coder
2026-11-18 05:17:11 +00:00
parent 6a778aa2f6
commit 8fb6459b0d
5 changed files with 306 additions and 0 deletions
+27
View File
@@ -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.