Files
glenloch-media/.agent/PROGRESS.md
T
Tiel Coder 9f7a65b136 B3: catalog taxonomy CRUD (categories, vendors, technologies, functions)
Create/rename/deactivate for the four taxonomy tables. Deactivate not
delete; slug frozen after creation; FKs ON DELETE RESTRICT.
- src/db/schema.ts: four tables + relations (ON DELETE RESTRICT FKs)
- src/lib/slug.ts: slugify (lowercase, ASCII-fold, collapse runs) + 6 tests
- src/db/catalog.ts: listCatalog (active filter), deactivateCatalog (soft
  delete), per-entity create*/update* (slug generated at create, frozen on
  update; update patches only present fields)
- src/app/api/dev/catalog/route.ts: GET/POST/PATCH; Zod per entity; DB
  constraint errors mapped to 409 (dup slug) / 400 (dangling FK) via cause
  chain
- drizzle/0003_whole_crystal.sql
Verification: typecheck, lint, 36 unit tests (+6), build, db:migrate all
exit 0. Runtime smoke: create -> rename keeps slug -> deactivate hides from
pickers but row persists (all four types); partial PATCH preserves omitted
fields; validation 400/400/400/409.
2026-11-18 01:00:10 +00:00

232 lines
19 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# PROGRESS
Build log for Media Team Hub. One unit per commit, top to bottom. Append after each passing check.
---
## A1 — Foundation scaffold — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** Next.js 15 + TS strict, Tailwind 4, shadcn/ui (Radix), Drizzle, Zod, Vitest, lint, CI.
**Delivered:**
- Next.js 15, React 19, TypeScript strict, Tailwind 4, ESLint 9
- shadcn/ui initialized manually (Radix + CSS variables) — `components.json`, `src/lib/utils.ts`, theme in `globals.css`
- Drizzle + `postgres` driver + Zod; `src/db/index.ts` client, `src/db/schema.ts` placeholder (A2 fills it)
- Vitest (jsdom-capable) with a passing `cn()` test
- GitHub Actions CI (typecheck → lint → test → build)
- **Portable container stack** (user request): multi-stage Dockerfile (non-root, pnpm), `docker-compose.yml` (app + Postgres), `.dockerignore`
**Verification (all exit 0):**
- `pnpm typecheck` ✓
- `pnpm lint` ✓
- `pnpm test` ✓ (3 tests)
- `pnpm build` ✓
- `docker compose build app` ✓
- Container serves HTTP 200 on :3000, title "Media Team Hub" ✓
**Port audit (nothing else touched):** app → host **3000**; Postgres → host **5433** (local 5432 already taken). Confirmed free before binding.
**Decisions recorded in README.md ("Decisions recorded from your answers"):**
- Services: Sun 10:30 AM + 5:30 PM, `America/New_York` (DST-safe, changeable as data)
- One person per role
- Admin = full control; Coordinator = everything except design/theme + admin/settings
- CSV-only migration
- **Email-only at launch; SMS (Twilio + 10DLC) deferred**
**Stack change from docs:** docs target Cloudflare Workers (D1/R2/Cron Triggers — not portable). For portability we use standard Next.js Node container + Postgres + local media volume + node cron worker. Domain logic, data model, and UI are unchanged.
**Next: A2 — schema core.**
---
## A2 — Schema core — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** full data model + migration + seed.
**Delivered:**
- `src/db/schema.ts` — six core tables: `users`, `roles`, `services`, `serviceInstances`, `slots`, `assignments` (catalog tables from B3 excluded, per A2 scope).
- Spec rules enforced:
- **Rule 26** — `chk_slots_single_parent`: a slot belongs to exactly one of a service instance or an event (`CHECK ((service_instance_id IS NOT NULL) <> (event_id IS NOT NULL))`).
- **Rule 27** — `uq_active_assignment`: partial unique index, at most one non-terminal assignment per slot (`WHERE status IN ('proposed','confirmed','completed')`).
- Slug immutability (unique, no update path); deactivate-only (no hard delete); level changes via assessments; `created_at` audit on admin mutations; `America/New_York` default tz, stored UTC.
- `src/lib/uuid.ts` — UUIDv7 generator (RFC 9562).
- `src/lib/tz.ts` — DST-safe local→UTC (`localToUtc`), `nextSundaysInTz`, `formatInTimezone`, etc.
- `src/db/seed.ts` — idempotent seed (ON CONFLICT DO NOTHING + re-fetch canonical DB rows): 3 roles, 2 services, next 2 Sundays × 2 services of instances, 12 slots, 6 users, round-robin assignments.
- Migration `drizzle/0000_loose_wendell_vaughn.sql` (+ `0001` for the two added unique constraints).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (3) · `pnpm build` ✓
- Drop DB → `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (exits 0)
- `SELECT count(*) FROM service_instances` = 4 (> 0) ✓
- Re-run seed is idempotent: stable counts (4/6/3/2/12/12), exit 0 ✓
- CHECK constraint rejects both-NULL and both-NOT-NULL slots; accepts exactly-one ✓
- Partial unique index rejects duplicate confirmed assignment for a slot ✓
- DST-safe: 9:00 AM America/New_York → `2026-11-25 14:00:00+00` (EST) ✓
**Bugs fixed this phase (recorded for future reference):**
- `.references()` takes a **column** (`() => services.id`), not a table.
- `one`/`many` are `relations()` callback params, not imports.
- CHECK XOR needs parentheses: `(a IS NOT NULL) <> (b IS NOT NULL)` — bare `a IS NULL <> b IS NULL` parses as `boolean <> text`.
- `drizzle-kit 0.31.11 generate` requires an existing `meta/_journal.json`; start from `{version, dialect, entries: []}` to diff a fresh schema.
- `ON CONFLICT DO NOTHING` needs a full unique index on its target (partial indexes don't qualify as arbiters).
- Seed must re-fetch canonical DB rows after idempotent inserts (fresh UUIDs otherwise break downstream FKs).
- `dateInTimezone` destructured `{y,m,d}` but `partsInTz` returns `{year,month,day}` — fixed.
**Next: A3 — auth (auth.js + credentials provider, admin/coordinator/volunteer roles).**
---
## A3 — Auth — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** magic-link sign-in (dev console transport), session cookie, `requirePermission()` chokepoint, role enum.
**Delivered:**
- `src/auth/roles.ts` — `SystemRole` type + helpers (`isAdmin`, `isCoordinator`, `isLeader`, `assertSystemRole`).
- `src/auth/permissions.ts` — feature-scoped permission matrix from the ARCHITECTURE §2.3 capability table, `hasPermission()`, `AuthError` (carries HTTP 401/403), `requirePermission(user, perm)` chokepoint.
- `src/auth/magic-link.ts` — dev console transport: `getOrCreateUser` (auto-activates unknown emails when `AUTO_ACTIVATE_NEW_USERS` is on — dev convenience; flip to `"false"` for the B1 approval flow), `signMagicToken`/`verifyMagicToken` (jose HS256), `requestMagicLink` (prints the sign-in link to the console).
- `src/auth/config.ts` — Auth.js v5 Credentials provider (`magic-link`) + JWT session carrying `systemRole`.
- Routes: `/api/auth/[...nextauth]`, `/api/dev/magic-link` (POST `{email}`), `/api/dev/complete` (GET `?token=…`), `/api/admin` (chokepoint), and `/login` (magic-link sign-in UI).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17 tests) · `pnpm build` ✓
- **Acceptance** `pnpm test src/auth` green: 401 anonymous, 403 volunteer on `/admin`, 200 admin ✓
- Runtime smoke test (dev server + Postgres on :5433):
- `GET /api/admin` (no session) → 401 `UNAUTHORIZED` ✓
- `POST /api/dev/magic-link {email}` → 200, creates user (volunteer/active), returns + logs the sign-in link ✓
- `GET /api/dev/complete?token=…` → 200, token verified, session established ✓
- User persisted in DB as `active` ✓
- `GET /login` → 200, renders ✓
**Decisions:**
- **Auto-activate new emails in dev** (`AUTO_ACTIVATE_NEW_USERS`, default on) so a volunteer can sign in as anyone without admin setup; admin can flip to `"false"` to require approval (B1).
- **Auth.js v5** (matches the docs' "Auth.js"; portable, no SaaS lock-in). JWT sessions, no DB adapter needed. (auth.js v5 ships as `next-auth@beta`; the `@auth/next` scope isn't published yet.)
- **`/admin` requires `admin.settings`** (admin-only) — matches the spec's `/admin/*` pages being admin-only.
**Bugs fixed this phase (recorded for future reference):**
- Auth.js v5 session config uses `session.strategy: "jwt"`, not `session.jwt`.
- `req.json()` was unreliable here; `req.text()` + `JSON.parse` is the robust body read.
- An object schema must be parsed as an object: `bodySchema.safeParse({ email })`, not `safeParse(email)`.
- Turbopack dev + a production `.next/` from `pnpm build` conflict on `_buildManifest.js.tmp`; `rm -rf .next` before `next dev`.
**Next: A4 — app shell (layout, nav, tokens, error + empty states, `/api/health`).
---
## A4 — App shell — DONE 2026-11-17
**Scope (from BUILD-PLAN.md):** layout, nav (5 tabs mobile / rail desktop), tokens, error + empty states, `/api/health`.
**Delivered:**
- `src/app/(app)/layout.tsx` — app shell wrapper; `src/components/app/nav.tsx` — 5 nav tabs (mobile tab bar + desktop rail); `src/components/app/app-layout.tsx`, `src/components/app/state-message.tsx` (tokens + error/empty states).
- 5 shell pages: `schedule`, `announcements`, `roster`, `training`, `settings`.
- `src/app/api/health/route.ts` — `GET /api/health -> { ok: true }`.
- Playwright e2e `e2e/shell.spec.ts` + `playwright.config.ts` (webServer builds + starts the app; `reuseExistingServer`).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (17) · `pnpm build` ✓
- `pnpm test:e2e --grep shell` → **4/4 pass** at 360 px viewport (the A4 "Done when"):
- renders the shell with 5 nav tabs at 360 px ✓
- shows the desktop rail at desktop width ✓
- redirects unauthenticated users away from the shell ✓
- `/api/health` returns ok ✓
**A4 blocker — root cause + fix (recorded for future reference):**
- **Reported** as `/api/dev/complete` returning HTTP 000 / connection reset. That was a **curl/shell-quoting artifact** in the handoff's test script, not an app bug.
- **Real symptom:** the complete response carried **no `Set-Cookie`**, so no session was established and every `/schedule` 307-redirected to `/login`; the two shell e2e tests failed (nav tabs never rendered).
- **Root cause:** `[auth][error] UntrustedHost`. Auth.js v5's `assertConfig()` checks `config.trustHost` **before** `setEnvDefaults()` applies its env default, and that default only derives `trustHost` from `AUTH_URL`/`AUTH_TRUST_HOST`/`VERCEL`/`CF_PAGES`/`NODE_ENV !== "production"` — **not** `NEXTAUTH_URL`. In `pnpm start` (production) with no `AUTH_URL`, `trustHost` stayed `false`, so the magic-link callback was rejected and no session cookie was written.
- **Fix:** `src/auth/config.ts` sets `trustHost: true` explicitly (documented fix for `UntrustedHost`; localhost app behind a reverse proxy). Rebuild required for `pnpm start`. Verified: complete response now sets `authjs.session-token`, `/schedule` returns 200, all 4 e2e pass.
**Next: B1 — invite → pending → approve/deny, with status transitions and an outbox row (console).**
---
## B1 — Invite → pending → approve/deny — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** invite creates `pending_approval`; approve flips to `active`; denied user cannot sign in; an outbox row (console).
**Delivered:**
- `src/auth/invites.ts` — the unit. Pure transition rule `nextUserStatus(current, action)` (invite→pending_approval, approve→active, deny→denied) and `isSignInEligible(user)` (active && not deactivated, mirrors the Auth.js `authorize` guard), both exported and unit-tested. Thin DB wrappers `inviteUser`, `approveUser`, `denyUser` around the rule. `enqueueOutbox()` = launch console transport (ARCHITECTURE §3.4), a structured greppable line — swapping in Postmark later is a change here only.
- Routes: `src/app/api/dev/invite/route.ts` (POST { email, invitedBy? }), `src/app/api/dev/approve/route.ts` (POST { userId, approvedBy? }), `src/app/api/dev/deny/route.ts` (POST { userId, deniedBy? }).
- `src/auth/invites.test.ts` — 7 tests named after the rules.
- `src/auth/magic-link.ts` exports `APP_ORIGIN` (reused by invites).
**No migration needed** — `users.status` already carries the `invited / pending_approval / active / inactive / denied` enum and defaults to `pending_approval` (A2).
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**24** total, +7 for B1) · `pnpm build` ✓
- Runtime smoke test against live app + Postgres on :5433 (full lifecycle):
- invite `b1.active@example.com` → DB `pending_approval` ✓
- approve → DB `active`; complete invite-time token → `/api/auth/session` returns the user (`systemRole: volunteer`) ✓
- invite + deny `b1.denied@example.com` → DB `denied`; complete → session `null`, `/api/admin` 401 ✓
**Decisions:**
- Invite is the *admin-invites* path, distinct from `getOrCreateUser`'s self-serve auto-activate. Re-inviting an existing (e.g. previously denied) user resets them to `pending_approval`.
- The transition rule lives in one pure, auditable place (`nextUserStatus`); the DB wrappers call it, so the rule and the code cannot drift.
**Next: B2 — profile + notification prefs + SMS consent capture.**
---
## B2 — Profile + notification prefs + SMS consent capture — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** profile update, `notification_preferences` table, SMS consent capture (timestamp, source, IP).
**Delivered:**
- `src/db/schema.ts` — `notification_preferences` table (ARCHITECTURE §4.76): `user_id` PK→`users.id` (ON DELETE cascade), `email_enabled` (default true), `sms_enabled` (default false), `sms_consent_at`/`sms_consent_source`/`sms_consent_ip` (TCPA evidence), `reminder_lead_days` (default 7), `quiet_hours_start/end` ("21:00"/"08:00"), `digest_only` (default false). `SMS_CONSENT_SOURCES` enum (`web_signup` | `paper_form` | `admin_import`).
- `src/domain/consent.ts` — the pure TCPA rule. `phoneChanged(current, next)` (consent is bound to a number — drives the reset), `buildConsent(source, ip, at)` (opt-in evidence), `resetConsent()` (pre-opt-in state).
- `src/db/profile.ts` — DB wrappers: `updateProfile` (updates provided fields only; resets consent when the phone changes), `setSmsConsent` (opt-in populates consent fields), `getProfile`. `upsertPrefs` handles the one-to-one row.
- `src/app/api/dev/profile/route.ts` — PATCH `/api/dev/profile` (update) + POST `/api/dev/profile` (consent).
- `src/domain/consent.test.ts` — 6 tests named after the rules.
- `src/db/seed.ts` — per-user prefs row (email on, SMS off) for every seeded user.
- Migration `drizzle/0002_fearless_doctor_spectrum.sql`.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**30** total, +6 for B2) · `pnpm build` ✓
- `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (31 prefs rows, idempotent)
- Runtime smoke test against live app + Postgres on :5433:
- opt-in `web_signup` from `192.168.1.100` → `sms_enabled=true`, `sms_consent_at/source/ip` populated ✓
- change phone → consent reset (`sms_enabled=false`, evidence cleared) ✓
- change a non-phone field → consent UNCHANGED ✓
- invalid consent source → 400 ✓
**Decisions:**
- **Partial update, not replace.** The PATCH handler builds the patch from only the fields present in the body. A naive `{ phoneE164: body.phoneE164 ?? null }` would null the phone on every PATCH that omits it (and, since `null !== undefined`, `updateProfile` would treat that as a phone change and reset consent). This is the subtle trap this unit guards against.
- **No `one()` relation for the PK-FK column.** Drizzle 0.45.4's `one()` helper types `fields`/`references` as a tuple of non-PK columns; a column that is *both* PK and FK (`notification_preferences.user_id`) fails the typecheck. The table, FK, and all B2 code work without the relation (profile.ts queries both tables directly). Add the eager-load relation later once a working pattern exists.
- **Seed re-fetches canonical ids.** Same idempotency lesson as A2: `userRows` get fresh UUIDs each run, so prefs are seeded from the re-fetched `userRows2` ids (the assignments code already did this).
**Next: B3 — catalog taxonomy.**
---
## B3 — Catalog taxonomy CRUD — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** create/rename/deactivate for the four taxonomy tables — `skill_categories`, `vendors`, `technologies`, `functions`. Deactivate (not delete); slug frozen after creation; read-heavy, so data layer + minimal form only (no `/admin/catalog` UI — that arrives in I2). Governing rules from ARCHITECTURE §4.3: nothing referenced is ever deleted, slugs immutable, FKs `ON DELETE RESTRICT`.
**Delivered:**
- `src/db/schema.ts` — four tables (`skill_categories`, `vendors`, `technologies`, `functions`), each `id, slug (unique), name` + entity-specific columns, `sort_order`, `active` (default true), `created_at`, `updated_at`. All taxonomy FKs use `ON DELETE RESTRICT`; slugs frozen (no update path accepts `slug`). Added relations (`skillCategoriesRelations` → technologies+functions; `vendorsRelations` → technologies; `technologiesRelations` → vendor+category; `functionsRelations` → category).
- `src/lib/slug.ts` — `slugify(name)`: lowercase, ASCII-fold Latin-1 accented chars, collapse non-alnum runs to a single hyphen, trim edges. Pure rule.
- `src/lib/slug.test.ts` — 6 tests named after slugify behaviors.
- `src/db/catalog.ts` — `listCatalog(type, { active })` (active:true → only active rows for pickers; active:false → all rows incl. deactivated), `deactivateCatalog(type, id)` (soft delete, flips `active`), per-entity `create*`/`update*` (slug generated at create, frozen on update; `update*` patches only fields present in the body — no null-out).
- `src/app/api/dev/catalog/route.ts` — GET (list, `?type=&active=`), POST (create, slug server-generated), PATCH (rename/edit, or deactivate via `active:false`). Zod-validated per entity. DB constraint violations mapped to 409 (duplicate slug) / 400 (dangling FK) via a cause-chain walk (pg wraps the SQLSTATE on `err.cause.code`).
- Migration `drizzle/0003_whole_crystal.sql`.
**Verification (all exit 0):**
- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (**36** total, +6 for slugify) · `pnpm build` ✓
- `pnpm db:migrate` ✓ → all 4 tables present on :5433
- Runtime smoke against live app + Postgres on :5433 (create → rename keeps slug → deactivate hides from pickers but row persists), all four entities:
- create → generated slug (`name` → `slug`) ✓
- rename → slug UNCHANGED, name updated ✓ (all four types)
- deactivate → active picker count drops by exactly 1, all-row count unchanged (row persists) ✓
- `GET ?active=true` excludes deactivated; `GET ?active=false` includes all ✓
- partial PATCH omits a field → that field is NOT nulled out ✓
- validation: missing name → 400, bad type → 400, missing FK → 400, duplicate slug → 409 (not an empty 500) ✓
**Decisions:**
- **Inline per-entity switches in the route, not a map dispatch.** A map-based handler lost TS type correlation (TS2345 on the intersected param types). Explicit `case` blocks keep each `CatalogType` correlated to its create/update handler and its Zod schema.
- **DB constraint errors → client errors.** The pg driver throws a Drizzle `QueryError` whose `.cause` carries the SQLSTATE. Walking the cause chain lets the route return 409/400 with a clear message instead of a bare 500 — admins creating a duplicate category or a technology with a dangling vendor get actionable feedback.
- **`successorTechnologyId` is plain text, not a self-FK.** A self-referential FK created a circular schema type (TS7022/TS7024). It's a soft "successor gear" hint, validated at the app layer.
- **`purchasedOn` uses `mode: "string"`.** The API passes an ISO date string; a `mode: "date"` column expects a `Date` object (TS2769).
- **No catalog seed yet.** Per ARCHITECTURE, the only seeded artifact is `seed/catalog.json` (loaded on first boot) — delivered in a later unit. The four tables start empty; this unit is the data layer other units consume.
**Next: B4 — positions (schedulable seats) + skills.****