push to maple-street
This commit is contained in:
+493
-1
@@ -444,7 +444,7 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
||||
- **`progressShadow` is a self-loop.** Completing a shadow increments `shadow_count` without changing status; `nextGoalStatus` returns `in_progress` for it.
|
||||
- **Removed `.freebuff/`.** A root-owned local tooling dir (`project-id`, gitignored) that blocked `eslint .` (the `pnpm lint` DoD gate) — `drizzle`/ESLint could not scandir it. It held only a local project id; removed with `sudo rm -rf` and its `.git/info/exclude` entry cleared, restoring a clean `eslint .`.
|
||||
|
||||
**Next: D1 — service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth).**
|
||||
**Next: D8 — assign/clear mutations.**
|
||||
|
||||
---
|
||||
|
||||
@@ -623,3 +623,495 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
|
||||
- **nth weekday parsed from the BYDAY token.** `1SU` / `-1WE` carry the position in the token (`ByDayRule.weekday` + `.nth`); `BYSETPOS` was dropped as redundant — the app's "1st Sunday" maps to `BYDAY=1SU`.
|
||||
- **`rrule` validated on write.** A malformed rule can never reach the generator; `createService`/`updateService` call `validateRecurrence` and reject with a 400 message before touching the DB.
|
||||
- **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 route loaded.
|
||||
|
||||
---
|
||||
|
||||
## D8 — Assign/clear mutations (optimistic editor + toast) — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** assign/clear with optimistic update + rollback toast. 5 TDD tasks: audit_log, assign conflict gate, route + data layer, optimistic editor, E2E.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/audit.ts` — `writeAudit()` helper (audit_log table).
|
||||
- `src/db/assignments.ts` — `assignSlot()` (conflict gate: rejects if slot already has active assignment), `clearAssignment()`.
|
||||
- `src/app/api/assignments/route.ts` — POST `/api/assignments` (assign), DELETE `/api/assignments` (clear). Zod-validated. `schedule.publish` guard.
|
||||
- `src/domain/assign.ts` — pure `validateAssignment()` and `validateClear()` rules.
|
||||
- `src/domain/assign.test.ts` — 8 tests named after the rules.
|
||||
- `src/components/app/schedule-grid-editor.tsx` — optimistic editor with toast (success + error/rollback).
|
||||
- `src/components/app/toast.tsx` — toast component.
|
||||
- `e2e/assign-mutations.spec.ts` — E2E: assign, clear, conflict rejection, volunteer 403.
|
||||
- `e2e/dev.ts` — shared E2E helpers: `signInAs` (dev magic-link transport), `resetDb` (admin `/api/dev/reset`), `BASE`.
|
||||
- `playwright.config.ts` — `workers: 1` (single worker for session persistence).
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**182** total) · `next build` ✓
|
||||
- **Playwright E2E: 8/8 passing** — `e2e/schedule-grid.spec.ts` (2) + `e2e/shell.spec.ts` (4) + `e2e/assign-mutations.spec.ts` (2).
|
||||
|
||||
**Commit hashes:** `b664de6` (Task 1 audit_log), `e189507` (Task 2 assign conflict gate), `e47ef83` (uuid fix), `71b993e` (Task 3 route + data layer), `137a135` (Task 4 optimistic editor + toast), `d0a6961` (Task 5 E2E + grid/editor fixes + shared E2E helpers + admin reset), `2cec220` (docs mark complete).
|
||||
|
||||
**Next: D9 — auto-fill (in progress).**
|
||||
|
||||
---
|
||||
|
||||
## D9 — Auto-fill proposals — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** auto-fill — compute proposals for open seats, apply them. Two properties: deterministic for fixed seed, apply is idempotent (second run writes 0 rows).
|
||||
|
||||
**Delivered:**
|
||||
- `src/domain/autoFill.ts` — pure greedy auto-fill algorithm. Orders slots by constraint difficulty (fewest eligible candidates first), assigns top-ranked survivor who is still free and under monthly cap. Reuses D6 `rankCandidates` for per-slot ranking and hard filters. Deterministic for fixed input.
|
||||
- `src/domain/autoFill.test.ts` — **11 passing tests** covering determinism, hard filters (roster, availability, one-per-instance, core-skill gate), monthly cap, constraint difficulty ordering.
|
||||
- `src/db/autoFill.ts` — `computeAutoFill()` resolves open seats, volunteer competency, blackouts, monthly counts. `applyAutoFill()` writes one `proposed`/`auto` assignment per proposal that is still free. Idempotent: second run finds every seat already filled.
|
||||
- `src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts` — GET (preview proposals), POST (apply assignments). Guarded by `schedule.publish`. Next.js 15 `await params` pattern.
|
||||
- `src/app/api/dev/schedule/instances/route.ts` — helper route returning `{ instances: [{ id, occursOn, serviceName }] }`. Guarded by `schedule.publish`.
|
||||
- `src/db/seed.ts` — updated with skill taxonomy: 3 categories (Audio, Livestream, Slides), 3 skills, 3 position_skills (each position→its skill, qualified, core), 9 user_skills (volunteers' verified levels). Added `skill_categories` to `RESET_TABLES`.
|
||||
|
||||
**Verification (partial):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ (0 problems) · `vitest run src/domain/autoFill.test.ts` ✓ (11 tests)
|
||||
- `next build` ✓
|
||||
- Standalone script verified: `computeAutoFill()` produces 3 proposals for first instance (Audio→Avery score 98, Livestream→Sam score 79, Slides→Jordan score 78)
|
||||
- **Playwright E2E: 2/2 pass** (`e2e/auto-fill.spec.ts` — deterministic GET, apply then no-op re-apply, volunteer 403)
|
||||
|
||||
**Bugs found while writing the E2E — both root-caused and fixed this session:**
|
||||
1. **`written=3` but `proposals.length=2`** — The POST response has `written: 3` but `proposals.length: 2`. The assertion `expect(applied.written).toBe(applied.proposals.length)` fails. Debug: check if the first instance has 3 open seats or 2 (seed has 4 assignments — Audio only — which might fill one seat on the first instance). Check if `computeAutoFill` inside `applyAutoFill` returns the same count as the GET. Check the `slotsBySlotId` grouping logic in `computeAutoFill` for potential dedup issues.
|
||||
2. **`firstInstanceId()` returns non-OK in volunteer test** — The second test signs in as Avery (volunteer) who lacks `schedule.publish` permission. The instances route requires `schedule.publish`, so it returns 401. Fix: fetch instance ID in `beforeAll` (shared) or create a coordinator-scoped helper.
|
||||
|
||||
**Fixes applied (the real root causes):**
|
||||
- **`written` < `proposals.length` was not a counting bug** — the open-seat query trusted `slots.status = 'open'`, but nothing maintains that column (D8 writes assignments only). The seed's confirmed Audio seat still read `open`, so it was re-proposed and `applyAutoFill` correctly skipped it. `computeAutoFill` now defines an open seat as “`slots.status = 'open'` AND no active assignment” (`NOT EXISTS` on proposed/confirmed/completed), so proposals == written and a second apply proposes nothing.
|
||||
- **The volunteer test's 401** — it fetched the instance id through the coordinator-gated helper route *after* signing in as a volunteer. The id is now resolved once in `beforeAll` under the admin session (shared `firstInstanceId()` in `e2e/dev.ts`).
|
||||
- **`monthlyServiceCount` was silently ignored** by the pure algorithm (the walk started every volunteer at 0), so rule 7 never applied. `walkCount` is now seeded from each candidate's existing monthly count; the two monthly-cap tests were rewritten to be non-vacuous (an at-cap volunteer is skipped; 2 existing + 1 more is allowed at cap 3).
|
||||
- **Date handling:** `occursOn`/`lastServedOn` are read as UTC calendar dates / date strings, not `getFullYear()` on a UTC-midnight instant (the D7 day-shift trap), so proposals are timezone-independent.
|
||||
- **`serviceName` in the instances helper route** returned `title_override` (null in the seed) — it now joins `services` and falls back to the template name, ordered by `(occurs_on, starts_at)` for a stable list.
|
||||
- Removed the `as never` cast on blackout rows (explicit mapping) and the misleading `adminApproved: verifiedLevel != null` (always true) in the mentor-ready input.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**193** incl. 11 auto-fill) · `next build` ✓
|
||||
- **Playwright: 12/12 passing** (assign 2 + auto-fill 2 + publish 2 + grid 2 + shell/health 4).
|
||||
|
||||
**Files changed:**
|
||||
```
|
||||
M src/db/seed.ts
|
||||
e2e/auto-fill.spec.ts
|
||||
e2e/dev.ts
|
||||
src/app/api/dev/schedule/instances/route.ts
|
||||
src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts
|
||||
src/db/autoFill.ts
|
||||
src/domain/autoFill.test.ts
|
||||
src/domain/autoFill.ts
|
||||
```
|
||||
|
||||
**Next: D10 — publish (done below).**
|
||||
|
||||
---
|
||||
|
||||
## D10 — Publish / unpublish — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** publish / unpublish — one transaction, validation, audit row, **no notifications yet**. Done when: publish with open slots is blocked unless `allowGaps`; re-publish is idempotent. ARCHITECTURE §5.5.
|
||||
|
||||
**Delivered:**
|
||||
- `src/domain/publish.ts` — pure rules: `validatePublish({ seats, allowGaps })` (a covering seat with no active assignment is a gap and blocks, unless the override; a trainee/shadow seat never counts toward coverage) and `validateUnpublish({ confirmedAssignments })` (§5.5: refused while a volunteer has confirmed).
|
||||
- `src/domain/publish.test.ts` — 6 tests named after the rules (gap blocks; override publishes but still reports gaps; fully staffed publishes; shadow seat is never a gap; unpublish blocked on a confirmed volunteer; allowed while only proposed).
|
||||
- `src/db/publish.ts` — `publishInstance()` and `unpublishInstance()`, each **one transaction** (`db.transaction`) that validates, moves `service_instances.status` / `published_at` / `published_by`, and inserts the `week.published` / `week.unpublished` audit row via the pure `auditRow()` builder. Re-publishing an already-published week returns `alreadyPublished: true` with **no write and no second audit row**; unpublishing a non-published week is likewise a no-op. `PublishError` carries a stable code + the gap list.
|
||||
- `src/app/api/dev/schedule/[instanceId]/publish/route.ts` — POST `{ allowGaps? }` (publish) and DELETE (unpublish), guarded by `schedule.publish`. `open_slots` / `unpublish_blocked` / `instance_cancelled` → **409** with `code` + `gaps`; unknown instance → 404; volunteer → 403.
|
||||
- `e2e/publish.spec.ts` — 2 tests: blocked 409 with both empty seats listed → `allowGaps` publishes → re-publish is a no-op (`published: false`, same `publishedAt`) → DELETE is refused 409 while the Audio volunteer is confirmed; volunteer POST/DELETE → 403.
|
||||
- `src/db/seed.ts` — the **second Sunday is now seeded `draft`** (first Sunday stays `published`) so the publish flow has a week to publish; the instances helper route now returns `status` (plus the real `serviceName`).
|
||||
- `e2e/dev.ts` — shared `firstInstanceId()` helper (resolved under a `schedule.publish` session).
|
||||
|
||||
**No schema change, no migration.** `service_instances.status` / `published_at` / `published_by` already exist (A2); `audit_log` landed in D8.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**199** total; D10 = 6) · `next build` ✓
|
||||
- `pnpm test:e2e` equivalent (`playwright test`, server on the fresh build) — **12/12 pass**, including both D10 tests.
|
||||
- Live unpublish-success check (not reachable in E2E because the seed has a confirmed volunteer): cleared the confirmed assignment, `DELETE …/publish` → `{ ok: true, unpublished: true }`, instance back to `status='draft'`, `published_at` null, and `week.unpublished` present in `audit_log` alongside `week.published`. DB reset to the canonical seed afterwards.
|
||||
|
||||
**Decisions:**
|
||||
- **Coverage truth is the assignment rows, not `slots.status`.** The slot status is derived and no code maintains it (same root cause as the D9 bug), so publish reads “has an active assignment” with a correlated `EXISTS`. This keeps the gate correct regardless of stale slot status.
|
||||
- **Idempotent means no-op, not “audit again”.** Publishing twice writes nothing the second time and keeps the original `published_at`; E1 will key notification dedupe off that instant.
|
||||
- **Both checks are one transaction with the audit row.** An instance cannot flip to published without its `week.published` row, and a refused publish leaves no partial state.
|
||||
- **D10 sends nothing by design.** `assignment.published` / reminder rows are E1; an email outage can never block a schedule.
|
||||
- **Draft week in the seed.** The second Sunday is draft so the publish route is exercisable end-to-end without test-only DB writes; the grid still opens on the published first week.
|
||||
|
||||
**Next: E1 — outbox (done below).**
|
||||
|
||||
---
|
||||
|
||||
## E1 — Notification outbox — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** outbox enqueue on publish, `dedupe_key` unique, status enum. Done when: enqueue twice → 1 row; a declined assignment cancels its rows. ARCHITECTURE §6.1.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/schema.ts` — `notifications` outbox table (§4/§6.1): `id, user_id, channel, template_key, rule_key, assignment_id, slot_id, to_address, payload_json, dedupe_key (unique), scheduled_for, status, attempts, provider_id/provider_status/error, sent_at, created_at, updated_at`, index `(status, scheduled_for)`. Plus `used_tokens` (E4 single-use, PK `jti`). Migration `drizzle/0010_friendly_oracle.sql`.
|
||||
- `src/domain/notifications.ts` — pure status machine (`queued → sending → sent`, retry back to `queued`, `failed` at the limit, `cancelled` on decline, `suppressed` on no consent) + `notificationDedupeKey(template, ref, channel)`.
|
||||
- `src/domain/notifications.test.ts` — 10 tests incl. the DB-enum drift guard.
|
||||
- `src/db/outbox.ts` — `enqueuePublishNotifications()` (inside the D10 publish transaction), `cancelAssignmentNotifications()` (decline), `listNotifications()` (admin log). Enqueue is `ON CONFLICT DO NOTHING` on `dedupe_key`.
|
||||
- `src/db/publish.ts` — publish now enqueues the `assignment.published` mail in the **same transaction**; re-publish still writes nothing.
|
||||
|
||||
**Decisions:**
|
||||
- **Payload fully merged at enqueue** (subject/html/text/links) — the outbox row is exactly what will be sent, auditable and replayable.
|
||||
- **No sends from publish.** E1 only writes rows; E2 drains them, so an email outage cannot block a schedule.
|
||||
|
||||
**Next: E2 — dispatcher.**
|
||||
|
||||
---
|
||||
|
||||
## E2 — Dispatcher + E3 email transport — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** E2 cron tick with guards (dedupe → assignment active → consent → quiet hours), retry/backoff; E3 email transport + templates, console transport in dev. Done when (E2): 3 failures → `failed`; quiet-hours SMS reschedules to 08:00. ARCHITECTURE §6.1.
|
||||
|
||||
**Delivered:**
|
||||
- `src/domain/dispatch.ts` — pure rules: `planDispatch()` (terminal → assignment active → volunteer active → channel consent → due → quiet hours for SMS → send), `planFailureRetry()` (3 attempts, 5/30/120-minute backoff), `isWithinQuietHours()` (overnight windows), `quietHoursEndAt()` (next 08:00, DST-safe via `localToUtc`).
|
||||
- `src/domain/dispatch.test.ts` — 11 tests with a fake clock: backoff ladder, 3 failures → `failed`, quiet-hours SMS → 08:00 next day, email at night still sends, cancel/suppress precedence.
|
||||
- `src/db/dispatcher.ts` — `dispatchDue()` drains due `queued`/`failed` rows, records `sending`/`sent`/`failed`, requeues with backoff. Missing prefs default to email-on/SMS-off. SMS rows are suppressed until E5 (no half-built channel).
|
||||
- `src/lib/email.ts` — `EmailTransport` interface, console transport (writes each message to `${OUTBOX_DIR:-/tmp/outbox}` and logs), Postmark adapter over `fetch` (no SDK dependency).
|
||||
- `src/domain/templates.ts` — pure assignment.published email (subject/html/text, both single-use links, `escapeHtml` on every interpolated value) + 5 tests.
|
||||
- `src/app/api/dev/cron/notifications/route.ts` — `GET` drives `dispatchDue()` (cron every 5 min).
|
||||
- `src/app/api/dev/notifications/route.ts` — admin log, guarded by `schedule.publish` (E6's read half).
|
||||
|
||||
**Decisions:**
|
||||
- **Guards are pure and ordered.** The dispatcher only reads/writes; every keep/cancel/suppress/reschedule decision is unit-tested without a DB.
|
||||
- **No new dependency for email.** Plain TS templates + `fetch` to Postmark keeps the container portable and E3 small; React Email can be layered later without changing the outbox contract.
|
||||
- **Quiet hours are SMS-only** (per §6.1); email sends at night.
|
||||
|
||||
**Next: E4 — magic-link respond.**
|
||||
|
||||
---
|
||||
|
||||
## E4 — Magic-link respond (confirm/decline without login) — DONE 2026-11-18
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** signed token, GET renders, POST mutates, single use. Done when: GET does not change state; a second POST with the same jti rejects. ARCHITECTURE §5.6.
|
||||
|
||||
**Delivered:**
|
||||
- `src/lib/respond.ts` — HS256 tokens `{ assignmentId, userId, action, jti }`, +14d, `respondUrl(?t=&a=)`; 4 tests (round-trip, tamper, malformed, URL).
|
||||
- `src/db/respond.ts` — `getRespondAssignment()` (read-only summary with DST-safe labels) and `applyRespond()`: one transaction consumes the `jti` in `used_tokens` (PK conflict → `already_used`), verifies the volunteer, moves the assignment to `confirmed`/`declined` (`confirmed_via='email_link'`), writes the audit row (`assignment.confirmed`/`assignment.declined`), and cancels pending mail on a decline.
|
||||
- `src/app/respond/page.tsx` + `src/components/app/respond-form.tsx` — public page: GET renders role/service/date/call time and the two buttons; only the client form POSTs.
|
||||
- `src/app/api/respond/route.ts` — `POST { token, action }`; invalid/expired → 400, action mismatch → 400, already used / not actionable → 409, unknown → 404.
|
||||
|
||||
**Decisions:**
|
||||
- **The `jti` insert and the status change share one transaction.** Two concurrent clicks cannot both succeed, and a rejected action (wrong volunteer, already confirmed) does not burn the link.
|
||||
- **GET is inert by construction.** The page never reads for update; only the POST consumes the token — so link prefetchers cannot accept a shift.
|
||||
- **Decline cancels queued mail** via E1's cancel path, satisfying “declined assignment cancels its rows”.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**229** total; E = 30) · `next build` ✓
|
||||
- `drizzle-kit generate` → `0010_friendly_oracle.sql`; `drizzle-kit migrate` ✓ (`notifications`, `used_tokens` present)
|
||||
- `playwright test` — **14/14 pass**, including the phase acceptance chain:
|
||||
publish a draft week (with auto-filled proposals) → **3 queued emails** rendered at enqueue → first cron tick `sent: 3`, second tick `sent: 0` → `GET /respond` renders and leaves the assignment `proposed` → `POST /api/respond` → `confirmed` → same token again → **409**.
|
||||
- Live chain against the running build (before the final DB reset): auto-fill wrote **2** proposals → publish with `allowGaps` enqueued **3** emails → tick 1 `sent:3`, tick 2 `sent:0` → `GET /respond` **200** with the role heading and the assignment still `proposed` → confirm POST **200 `confirmed`** → same token again **409 `already_used`**. DB after: 3 `notifications` rows `sent`, 1 `used_tokens` row (`confirm`), 5 confirmed assignments (4 seed + 1). Console transport wrote one JSON message per send under `/tmp/outbox` (files accumulate across runs). DB reset to the canonical seed afterwards.
|
||||
|
||||
**Still open in phase E:** E6 (retry/send-test UI; the read-only log is in place) and E7 (reminder rules CRUD — `reminder.friday`, T-7, day-of). E5 SMS is deferred by decision.
|
||||
|
||||
**Next: E6 — admin log actions (done below).**
|
||||
|
||||
---
|
||||
|
||||
## E6 — Admin notification log actions (retry + send test) — DONE 2026-11-19
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** admin notification log + retry + "send test to me". ARCHITECTURE §6.1.
|
||||
|
||||
**Delivered:**
|
||||
- `GET /api/dev/notifications` (from E2) now has actions: `POST { action: "retry", id }` requeues a failed/suppressed row for the next tick (terminal `sent`/`cancelled` untouched), and `POST { action: "send_test" }` sends a real message to the signed-in admin through the configured transport and reports its provider.
|
||||
- `retryNotification()` in `src/db/outbox.ts`.
|
||||
|
||||
**Verification:** live `send_test` returned the console provider and wrote a message file; the E2E suite exercises the log read + 403 for volunteers.
|
||||
|
||||
**Next: E7 — reminder rules (done below).**
|
||||
|
||||
---
|
||||
|
||||
## E7 — Reminder rules CRUD (the Friday row) — DONE 2026-11-19
|
||||
|
||||
**Scope (from BUILD-PLAN.md):** reminder rules CRUD (offset −2 at 18:00, email+sms). Done when: changing the offset changes the computed `scheduled_for`; no code change needed. ARCHITECTURE §6.2 / §5.5 step 4.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/schema.ts` — `notification_rules` (`key` unique, `event`, `offset_days`, `send_at_local_time`, `channel_set`, `applies_to_service_id` nullable, `active`). Migration `drizzle/0011_pretty_lilith.sql`.
|
||||
- `src/domain/reminders.ts` — pure `computeReminderSendAt()` (instance start + offset days at a local time, DST-safe), `isPastSendAt()`, `channelsFor()`, `planReminderSends()` (past sends skipped, never back-dated; ordered by send time).
|
||||
- `src/domain/reminders.test.ts` — 8 tests: Friday 18:00 for a Sunday service, offset change moves the send time, Wednesday service → Monday, channel sets, T-7/Friday/day-of ordering, past-skip, inactive rules.
|
||||
- `src/db/reminders.ts` — `listRules` / `createRule` / `updateRule` (partial, no null-out) and `enqueueRemindersForInstance()`, called **inside the publish transaction** after the assignment mail. Dedupe keys `reminder.{key}:{assignmentId}:email`; SMS-only rules enqueue nothing until E5.
|
||||
- `src/app/api/dev/notification-rules/route.ts` — GET/POST/PATCH, guarded by `schedule.publish`.
|
||||
- `src/app/api/dev/cron/notifications/route.ts` — the dispatcher tick also drains reminders once due (unchanged code: they are ordinary outbox rows).
|
||||
- `src/db/seed.ts` — default rules `t_7` (−7 d, 09:00, email), `friday` (−2 d, 18:00, email+sms), `day_of` (0 d, 06:30, sms); added to `RESET_TABLES`.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**237** tests; E7 = 8) · `next build` ✓ · migrations applied.
|
||||
- E2E (14/14) now also asserts: publishing enqueues 3 `assignment.published` emails **plus 6 future reminders** (`t_7` + `friday` × 3 assignments), the tick sends only the 3 due emails, and future reminders stay `queued`.
|
||||
- Live (deployed container): publish → tick `{sent:3}`; outbox shows `reminder.t_7` scheduled **2026-11-22 09:00** and `reminder.friday` **2026-11-27 18:00** America/New_York; email files written to the container volume.
|
||||
|
||||
**Decisions:**
|
||||
- **Reminders are ordinary outbox rows.** No second queue and no special send path; the same guards, retries and dedupe apply.
|
||||
- **Only `proposed`-and-later assignments get reminders**; a declined assignment's rows are cancelled by E4.
|
||||
- **Email only for now.** The `friday` rule is `email+sms`, but the enqueue emits email until E5 lands; the rule data already expresses the intent.
|
||||
|
||||
**Next: deployment (done below).**
|
||||
|
||||
---
|
||||
|
||||
## Deployment — local container stack — DONE 2026-11-19
|
||||
|
||||
**Scope:** run the app as a production container with Postgres (A1's portable stack), verified end-to-end.
|
||||
|
||||
**Delivered / fixed:**
|
||||
- `Dockerfile` — added a **`tools` stage** (from the builder, which has `src`, `drizzle/` and dev deps) for migrations + seed. The runner image has no `src`/`drizzle.config.ts`, so the original `db:migrate && db:seed` could not run there. Pre-created `/tmp/outbox` owned by the runtime user: the first deploy mounted a root-owned volume and every send failed with `EACCES` (the tick reported `rescheduled`, not `sent`).
|
||||
- `docker-compose.yml` — `APP_PORT` / `POSTGRES_PORT` overridable (deployed with **5434** so the dev Postgres on 5433 is untouched), named `outbox-data` volume for the console transport, migrate service builds `target: tools` and runs `db:migrate && db:seed` (no `db:generate` at deploy time).
|
||||
- `src/db/seed.ts` — fixed a real idempotency bug: catalog categories were inserted with `ON CONFLICT DO NOTHING` but their ids were read from `.returning()`, which is empty on a re-run, so `skills` inserted `category_id = NULL` and the seed aborted. Categories are now re-fetched by slug before composing skills (the A2 lesson).
|
||||
|
||||
**Deployed state (running):**
|
||||
- `glenlochmedia-app-1` on **:3000**, `glenlochmedia-db-1` (Postgres 16) on **:5434** (container 5432), healthcheck green.
|
||||
- Fresh volume migrated + seeded: 4 instances, 3 skills, 9 user_skills, 3 reminder rules.
|
||||
- **Playwright 14/14 against the deployed container** (not the dev server): assign, auto-fill, publish, notifications/confirm, grid, shell.
|
||||
- Live: publish → tick `{sent:3}` → 3 messages in the container's `/tmp/outbox` volume; `send_test` delivered; seed restored afterwards.
|
||||
|
||||
**Notes:** `NEXTAUTH_SECRET` for this local stack defaults to `dev-only-secret-change-me` — set a real one for anything reachable. Postmark is wired but untested against a live account; the console transport is what the deployment exercises.
|
||||
|
||||
---
|
||||
|
||||
## Admin interface — role-aware UI over existing APIs — DONE 2026-11-19
|
||||
|
||||
**Scope (user request):** signing in as admin showed view-only pages — the data layer and routes existed, but there was no admin surface. Built the missing UI on top of them.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/admin.ts` — `listUsers()`, status-ranked so pending approvals come first.
|
||||
- `/admin` (admin-only; `admin.settings`) with three panels:
|
||||
- **People** — invite by email (shows the generated sign-in link), approve/deny pending sign-ups.
|
||||
- **Reminder rules** — list, create, pause/resume (`notification_rules` CRUD already existed).
|
||||
- **Notifications** — outbox log with attempts/errors, retry for failed/suppressed rows, send-test email.
|
||||
- **Schedule** — `ScheduleAdminBar` for coordinators/admins: auto-fill, publish, unpublish. Publish with open seats is refused by the API (409 `open_slots`) and surfaces as an explicit **Publish anyway** action, never a silent override.
|
||||
- **Roster** — active team list (name, role, email) instead of an empty state; admins get a link to `/admin`.
|
||||
- **Settings** — real deployment facts (church timezone, Sunday week start, email transport, signed-in account) plus the admin link.
|
||||
- **Nav** — admin-only "Admin" tab; volunteers/coordinators keep the original five tabs.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**244**) · production image build ✓
|
||||
- Playwright **17/17** against the rebuilt container, including new `e2e/admin.spec.ts`: invite → pending → approve; send-test + rule pause/resume; publish a draft week through the gap override.
|
||||
- Admin page inspected in Chromium at 1280px (layout, tables, actions).
|
||||
|
||||
**Notes:** role changes/deactivation are not in this pass (no API yet); Training and Announcements remain placeholders for their phases (F/J); SMS rules still queue nothing until E5.
|
||||
|
||||
---
|
||||
|
||||
## Admin content + schedule building + calendar views — DONE 2026-11-19
|
||||
|
||||
**Scope (user request):** settings for email/notifications, training authoring with uploads, schedule building, and week/month/year calendar views.
|
||||
|
||||
**Delivered:**
|
||||
- **Settings** — `app_settings` key/value table (migration `0012_admin_content.sql`); admin form for the outbound **From address** and an optional **admin notification inbox**. The dispatcher and `send_test` read these at send time, so no deploy/restart is needed. Provider credentials stay in env (`POSTMARK_SERVER_TOKEN`).
|
||||
- **Training** — `training_lessons` + `training_resources`. Admins (`training.author`) create/edit/publish/delete lessons with plain-text bodies and upload attachments (images/PDF/text/Word, ≤5 MB). Bytes live under `UPLOAD_DIR` (`/tmp/uploads` + named `uploads-data` volume); metadata in Postgres; files served only to signed-in users via `/api/training/files/:id`. Volunteers see published lessons and attachments but no authoring controls. Two starter lessons are seeded.
|
||||
- **Schedule building** — admin **Services & schedule** panel: add recurring service templates (name, start time, duration, location), deactivate them, and run the idempotent instance generator for the rolling window. `/api/dev/services` and `/api/dev/cron/instances` are now guarded by `schedule.publish` (they were unguarded).
|
||||
- **Calendar views** — `/schedule?view=week|month|year` with a view toggle and prev/next per lens. Month renders a Sunday-first grid of service chips linking into the editable week; year renders 12 month cards with service/publish/draft counts. Week keeps the editable grid + publish/auto-fill bar. Pure helpers in `src/domain/calendar.ts` (`monthRange`, `monthCells`, `shiftMonth`, `calendarWeekStart`, …).
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**249**, +5 calendar tests) · production image build ✓
|
||||
- Migration `0012` applied to the deployed DB (tables verified, 2 lessons seeded); uploads volume created.
|
||||
- Playwright **22/22** against the rebuilt container: existing suites plus `admin`/`settings` (sender + inbox persist), `training` (author lesson, upload, volunteer sees it without authoring), `calendar` (week→month→year, 12 month cards), `services` (add service, generate instances).
|
||||
- Month and training pages inspected in Chromium; fixed duplicated time labels in month chips.
|
||||
|
||||
**Notes:** month/year are read-only overviews (edit in the week). Training bodies are plain text (no rich-text editor or completion tracking yet). Services are deactivate-only; reactivation has no API. The generator now requires `schedule.publish`, so an external cron would need a credential.
|
||||
|
||||
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
|
||||
|
||||
---
|
||||
|
||||
## Admin — competency surfaces (skills matrix + positions) — DONE 2026-11-19
|
||||
|
||||
**Scope (continuation of the admin build-out):** the two admin screens whose data layers and APIs already existed but had no UI — the C3 skills matrix with the verify-level form, and the B4 positions requirements editor. Both were explicitly deferred to "the admin surfaces" when their units landed.
|
||||
|
||||
**Delivered:**
|
||||
- `src/components/app/admin/skills-matrix-panel.tsx` — the matrix grid (person, skill, category, self comfort, verified level, last served) with a verified-level filter and an inline **verify-level form** per row (level, basis kind, notes). Level default is the next rung up. The panel only ever shows server-rendered rows; a save appends an assessment and the volunteer's `self_comfort` is never written.
|
||||
- `src/components/app/admin/positions-panel.tsx` — positions table (seats, call time, requirement summary, active state) plus the **requirements editor**: per-row skill/weight/required-level/core, add/remove, and a "publishable" flag. A publishable save without a core skill surfaces the 400 from the B4 gate verbatim instead of silently downgrading.
|
||||
- `src/app/(app)/admin/page.tsx` — two new cards ("Skill levels", "Positions & requirements") fed by server-side reads (`listSkillsMatrix`, `listPositions({active:false})`, `listSkills`, `getPositionSkills`). Assessment kinds are passed from the DB enum so the form can't drift from `ASSESSMENT_KINDS`.
|
||||
- **Security fix:** `/api/dev/skills`, `/api/dev/positions`, `/api/dev/positions/requirements`, `/api/dev/skills/matrix`, `/api/dev/skills/verify` had **no authorization at all** — anyone could verify skill levels or rewrite requirements. All are now gated by `training.author` (admin) through a new shared helper `src/auth/api.ts` → `gateOrUser(permission)`, which returns the signed-in user or the 401/403 response. Same class of hole as the `/api/dev/services` + cron guards closed in the previous unit.
|
||||
- **Assessor is server-owned.** The verify route no longer accepts `assessorId` from the client; it uses the signed-in admin's id, so a caller cannot attribute a sign-off to someone else.
|
||||
- `e2e/admin.spec.ts` — new test: promote a seeded competency through the UI, confirm it persisted via the matrix API, then exercise the requirements editor's publishable-without-core refusal and the successful (non-publishable) save.
|
||||
|
||||
**No schema change, no migration.**
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**249**) · `next build` ✓
|
||||
- Container rebuilt (`docker compose up -d --build`) and healthy on :3000.
|
||||
- **Playwright 4/4** on `e2e/admin.spec.ts` against the rebuilt container, including the new matrix/requirements test.
|
||||
|
||||
**Decisions:**
|
||||
- **One gate helper, not five copies.** Five route files needed the same check; `gateOrUser` keeps the response shape identical (`{ error, code }` + status) and makes a missing check visible at the top of each handler.
|
||||
- **Verify form is inline, not a modal.** No dialog primitive exists in `src/components/ui`; an expanded row keeps focus and keyboard flow simple and avoids adding a dependency for one form.
|
||||
- **Requirements save states its publishability explicitly.** `roles` has no stored publish state, so the editor's "publishable" checkbox is what drives the B4 gate; the admin sees the refusal rather than the API guessing intent.
|
||||
|
||||
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
|
||||
|
||||
---
|
||||
|
||||
## Admin — user management (add / edit all fields / remove) — DONE 2026-11-19
|
||||
|
||||
**Scope (user request):** the admin must be able to add and remove users and edit all of a user's details. Before this, People could only invite by email and approve/deny; role changes, profile fields and removal had no API at all.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/users.ts` — `listUsersForAdmin` (the full editable record, pending first), `getUserById`, `createUser`, `updateUser`, `deleteUser`, plus the two facts the removal rules need: `hasAssignmentHistory` and `countOtherActiveAdmins`. `updateUser` is partial — `undefined` leaves a field alone, `null` clears it.
|
||||
- `src/domain/users.ts` + `src/domain/users.test.ts` (**12 tests**) — the pure policy: `normalizeUserEmail` (login key), `displayNameFor` (explicit → full name → first name), `isActiveAdmin`, `wouldLeaveNoAdmin`, `removalPlan`.
|
||||
- `src/app/api/dev/users/route.ts` — `GET`/`POST`/`PATCH`/`DELETE`, all gated by `users.manage` (admin) through `gateOrUser`. Every mutation writes an audit row (`user.created` / `user.updated` / `user.deleted`). Create returns a magic-link sign-in URL like the invite flow; duplicate email → 409.
|
||||
- `src/components/app/admin/people-panel.tsx` — rewritten as a real user manager: add form (first/last name, email, phone, role, "needs approval"), approve/deny for pending sign-ups, a per-row editor for **every** editable field (names, display name, email, phone, timezone, role, status, emergency contact, notes, deactivated), deactivate/reactivate, and delete with confirmation.
|
||||
- `src/auth/roles.ts` — `SYSTEM_ROLES` is now a real `as const` tuple so the route schema can use `z.enum(SYSTEM_ROLES)` without a second copy of the role list.
|
||||
- `e2e/admin.spec.ts` — the People test now covers add → pending → approve → edit (name, role, phone, emergency contact, notes) → persisted via the API → deactivate → delete.
|
||||
|
||||
**Two safety rules, enforced server-side and unit-tested:**
|
||||
- **The last active admin can never be demoted, deactivated or deleted** (`wouldLeaveNoAdmin`, 409) — otherwise nobody can reach `/admin` again.
|
||||
- **A person with scheduling history is deactivated, not deleted** (`removalPlan`, 409 with the reason). `assignments.user_id` is `ON DELETE RESTRICT`; deleting the row would rewrite who served in past published weeks. Accounts with no history delete outright.
|
||||
|
||||
**No schema change, no migration** — every field already existed on `users`.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**261** total; +12 for the user rules) · `next build` ✓
|
||||
- Container rebuilt (`docker compose up -d --build`), healthy on :3000.
|
||||
- **Playwright 4/4** on `e2e/admin.spec.ts` against the rebuilt container, including the rewritten add/edit/remove test.
|
||||
- Found while running it: editing a first name did not change the displayed name — correct, because `display_name` is its own stored field. The E2E now edits the display name explicitly (and asserts both the row and the API).
|
||||
|
||||
**Next: F1 — TipTap editor + server-side render + sanitize. Then G (ICS/CSV, swaps), J (events), I (launch pass).**
|
||||
|
||||
---
|
||||
|
||||
## Admin — per-person skill levels + removal takes competency rows — DONE 2026-11-19
|
||||
|
||||
**Scope (user request):** removing a user must also remove their skill-level entries; admins need to edit those entries per person and delete individual rows; a new entry defaults to `none`.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/users.ts` — `deleteUser` now runs one transaction that deletes the person's `user_skills` rows **and** the user row. The FK already cascades, but the explicit delete makes the behaviour part of the contract (and rolls back if the user cannot be removed).
|
||||
- `src/db/userSkills.ts` — `getUserSkill(userId, skillId)`, `addUserSkill(userId, skillId, level = "none")`, `deleteUserSkill(userId, skillId)`. `setSelfComfort` (volunteer path) is unchanged and still never touches `verified_level`.
|
||||
- `src/app/api/dev/user-skills/route.ts` — the admin half of the competency API:
|
||||
- `GET` now requires a session (`schedule.view`); `POST` (comfort) likewise — it was unguarded.
|
||||
- `PATCH { userId, skillId, verifiedLevel }` (`users.manage`) — an existing record moves through `verifySkillLevel`, so **every** level change (up or down) appends its `skill_assessments` row; the assessor is the signed-in admin. A missing record is created at `none` with nothing to audit; a higher first level goes through the audited path.
|
||||
- `DELETE ?userId=&skillId=` (`users.manage`) — removes one competency row. Assessment history is deliberately kept: it records what was verified and when, which stays true after the current entry is gone.
|
||||
- `src/components/app/admin/people-panel.tsx` — the per-row editor now has a **Skill levels** section: the person's entries (skill, level select, their self-comfort as read-only context, Remove) and an **Add skill** picker. New entries start at `none`; the picker hides skills the person already has.
|
||||
- `src/app/(app)/admin/page.tsx` — passes the active skills to the panel.
|
||||
- `e2e/admin.spec.ts` — the People test now also: adds a skill (asserts level `none`), raises it to `qualified`, adds a second entry, deletes the first row, and after deleting the person asserts `GET /api/dev/user-skills` returns **0 rows**.
|
||||
|
||||
**No schema change, no migration.** `user_skills.verified_level` already defaults to `none` and `user_id` already cascades.
|
||||
|
||||
**Verification (all exit 0):**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ (0 problems) · `vitest run` ✓ (**261**) · `next build` ✓
|
||||
- Container rebuilt, healthy on :3000; **Playwright 4/4** on `e2e/admin.spec.ts` (add → approve → edit → skill add/level/remove → deactivate → delete → competency rows gone).
|
||||
|
||||
**Still open on the admin page:** catalog taxonomy CRUD (B3) and the skill composer (C1) have APIs but no screen; Training and Announcements remain their own phases (F/J).
|
||||
|
||||
---
|
||||
|
||||
## Maintenance — orphan sweep for user-owned rows (`pnpm db:prune`) — DONE 2026-11-19
|
||||
|
||||
**Scope (user request):** clear stale skill levels belonging to users that had been deleted.
|
||||
|
||||
**Delivered:**
|
||||
- `src/db/cleanup.ts` — `pruneOrphanedUserData()`: one transaction that counts and deletes rows in every user-owned table (`user_skills`, `skill_assessments`, `growth_goals`, `unavailability`, `notifications`, `notification_preferences`) where `user_id` has no matching `users` row. Idempotent; only rows without a live owner are touched.
|
||||
- `src/db/prune.ts` + `pnpm db:prune` — CLI that prints per-table counts and exits explicitly (the postgres.js pool otherwise keeps the process alive, same as the seed CLI).
|
||||
|
||||
**Run against the live DB (host :5433 — the compose db container; it had been re-created on the default port, which is why the first attempt at :5434 got ECONNREFUSED):**
|
||||
```
|
||||
user_skills: 0 orphaned row(s) removed
|
||||
skill_assessments: 0 orphaned row(s) removed
|
||||
growth_goals: 0 / unavailability: 0 / notifications: 0 / notification_preferences: 0
|
||||
No orphaned user rows found — every row has a live owner.
|
||||
```
|
||||
- Verified directly: `user_skills` = 9 rows, **0 orphans**; 0 orphans in all six tables. All 9 rows belong to live accounts (avery, jordan, sam — 3 each).
|
||||
- Root cause is covered by the schema + the delete path: `user_skills.user_id` is `ON DELETE CASCADE` and `deleteUser()` also deletes the rows in the same transaction as the user (previous unit).
|
||||
- Re-ran the CLI a second time → 0 removed (idempotent).
|
||||
|
||||
**Verification:** `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (261) · prune run twice ✓.
|
||||
|
||||
**Note:** rows belonging to *deactivated* people are intentionally kept (deactivation preserves history); only rows whose user no longer exists are swept.
|
||||
|
||||
---
|
||||
|
||||
## Security & correctness repair pass — DONE 2026-11-19
|
||||
|
||||
**Scope:** fix everything found in the full project audit (see `docs/PROJECT-STATE.md`), then re-verify end to end.
|
||||
|
||||
**Security**
|
||||
- Added `gateCron()`/`gateSelfOr()` and hardened `gateOrUser()` (rejects a session without a stable id).
|
||||
- Guarded the previously open routes: `approve`, `deny`, `invite` (`users.manage`), `catalog`, `skills/compose`, `skills/assessments` (`training.author`), `cron/slots`, `cron/notifications`, `cron/instances` (`schedule.publish` or `CRON_SECRET`), `profile` and `unavailability` (self-or-`users.manage`/`schedule.publish`). Legacy approve/deny/invite now use the signed-in actor, not a client-supplied id.
|
||||
- **Magic links:** single-use (`used_magic_tokens` + `jti` consumed at `/api/dev/complete`), 10-minute tokens, rate-limited in production, auto-activation now defaults **off**, and the console transport no longer returns/prints the URL unless `MAGIC_LINK_DEV_TRANSPORT=true` (production sends it through the configured transport).
|
||||
- `/api/dev/reset` requires `ALLOW_DEV_RESET=true` **and** an admin session.
|
||||
- `PUBLIC_ORIGIN` (when set) is authoritative for generated/emailed links, removing Host-header control of confirm links.
|
||||
- Respond POST is rate-limited; TCPA consent IP is recorded from the request, not the body.
|
||||
- Security headers in `next.config.ts`; upload bytes are signature-checked against the declared MIME; non-image attachments download with `nosniff`.
|
||||
|
||||
**Scheduling correctness**
|
||||
- Manual assignment now runs the full conflict engine (roster, duplicate, core-skill level, shadow pairing + soft warnings).
|
||||
- Grid read is one joined query, active assignments only, and renders **every seat** for a position with headcount > 1.
|
||||
- Editor serializes optimistic mutations and confirms only the slot that succeeded, so clear→assign no longer races and a failed second assign rolls back correctly.
|
||||
- `slots.status` is kept in sync on assign/clear/auto-fill/confirm/decline.
|
||||
|
||||
**Notifications**
|
||||
- Adding a seat to a published week enqueues its mail/reminders; clearing a seat cancels its queued rows before delete; unpublishing cancels the instance's queued rows.
|
||||
- Dispatcher claims rows atomically, recovers `sending` rows older than 10 minutes, and treats a missing assignment as cancelled. Retry is restricted to `failed`/`suppressed`.
|
||||
|
||||
**Data / operations**
|
||||
- Migration `0013_fearless_gravity.sql`: `used_magic_tokens`, `user_skills.mentor_approved_*`, unique `lower(users.email)`, `notification_rules` channel CHECK.
|
||||
- Mentor approval is now persisted (`mentor_approved_at/by`) with an admin toggle in the People panel; auto-fill/assignment use it instead of inferring from the level.
|
||||
- `approvedAt` is set/cleared on status transitions; approval is derived from `status === active && !deactivatedAt`.
|
||||
- New post-service cron `GET /api/dev/cron/complete` closes past assignments and maintains `user_skills.last_served_on` / `users.last_served_at` (idempotent).
|
||||
- CI now runs on `master`, with a Postgres service, migration-drift check and Playwright; Playwright DB URL is overridable.
|
||||
- `.env.example` and compose env describe the real variables; compose keeps the local console login working (`MAGIC_LINK_DEV_TRANSPORT=true`) and reset off.
|
||||
|
||||
**Verification (all green)**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**36 files / 278 tests**) · `next build` ✓
|
||||
- Playwright **24/24** against the rebuilt app (including the updated assign scenario: Sam is qualified for both seats, so only rule 1 can reject the duplicate).
|
||||
- `drizzle-kit migrate` applied `0013`; container rebuilt and healthy on :3000.
|
||||
|
||||
**Still open:** rich text/announcements (F1), exports/ICS/swaps (G), full event seats/reminders (J remainder), SMS (E5), retention/pruning for notifications, magic tokens, used tokens and orphaned upload files, reminder-count/reliability metrics, and a distributed rate limiter if the app is ever horizontally scaled.
|
||||
|
||||
---
|
||||
|
||||
## Event photography & shared RAW folders — DONE 2026-11-19
|
||||
|
||||
**Request:** add a photographer section where a photographer can be assigned to an event, create an event folder, upload RAW/edited images, and another assigned photographer can download them to edit. (Reference: Immich's album/upload model.) Answer: yes — implemented as a vertical slice rather than only a plan.
|
||||
|
||||
**Data model (migration `0014_nifty_calypso.sql`)**
|
||||
- `events` — title, type, local-time `starts_at`, location, shot brief, creator.
|
||||
- `event_photographers` — PK `(event_id, user_id)`, role `photographer | second_shooter | editor`, assigned_by/at.
|
||||
- `event_folders` — unique `(event_id, name)`, kind `originals | edited | mixed`.
|
||||
- `event_photos` — metadata only; unique `(folder_id, checksum_sha256)` dedupes re-uploads; kind `raw | image`; uploader RESTRICT.
|
||||
|
||||
**Access model (`src/lib/event-access.ts`)**
|
||||
- Managers (`schedule.publish` = coordinator/admin) see every event, assign/remove people, and can contribute.
|
||||
- Only assigned photographers/editors see an event; all assignees can create folders, upload, and download each other's files. Unassigned users get 404 (not 403) so event existence is not leaked.
|
||||
- Delete is uploader-or-manager only. UI hides controls to match.
|
||||
|
||||
**Storage & upload**
|
||||
- `src/lib/event-photos.ts`: extension allow-list for JPEG/PNG/WebP/GIF/AVIF/HEIC/TIFF/PSD plus CR2/CR3/NEF/ARW/DNG/RAF/ORF/RW2/…; MIME derived server-side; generated `events/<eventId>/<photoId>.<ext>` paths with traversal guard; safe RFC 6266 dispositions.
|
||||
- Upload is a **single raw request body**, not multipart: `POST /api/events/:id/folders/:folderId/photos?name=…` streams to disk through a size/hash transform (200 MB cap), so a 100 MB RAW frame is never buffered in memory. SHA-256 is computed during the write; duplicate bytes return the existing row instead of a second copy.
|
||||
- Images are inline-only for browser-renderable formats; RAW/TIFF/PSD force `attachment`. Downloads stream from disk with private caching and `nosniff`/CSP headers.
|
||||
|
||||
**UI**
|
||||
- Nav gains **Events**; `/events` shows upcoming/past (managers see all + create form, photographers see assignments), `/events/[id]` shows brief, assignees and folders, `/events/[id]/folders/[folderId]` is the gallery and uploader.
|
||||
- Uploads run sequentially with per-file status; gallery previews JPEG/PNG/WebP and shows a RAW file tile; every file has Download; uploader/manager sees Delete.
|
||||
- Folder creation is available to any assignee; photographer assignment is manager-only.
|
||||
|
||||
**Verification**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**38 files / 292 tests**) · `next build` ✓
|
||||
- Removal guard: a person who uploaded event photos cannot be hard-deleted (FK RESTRICT); `removalPlan` now returns a clear "deactivate instead" conflict, with a unit test.
|
||||
- Playwright **28/28** (4 new): coordinator creates event + assigns Avery and Sam → Avery creates folder and uploads a PNG + CR3 → Sam downloads the PNG byte-for-byte → Jordan (unassigned) gets 404.
|
||||
- `0014` applied to the compose Postgres; app container rebuilt and healthy.
|
||||
|
||||
**Known limits:** no server-side thumbnails/transcoding (full JPEG is used for previews), no ZIP folder download, no public gallery or culling/consent flow, no storage quota/retention, and event seats are not yet part of the weekly scheduling/publish pipeline (`slots.event_id` remains unlinked).
|
||||
|
||||
### Post-feature fix — stale sessions on upload (2026-11-19)
|
||||
|
||||
**Symptom:** a real upload after the E2E reset failed with a 500 and the generic "upload failed" message. Container logs showed `event_photos_uploader_id_users_id_fk` rejecting the session's user id — the JWT still carried the pre-reset id.
|
||||
|
||||
**Fix:** `gateOrUser` now re-reads `users` on every guarded request and rejects missing/inactive/deactivated accounts with `401 STALE_SESSION`; it also uses the DB role, not the JWT role. The photo gallery detects 401, shows "Your session expired" and sends the user to `/login`. Re-verified with a fresh magic-link session through the running container: create event → create folder → raw-body PNG upload → `201`, row present, bytes written. Test artifact cleaned up afterward.
|
||||
|
||||
---
|
||||
|
||||
## Event deletion + announcements — DONE 2026-11-19
|
||||
|
||||
**Request:** admins can delete photo events and their files; announcements can be created from the admin side.
|
||||
|
||||
**Event deletion**
|
||||
- `DELETE /api/events/:id` (manager / `schedule.publish`): verifies access, deletes the event in a transaction (folders and photo metadata cascade), then recursively removes `UPLOAD_DIR/events/<eventId>` and writes `event.deleted` to the audit log with the photo count.
|
||||
- Delete is offered on the event detail page as a destructive button with a confirmation; it is hidden from assigned photographers without the manager role.
|
||||
- `eventPhotoDir()` is the traversal-guarded path helper; delete is best-effort on bytes so a storage error cannot leave a half-deleted event row.
|
||||
- E2E: after uploads, the manager deletes the event; detail URL and previously downloadable photo both return 404.
|
||||
|
||||
**Announcements**
|
||||
- Migration `0015_vengeful_sabra.sql` + `announcements` table: title, plain-text body, published flag, author, timestamps.
|
||||
- `/api/announcements` — signed-in GET (published only; drafts for authors), and `content.author` POST/PATCH/DELETE.
|
||||
- `/announcements` is now a real feed: admins/coordinators create posts (publish now or draft), publish/unpublish and delete; volunteers see published posts with no authoring controls. Bodies render as text, never HTML.
|
||||
- `notifications`/seed reset includes the new table; E2E covers admin create → volunteer visibility → unpublish hides it.
|
||||
|
||||
**Verification**
|
||||
- `tsc --noEmit` ✓ · `eslint src e2e` ✓ · `vitest run` ✓ (**38 files / 293 tests**) · `next build` ✓
|
||||
- Playwright **32/32** against a **separate `media_e2e` database** (migrated + seeded), so the development DB and the user's session/data are not reset by tests.
|
||||
- `0015` applied to the dev Postgres; container rebuilt and healthy on :3000.
|
||||
|
||||
Reference in New Issue
Block a user