diff --git a/.agent/HANDOFF-C2.md b/.agent/HANDOFF-C2.md deleted file mode 100644 index 6852c1f..0000000 --- a/.agent/HANDOFF-C2.md +++ /dev/null @@ -1,59 +0,0 @@ -# SESSION HANDOFF — C2 (Volunteer `/profile/skills` sliders) - -**Date:** 2026-11-18 · **Status:** C2 DONE and committed. - ---- - -## TL;DR - -- **C1 committed** (`1b34421`) — Skills composer. -- **C2 committed** — `user_skills` table, slider API, validation; 55 unit tests - green, 18-check runtime smoke green, migration `0005` applied to :5433. -- **App runs on :3000.** Next unit: **C3 — admin skills matrix + verify modal.** - -## ⚠️ Do not blanket-kill `next-server` - -Previous sessions chased a "stuck build" by running -`pkill -9 -f next-server`. That process is **pi-web, the agent's own UI host** -(`node …/pi-web`, cwd `…/node_modules/@agegr/pi-web`, Next v16.3.8, port 30141). -Killing it ends the session, and its supervisor respawns it with a new PID — which -looks like "next-server keeps coming back". The project is Next 15.5.29; its app -is identified by **port 3000**, not by process name. - -To free a port, resolve the PID through the port and only kill that: - -``` -ss -ltnp | grep ':3000' -``` - -## Running the app (this sandbox) - -`pnpm` is not on PATH here; use the local binaries. - -``` -DATABASE_URL="postgres://media:media@localhost:5433/media" \ -NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="dev-secret" \ -AUTO_ACTIVATE_NEW_USERS="true" PORT=3000 \ -./node_modules/.bin/next start # run as a background/detached process -``` - -Ready in <1s; `curl localhost:3000/api/health` → 200. - -- **DB:** Postgres on **:5433** (docker), not 5432. - `PGPASSWORD=media psql -h localhost -p 5433 -U media -d media` -- **Migrate:** `DATABASE_URL="postgres://media:media@localhost:5433/media" ./node_modules/.bin/drizzle-kit migrate` -- **Checks:** `./node_modules/.bin/{tsc --noEmit | eslint . | vitest run | next build}` -- No sudo needed for any of the above. `/tmp/start_app.sh` no longer exists. - -## What C2 guarantees - -Two numbers, one truth: `self_comfort` (volunteer's slider, 0–100 int or null) -is the signal; `verified_level` is the gate. `setSelfComfort` updates only -`self_comfort`/`self_rated_at` on conflict, so moving a slider can never move a -verified level or its audit columns (C3 owns those). - -## Next: C3 — Admin skills matrix + verify-level modal - -- Writes `skill_assessments` (append-only) and updates `verified_level` on - `user_skills` (+ `verified_by`/`verified_at`). -- E2E: verify writes an assessment row + updates the level; audit row exists. diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index 4927755..a8c7b08 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -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//.` 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/` 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. diff --git a/.env.example b/.env.example index 076c61f..da116d8 100644 --- a/.env.example +++ b/.env.example @@ -5,22 +5,61 @@ # --------------------------------------------------------------------------- # Database (Postgres). docker-compose sets this for the app container. -DATABASE_URL=postgres://media:media@localhost:5432/media +DATABASE_URL=postgres://media:media@localhost:5433/media # Auth (magic-link). Generate a secret with: openssl rand -base64 32 +# This value also encrypts the admin-entered Gmail app password: rotating it +# makes stored SMTP credentials undecryptable (they are then treated as unset). NEXTAUTH_URL=http://localhost:3000 NEXTAUTH_SECRET=change-me-generate-a-random-secret -# Email (Postmark) — deferred? No: email is launch. SMS (Twilio) is later. -POSTMARK_SERVER_TOKEN= -POSTMARK_FROM=media@localhost - -# AI assist (optional, phase 4). App degrades gracefully without it. -LLM_API_KEY= +# Canonical origin used in emailed links (sign-in, confirm/decline). Set this +# to the public URL in any deployment reachable from outside the LAN. Leave +# empty locally to use the request origin. +PUBLIC_ORIGIN= # App APP_ORIGIN=http://localhost:3000 CHURCH_TIMEZONE=America/New_York -# Observability +# New sign-ins. false = admin approval required (recommended for anything +# reachable off-host). true = auto-activate unknown emails (dev/test only). +AUTO_ACTIVATE_NEW_USERS=false + +# Console magic-link transport: returns/prints the sign-in URL instead of +# emailing it. Defaults to on outside production; set true explicitly for the +# local container stack, which has no mail provider configured out of the box. +MAGIC_LINK_DEV_TRANSPORT=true + +# Destructive E2E/test endpoint POST /api/dev/reset. Must be true for the +# Playwright suite; must stay false in a real deployment. +ALLOW_DEV_RESET=false + +# Shared secret for the HTTP cron routes: +# GET /api/dev/cron/instances|slots|notifications|complete +# Send it as `Authorization: Bearer ` or `?secret=`. +CRON_SECRET= + +# Email delivery. Precedence at send time: +# 1. Gmail SMTP configured in Admin → Email delivery (stored encrypted) +# 2. Postmark, when POSTMARK_SERVER_TOKEN is set +# 3. Console transport: writes JSON messages under OUTBOX_DIR +POSTMARK_SERVER_TOKEN= +POSTMARK_FROM=media@localhost + +# Console transport directory (a named Docker volume in compose). +OUTBOX_DIR=/tmp/outbox + +# Training attachments (metadata in Postgres, bytes on disk; max 5 MB each). +UPLOAD_DIR=/tmp/uploads + +# NFS archive. Mount the export on the Docker host, then point +# MEDIA_ARCHIVE_DIR at that host mount when starting compose: +# MEDIA_ARCHIVE_DIR=/mnt/nfs/glenloch docker compose up -d +# The app always writes to /archive inside the container; admins can change the +# archive subfolder in Settings → Photo archive (NFS). +ARCHIVE_DIR=/archive +NFS_SHARE= + +# Observability (declared; no Sentry integration is wired yet) SENTRY_DSN= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d77d5a5..0c6613d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,13 +2,35 @@ name: CI on: push: - branches: [main, develop] + branches: [master] pull_request: - branches: [main, develop] + branches: [master] jobs: build: runs-on: ubuntu-latest + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: media + POSTGRES_PASSWORD: media + POSTGRES_DB: media + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U media" + --health-interval 5s + --health-timeout 5s + --health-retries 10 + env: + DATABASE_URL: postgres://media:media@localhost:5432/media + NEXTAUTH_SECRET: ci-secret-not-for-production + NEXTAUTH_URL: http://localhost:3000 + AUTO_ACTIVATE_NEW_USERS: "true" + MAGIC_LINK_DEV_TRANSPORT: "true" + ALLOW_DEV_RESET: "true" + CRON_SECRET: ci-cron-secret steps: - uses: actions/checkout@v4 @@ -24,6 +46,12 @@ jobs: - name: Install run: pnpm install --frozen-lockfile + - name: Install media tools + run: sudo apt-get update && sudo apt-get install -y postgresql-client unzip ffmpeg + + - name: Migration drift check + run: pnpm db:generate && git diff --exit-code -- drizzle + - name: Typecheck run: pnpm typecheck @@ -33,5 +61,11 @@ jobs: - name: Test run: pnpm test + - name: Apply migrations + run: pnpm db:migrate + + - name: End-to-end + run: pnpm test:e2e + - name: Build run: pnpm build diff --git a/.pi/DEAD_ENDS.md b/.pi/DEAD_ENDS.md new file mode 100644 index 0000000..763525f --- /dev/null +++ b/.pi/DEAD_ENDS.md @@ -0,0 +1,25 @@ +# Dead-Ends Ledger + +Append-only. Re-injected into every session. Write a entry when an approach +fails twice, or a probe/assumption is proven invalid. + +--- + +## 2026-11-18 — `weekdayInTz()` returns `undefined`; `partsInTz()` never emits `weekday` +- **Settled:** `partsInTz()` builds its `Intl.DateTimeFormat` without a `weekday` option, so `partsInTz(...).weekday` is always `undefined`. `weekdayInTz()` returned that `undefined` (cast `as unknown as number`), and `nextSundaysInTz()` (which also reads `.weekday`) was silently wrong — the seed created instances on the wrong Sundays. +- **Do not retry:** assuming `weekdayInTz(date, tz)` returns a number, or relying on `nextSundaysInTz()` dates without verifying. +- **Why:** the missing Intl part means every call returns `undefined` → `WEEKDAYS.indexOf(undefined)` = -1 → off-by-week instance dates. +- **Instead:** add `weekday: "short"` to `partsInTz`'s format and make `weekdayInTz` return `WEEKDAYS.indexOf(label)` (done in `src/lib/tz.ts`). Verified: Tue 2026-11-18 → weekStart 2026-11-16; next Sundays 11-23 / 11-30. + +## 2026-11-18 — D7 E2E cannot be completed in-session; harness hangs abort the run +- **Settled:** the Playwright run (`e2e/schedule-grid.spec.ts` + `e2e/shell.spec.ts`) reaches the webServer build/start phase but the command is aborted (SIGTERM / "Command aborted") before tests finish green. Code, typecheck, eslint, unit suite, and build are all green; DB re-seeded; only the E2E pass + commit remain. +- **Do not retry:** assuming D7 is done just because `tsc`/`eslint`/`vitest`/`next build` pass — the E2E (the unit's actual Done-when) has not completed green. +- **Why:** the Done-when for D7 is "E2E renders a seeded week; no console errors"; that gate is unmet until the Playwright run finishes. +- **Instead:** in a fresh session, start the app with `NEXTAUTH_SECRET` set (E2E webServer sets it; a bare `pnpm start` throws Auth.js `MissingSecret`), run `npx playwright test e2e/schedule-grid.spec.ts e2e/shell.spec.ts`, then commit. + +## 2026-11-18 — D7 E2E CAN complete in-session; two more latent tz/CSS bugs fixed +- **Settled:** the D7 E2E (6/6) runs green in-session once the app is rebuilt+restarted with `NEXTAUTH_SECRET` set. Two further bugs were the real blockers, both now fixed. +- **Supersedes:** the 2026-11-18 entry ("D7 E2E cannot be completed in-session; harness hangs abort the run"). +- **Do not retry:** assuming the grid is fine just because `curl /schedule` shows the HTML — the browser can render it invisible (see below). +- **Why it failed (2):** (1) `weekdayInTz`/`nextSundaysInTz` built `Date.UTC(y,mo-1,d)` from a *local* date string and read its weekday — for America/New_York (UTC-5) UTC midnight lands the previous evening, so the seed materialized instances on **Mondays** and the default week was off by one. Fixed: `weekdayInTz` builds the local-midnight instant via `utcOffsetMs`; `nextSundaysInTz` uses `weekdayInTz` + `addDaysISO`. (2) `` set `visibility: collapse` (Tailwind `collapse`), hiding the whole grid server-rendered-but-invisible. Fixed: `border-collapse`. +- **Instead:** fix tz + grid, `TRUNCATE assignments, slots, service_instances` then `tsx src/db/seed.ts`, rebuild+restart, run `npx playwright test e2e/schedule-grid.spec.ts e2e/shell.spec.ts`. diff --git a/A4_HANDOFF.md b/A4_HANDOFF.md deleted file mode 100644 index 215f14c..0000000 --- a/A4_HANDOFF.md +++ /dev/null @@ -1,126 +0,0 @@ -# A4 Handoff — App Shell - -**Status:** In progress. A1, A2, A3 committed. A4 work is uncommitted. - -**Resolved:** The `/api/dev/complete` session bug (see below). With it fixed, all 4 e2e shell tests pass, plus typecheck/lint/17 unit tests. Next session: commit A4 (instructions at the bottom of this file). - ---- - -## What's Done - -- **A1** (commit `9cdf8be`): Foundation scaffold — Next.js 15, shadcn/Radix, Drizzle+Postgres, Vitest, Docker. -- **A2** (commit `d133aff`): Schema core — 6 tables, migration, idempotent seed. -- **A3** (commit `c0e73e2`): Auth — magic-link sign-in, `requirePermission()` chokepoint, role enum. - -## A4 Work (Uncommitted) - -Built for the app shell: - -- `src/components/app/nav.tsx` — Nav (5 tabs mobile / rail desktop). Uses lucide-react icons. -- `src/components/app/state-message.tsx` — Error + empty states. -- `src/components/app/app-layout.tsx` — Shell layout (header, nav, main, footer). -- `src/app/(app)/layout.tsx` — Authenticated route group (redirects to /login if no session). -- `src/app/(app)/schedule/page.tsx` — `src/app/(app)/roster/page.tsx` — `src/app/(app)/training/page.tsx` — `src/app/(app)/announcements/page.tsx` — `src/app/(app)/settings/page.tsx` — 5 shell pages. -- `src/app/api/health/route.ts` — Health check endpoint. -- `e2e/shell.spec.ts` — Playwright e2e test (5 nav tabs at 360px viewport). -- `playwright.config.ts` — Playwright config. -- `package.json` — Added `test:e2e` script. -- `src/app/api/dev/complete/route.ts` — Added try/catch + logging around `signIn`. - ---- - -## The Blocker (RESOLVED): `/api/dev/complete` never set a session cookie - -**Original report:** `GET /api/dev/complete?token=...` appeared to return HTTP 000 / connection -reset. That was a **test-harness artifact** (curl URL parsing/quoting in the handoff's shell -script), not an app bug — the endpoint returns `200 {"ok":true}`. - -**Real symptom:** The complete response carried **no `Set-Cookie` header**, so no session cookie -was established. Every subsequent navigation to `/schedule` (etc.) then 307-redirected to -`/login`, and the two shell e2e tests failed (nav tabs never rendered). The route reported -`{"ok":true}` because `signIn` returned the error-page URL rather than throwing. - -**Root cause:** `[auth][error] UntrustedHost: Host must be trusted.` -- Auth.js v5's `assertConfig()` checks `config.trustHost` **before** `setEnvDefaults()` applies - its env-based default (the code comment says so explicitly). -- `setEnvDefaults()` only derives `trustHost` from `AUTH_URL` / `AUTH_TRUST_HOST` / `VERCEL` / - `CF_PAGES` / `NODE_ENV !== "production"` — **not** from `NEXTAUTH_URL`. -- In `pnpm start` (production, `NODE_ENV=production`) with no `AUTH_URL`, `trustHost` stayed - `false`, so the magic-link callback was rejected and no session cookie was written. -- `pnpm dev` worked (dev mode) and Docker set `NEXTAUTH_URL` — but that var does not set - `trustHost`, so Docker had the same latent bug. - -**Fix:** `src/auth/config.ts` now sets `trustHost: true` explicitly (the documented fix for -`UntrustedHost`; this is a localhost app behind a reverse proxy). Rebuild required for -`pnpm start`. Verified: complete response now sets `authjs.session-token`, `/schedule` returns -200, and all 4 e2e shell tests pass. - ---- - -## How to Test (for next session) - -Start the app and test the complete flow: - -```bash -cd /home/bhursey/code/glenlochmedia - -# Start app (detached, kills itself on exit) -env DATABASE_URL="postgres://media:media@localhost:5433/media" \ - NEXTAUTH_SECRET="e2e-secret-for-shell-tests" \ - AUTO_ACTIVATE_NEW_USERS="true" \ - PORT=3000 \ - pnpm start >/tmp/app.log 2>&1 & -APP_PID=$! - -# Wait for ready -for i in $(seq 1 30); do grep -qiE "Ready" /tmp/app.log && break; sleep 1; done - -# Get a token -TOKEN_URL=$(curl -s -X POST localhost:3000/api/dev/magic-link \ - -H 'Content-Type: application/json' \ - -d '{"email":"e2e-test@example.com"}' \ - | python3 -c "import sys,json; print(json.load(sys.stdin)['url'])") - -# Complete sign-in (this is where HTTP 000 happens) -curl -sv "http://localhost:3000$TOKEN_URL" 2>&1 | grep -iE "set-cookie|HTTP/|error" - -# Cleanup -kill $APP_PID -``` - -**Note:** Use valid emails (with a TLD). Zod's `.email()` rejects `@localhost`. - ---- - -## E2E Test - -```bash -cd /home/bhursey/code/glenlochmedia -pnpm test:e2e --grep shell -``` - -The webServer runs `pnpm db:migrate && pnpm build && pnpm start` on port 3000. - -**Current e2e status:** Both shell tests fail because `signInAs` doesn't establish a session (the complete endpoint resets the connection). Once the complete endpoint works, the e2e tests should pass. - ---- - -## Known Good Commands - -- Typecheck: `pnpm typecheck` (exit 0) -- Lint: `pnpm lint` (exit 0) -- Unit tests: `pnpm test` (17 tests, exit 0) -- Build: `pnpm build` (exit 0) -- DB migrate: `pnpm db:migrate` (needs Postgres on :5433) -- DB seed: `pnpm db:seed` - ---- - -## To Commit A4 (once complete) - -```bash -cd /home/bhursey/code/glenlochmedia -rm -f src/app/api/dev/magic-debug.log # debug file, don't commit -git add -A -git commit -m "A4: app shell (layout, nav, tokens, error/empty states, /api/health)" -``` diff --git a/Dockerfile b/Dockerfile index 842d1a7..e2fe3bc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,6 +7,10 @@ FROM node:22-alpine AS base WORKDIR /app ENV NODE_ENV=production +# ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor; +# sharp does the tone rendering and JPEG encode. The Postgres client provides +# pg_dump/psql for admin backups and restores; unzip reads restore packages. +RUN apk add --no-cache imagemagick libraw ffmpeg postgresql16-client unzip # pnpm is how this project is built (see package.json scripts). RUN npm install -g pnpm@9.15.0 @@ -18,22 +22,38 @@ RUN pnpm install --frozen-lockfile COPY . . RUN pnpm build -FROM node:22-alpine AS runner +# --------------------------------------------------------------------------- +# Tools stage — migrations + seed run from the builder image, which has the +# source, `drizzle/` and dev dependencies (drizzle-kit, tsx). Keeping them out of +# the runner keeps the serving image lean. +# --------------------------------------------------------------------------- +FROM builder AS tools +ENV NODE_ENV=development +CMD ["sh", "-c", "pnpm db:migrate && pnpm db:seed"] + +FROM base AS runner WORKDIR /app ENV NODE_ENV=production -# pnpm runs the app in production (see package.json scripts). -RUN npm install -g pnpm@9.15.0 +# Inherits pnpm and the ImageMagick/LibRaw runtime tools from `base`. # Run as a non-root user (busybox adduser/addgroup on alpine). RUN addgroup -S nodegrp \ && adduser -S -G nodegrp -H -D nextjs +# Some ImageMagick temporary work happens under /tmp; it is writable by all. +RUN chmod 1777 /tmp + # Build output, deps, static assets. COPY --from=builder --chown=nextjs:nodegrp /app/public ./public COPY --from=builder --chown=nextjs:nodegrp /app/node_modules ./node_modules COPY --from=builder --chown=nextjs:nodegrp /app/package.json ./package.json COPY --from=builder --chown=nextjs:nodegrp /app/.next ./.next +# The console email transport writes here. Create it in the image owned by the +# runtime user so a mounted named volume inherits that ownership (a root-owned +# volume made every send fail with EACCES in the first deploy). +RUN mkdir -p /tmp/outbox /tmp/uploads /archive && chown -R nextjs:nodegrp /tmp/outbox /tmp/uploads /archive + USER nextjs EXPOSE 3000 ENV PORT=3000 diff --git a/README.md b/README.md index 4ff5926..7ac06be 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ -# Media Team Hub — Planning Docs +# Media Team Hub -Architecture and build documentation for a church media team scheduling and training platform. No application code yet — these are the documents you review, approve, and hand to whoever builds it. +Scheduling and training platform for a church media team. + +> **Current state:** the app is built and running (Next.js 15 + Postgres, containerised). For the live code map, phase status, the security/correctness repair pass, remaining gaps and next steps, read **[docs/PROJECT-STATE.md](docs/PROJECT-STATE.md)**. The sections below are the original planning docs and describe intended behaviour; the stack notes are historical (the build targets a portable Node container, not Cloudflare Workers). ## Read in this order @@ -11,6 +13,52 @@ Architecture and build documentation for a church media team scheduling and trai | **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** | How is it built — stack, data model, scheduling and reminder logic, security. | ~25 min | | **[docs/BUILD-PLAN.md](docs/BUILD-PLAN.md)** | The order to build it in: 56 units across 10 phases (plus 5 deferred media-library units), 7 checkpoints, and the rules that stop an AI agent looping. Give this to the agent. | ~15 min | +## Media library & video + +**Media** is an ad-free library of the event photos and videos the signed-in +person can access. Event photos remain private to assigned photographers and +managers; the library does not publish them. + +Videos are uploaded from an event page or the Media page: + +- The untouched camera original is written to + `//videos//
+ + + + + + + + + {team.map((person) => ( + + + + + + ))} + +
+ Name + + Role + + Email +
+ {person.displayName} + + + {person.systemRole} + + {person.email}
+ + )} + ); } diff --git a/src/app/(app)/run-sheet/[instanceId]/page.tsx b/src/app/(app)/run-sheet/[instanceId]/page.tsx new file mode 100644 index 0000000..275d33d --- /dev/null +++ b/src/app/(app)/run-sheet/[instanceId]/page.tsx @@ -0,0 +1,28 @@ +import { notFound } from "next/navigation"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { getRunSheet } from "@/db/runSheet"; +import { RunSheetEditor } from "@/components/app/run-sheet/run-sheet-editor"; + +export const metadata = { title: "Run sheet" }; + +export default async function RunSheetPage({ + params, +}: { + params: Promise<{ instanceId: string }>; +}) { + const { instanceId } = await params; + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) return null; + + const data = await getRunSheet(instanceId); + if (!data) notFound(); + + const canEdit = hasPermission(user.systemRole, "schedule.publish"); + + return ; +} diff --git a/src/app/(app)/schedule/page.tsx b/src/app/(app)/schedule/page.tsx index 7d1c9cb..340b1d0 100644 --- a/src/app/(app)/schedule/page.tsx +++ b/src/app/(app)/schedule/page.tsx @@ -1,51 +1,139 @@ import { gridForWeek, defaultWeekStart } from "@/db/grid"; +import { calendarInstances } from "@/db/calendar"; import { activeVolunteers } from "@/db/volunteers"; import { WeekNav } from "@/components/app/week-nav"; +import { ScheduleAdminBar } from "@/components/app/schedule-admin-bar"; import { ScheduleGrid } from "@/components/app/schedule-grid"; import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor"; +import { + MonthNav, + ScheduleViewToggle, + YearNav, +} from "@/components/app/calendar-nav"; +import { MonthCalendar } from "@/components/app/month-calendar"; +import { YearCalendar } from "@/components/app/year-calendar"; import { auth } from "@/auth/config"; import { hasPermission } from "@/auth/permissions"; import type { SystemRole } from "@/auth/roles"; import { db } from "@/db"; +import { CHURCH_TIMEZONE, dateInTimezone } from "@/lib/tz"; +import { + isValidMonth, + isValidYear, + monthRange, + yearRange, +} from "@/domain/calendar"; export const metadata = { title: "Schedule" }; +type ScheduleView = "week" | "month" | "year"; + /** - * Scheduling grid (unit D7, extended by D8). Read-only for volunteers; the - * interactive optimistic editor for anyone with `schedule.publish` - * (coordinator + admin). Week via `?week=YYYY-MM-DD` (a Sunday); defaults to - * the week of the earliest upcoming published instance so a seeded DB shows - * data at once. + * Schedule with three lenses: + * - week: the editable grid (assign/clear), admin publish + auto-fill; + * - month: an overview grid of services, linking into the week; + * - year: twelve month cards with build-out counts. + * + * `?view=` selects the lens; `?week=`/`?month=`/`?year=` anchor it. Month and + * year are read-only by design — editing happens where the seats are visible. */ export default async function SchedulePage({ searchParams, }: { - searchParams: Promise<{ week?: string }>; + searchParams: Promise<{ + view?: string; + week?: string; + month?: string; + year?: string; + }>; }) { - const { week: paramWeek } = await searchParams; - // Validate the param is a YYYY-MM-DD string; fall back to the default week. - const weekStart = - typeof paramWeek === "string" && /^\d{4}-\d{2}-\d{2}$/.test(paramWeek) - ? paramWeek - : await defaultWeekStart(); + const params = await searchParams; + const view: ScheduleView = + params.view === "month" ? "month" : params.view === "year" ? "year" : "week"; - const week = await gridForWeek(weekStart); + const today = dateInTimezone(new Date(), CHURCH_TIMEZONE); + const weekStart = + typeof params.week === "string" && /^\d{4}-\d{2}-\d{2}$/.test(params.week) + ? params.week + : await defaultWeekStart(); + const month = + typeof params.month === "string" && isValidMonth(params.month) + ? params.month + : today.slice(0, 7); + const year = + typeof params.year === "string" && isValidYear(params.year) + ? Number(params.year) + : Number(today.slice(0, 4)); const session = await auth(); - const role = (session?.user as { systemRole: SystemRole } | null | undefined) + const role = (session?.user as { systemRole?: SystemRole } | null | undefined) ?.systemRole; const canEdit = role ? hasPermission(role, "schedule.publish") : false; + const header = ( +
+

Schedule

+

+ {view === "week" + ? "Service instances for the week and who is on each position." + : view === "month" + ? "Every service this month. Open a week to edit assignments." + : "A year at a glance — how much of the schedule is built and published."} +

+
+ ); + + const toggle = ( + + ); + + if (view === "month") { + const range = monthRange(month); + const instances = await calendarInstances(range.start, range.end); + return ( +
+ {header} + {toggle} + + +
+ ); + } + + if (view === "year") { + const range = yearRange(year); + const instances = await calendarInstances(range.start, range.end); + return ( +
+ {header} + {toggle} + + +
+ ); + } + + const week = await gridForWeek(weekStart); + return (
-
-

Schedule

-

- Service instances for the week and who is on each position. -

-
- + {header} + {toggle} + {canEdit && ( + ({ + id: inst.id, + label: `${inst.occursOn} · ${inst.serviceName}`, + status: inst.status, + }))} + /> + )} {canEdit ? ( ) : ( diff --git a/src/app/(app)/schedule/print/page.tsx b/src/app/(app)/schedule/print/page.tsx new file mode 100644 index 0000000..8c6fb7c --- /dev/null +++ b/src/app/(app)/schedule/print/page.tsx @@ -0,0 +1,154 @@ +import Link from "next/link"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { scheduleExportRows, type ScheduleExportRow } from "@/db/exports"; +import { + addDaysISO, + CHURCH_TIMEZONE, + dateInTimezone, + formatInTimezone, + weekStartOn, +} from "@/lib/tz"; +import { PrintButton } from "@/components/app/print-button"; +import { Button } from "@/components/ui/button"; + +export const metadata = { title: "Printable roster" }; + +function shortDate(iso: string): string { + return new Date(`${iso}T00:00:00Z`).toLocaleDateString("en-US", { + timeZone: "UTC", + weekday: "long", + month: "long", + day: "numeric", + }); +} + +interface Group { + key: string; + date: string; + serviceName: string; + startTime: string; + rows: ScheduleExportRow[]; +} + +function group(rows: ScheduleExportRow[]): Group[] { + const groups = new Map(); + for (const row of rows) { + const date = row.occursOn + ? `${row.occursOn.getUTCFullYear()}-${String(row.occursOn.getUTCMonth() + 1).padStart(2, "0")}-${String(row.occursOn.getUTCDate()).padStart(2, "0")}` + : ""; + const key = `${date}:${row.serviceName}`; + let group = groups.get(key); + if (!group) { + group = { + key, + date, + serviceName: row.serviceName, + startTime: row.startsAt + ? formatInTimezone(row.startsAt, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + hour: "numeric", + minute: "2-digit", + }) + : "", + rows: [], + }; + groups.set(key, group); + } + group.rows.push(row); + } + return [...groups.values()]; +} + +export default async function PrintSchedulePage({ + searchParams, +}: { + searchParams: Promise<{ week?: string }>; +}) { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined) + ?.systemRole; + if (!session?.user) return null; + if (!hasPermission(role, "schedule.publish")) return null; + + const params = await searchParams; + const today = dateInTimezone(new Date(), CHURCH_TIMEZONE); + const weekStart = + params.week && /^\d{4}-\d{2}-\d{2}$/.test(params.week) + ? params.week + : weekStartOn(today, CHURCH_TIMEZONE); + + const rows = await scheduleExportRows(weekStart, addDaysISO(weekStart, 6)); + const groups = group(rows); + + return ( +
+
+
+

Printable roster

+

+ Week of {shortDate(weekStart)} — includes every assignment and its + confirmation state. +

+
+
+ + +
+
+ +
+

Media team roster

+

Week of {shortDate(weekStart)}

+
+ + {groups.length === 0 ? ( +

+ No assignments in this week. +

+ ) : ( +
+ {groups.map((item) => ( +
+

+ {item.date ? shortDate(item.date) : ""} · {item.serviceName} ·{" "} + {item.startTime} +

+ + + + + + + + + + + {item.rows.map((row, index) => ( + + + + + + + ))} + +
RoleVolunteerCallStatus
{row.roleName}{row.userName} + {row.callTime + ? formatInTimezone(row.callTime, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + hour: "numeric", + minute: "2-digit", + }) + : "—"} + {row.status}
+
+ ))} +
+ )} +
+ ); +} diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx index a1ee16b..4441e75 100644 --- a/src/app/(app)/settings/page.tsx +++ b/src/app/(app)/settings/page.tsx @@ -1,16 +1,173 @@ -import { StateMessage } from "@/components/app/state-message"; +import Link from "next/link"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { getEmailSettings } from "@/db/settings"; +import { getUserSecurity } from "@/db/users"; +import { + checkArchiveDestination, + getStorageSettings, +} from "@/db/storage-settings"; +import { CHURCH_TIMEZONE } from "@/lib/tz"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { SettingsForm } from "@/components/app/settings-form"; +import { StoragePanel } from "@/components/app/storage-panel"; +import { PasswordForm } from "@/components/app/password-form"; export const metadata = { title: "Settings" }; -export default function SettingsPage() { +/** + * Deployment facts plus the admin-editable email identity. The From address + * and admin notification inbox live in the database, so changing them does not + * require a deploy or a container restart. + */ +export default async function SettingsPage() { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole; + const userId = (session?.user as { id?: string } | undefined)?.id; + const security = userId ? await getUserSecurity(userId) : null; + const isAdmin = hasPermission(role, "admin.settings"); + const emailSettings = isAdmin ? await getEmailSettings() : null; + const storageSettings = isAdmin ? await getStorageSettings() : null; + const storageStatus = storageSettings + ? await checkArchiveDestination(storageSettings) + : null; + const emailTransport = emailSettings?.smtpConfigured + ? "Gmail (SMTP)" + : process.env.POSTMARK_SERVER_TOKEN + ? "Postmark" + : "Console outbox (dev)"; + return ( - <> -

Settings

-

Church details, timezone, and scheduling rules.

- - +
+
+

Settings

+

+ Church details and how the app is configured. +

+
+ + {security && ( + + + My account + + Your username and password for signing in. Changing either does + not sign you out of this session. + + + + + Edit profile, notifications, skill comfort and calendar feed + + + + + )} + + + + Church + + Values that drive scheduling and message delivery. + + + +
+
+
+ Timezone +
+
{CHURCH_TIMEZONE}
+
+
+
+ Week starts +
+
Sunday
+
+
+
+ Email delivery +
+
{emailTransport}
+
+
+
+ Signed in as +
+
+ {session?.user?.email ?? "—"} + {security && ( + + Username: {security.username} + + )} +
+
+
+
+
+ + {isAdmin && emailSettings && ( + + + Email & notifications + + Sender identity for assignment mail and where admin test messages + are delivered. + + + + + + + )} + + {isAdmin && storageSettings && storageStatus && ( + + + Media archive (NFS) + + Mount an NFS export into this container. Finished event photos are + archived here, and every uploaded video keeps its camera original + on this mount. Photo archives include originals, saved edits, and a + manifest. + + + + + + + )} + + {isAdmin && ( +

+ People, services, reminder rules, and the notification log live in{" "} + + Admin + + . +

+ )} +
); } diff --git a/src/app/(app)/training/guides/admin/page.tsx b/src/app/(app)/training/guides/admin/page.tsx new file mode 100644 index 0000000..d2cdb96 --- /dev/null +++ b/src/app/(app)/training/guides/admin/page.tsx @@ -0,0 +1,779 @@ +import type { Metadata } from "next"; +import { + GuideCallout, + GuideFields, + GuideFigure, + GuideSection, + GuideShell, + GuideStep, + GuideSteps, +} from "@/components/app/training/guide"; + +export const metadata: Metadata = { + title: "Platform administration guide", +}; + +const SECTIONS = [ + { id: "before-you-start", title: "Before you start" }, + { id: "admin-hub", title: "The admin hub" }, + { id: "people", title: "People and access" }, + { id: "skills", title: "Skill levels" }, + { id: "positions", title: "Positions and requirements" }, + { id: "services-schedule", title: "Services and the schedule" }, + { id: "coverage", title: "Coverage and swaps" }, + { id: "run-sheets", title: "Run sheets" }, + { id: "messages", title: "Reminders and notifications" }, + { id: "email-settings", title: "Email and deployment settings" }, + { id: "backup", title: "Backup and restore" }, + { id: "content", title: "Announcements and training" }, + { id: "exports", title: "Print and CSV exports" }, + { id: "troubleshooting", title: "Troubleshooting" }, +]; + +export default function AdminGuidePage() { + return ( + + +

+ The hub has three working roles. Your role decides which tabs and + buttons exist for you, so a missing control usually means a missing + permission rather than a broken page. +

+ + + + Open the site and sign in at /login with your username + (email by default) and password, or request a one-time sign-in link + by email. + + + After signing in you land on Schedule. Admins and + coordinators also see Dashboard and{" "} + Coverage in the navigation; admins see{" "} + Admin at the end of the rail. + + + Use the same account for desktop and phone. The layout adapts, and + the mobile tab bar scrolls horizontally when there are more tabs + than fit. + + + +

+ You cannot demote or delete the last active admin, and you cannot + delete a person who has scheduling history — deactivate them + instead. Both protections are deliberate; the app will explain the + refusal rather than silently changing the record. +

+
+
+ + +

+ Admin is one long page of cards, in the order you + normally use them: People, Skill levels, Positions & requirements, + Services & schedule, Reminder rules, Email delivery, Backup & + restore, and Notifications. Changes save immediately; there is no + page-level Save button. Reload the page if another admin may have + changed something while you were working. +

+ + +

+ New service instances start as drafts. Volunteers only see the + week, and only receive assignment email, after you publish it. A + draft is safe to edit; a published week should be changed carefully + because people have already been told about it. +

+
+
+ + +

+ The People card is the church directory and the access control panel + at the same time. The table lists everyone, including pending and + deactivated accounts, with their role, status, phone, and actions. +

+ + +

Add someone

+ + + Enter first name, last name, email, and optionally a phone number in + E.164 form (for example +15551234567). + + + Choose the role: volunteer,{" "} + trainee, coordinator, or{" "} + admin. Default to volunteer unless the person + genuinely needs scheduling or admin powers. + + + Leave Needs approval before signing in ticked when + you are not yet sure about the person. They will appear as pending + until you approve them. + + + Press Add user. The app shows a one-time sign-in + link; copy it and send it to the person through a channel you trust. + The link only works once the account is active. + + + +

Approve or deny sign-ups

+

+ People can request access with their email. Pending rows show{" "} + Approve and Deny. Approving makes the + account active and lets the person set a password; denying keeps them + out but leaves the record for your notes. +

+ +

Edit a person

+

+ Edit expands an inline panel. Save with{" "} + Save changes at the bottom of the panel. +

+ + +

+ Deactivating blocks sign-in but keeps the person’s assignment, + training, and audit history intact. Delete is reserved for accounts + created by mistake; the server refuses to delete anyone with + scheduling history and tells you to deactivate instead. +

+
+
+ + +

+ The Skill levels card answers “who is signed off on what?”. Each row is + one person and one skill, with the volunteer’s own comfort rating, the + verified level, and the last date they served that skill. +

+ +

+ The ladder is none → observer → assisted → qualified → + expert. Use the filter at the top to show only one level when + you are auditing a position. +

+ + + Find the person and skill, then open the verify control on that row. + + + Choose the new level. The app preselects the next rung, which is the + usual case. + + + Choose the assessment kind (for example admin, mentor, or practical) + and add a short note explaining the evidence. + + + Save. The change writes an audited assessment and moves the verified + level in one transaction. + + + +

+ The comfort percentage is the volunteer’s own signal from their + profile. Verification changes only the verified level, so a + coordinator cannot quietly rewrite how confident someone feels. +

+
+
+ + +

+ A position is a seat on a service — Audio, Livestream, Slides, and + anything else you add. The table shows seats, call time, required + skills, and whether the position is active. +

+ + + + + Press Edit requirements on a row. + + + Change an existing requirement, press Remove to drop + one, or Add skill to append another. + + + Leave Publishable ticked only when the requirement + set is complete enough to schedule against. + + + Press Save requirements. The whole set is saved + together, so what you see is exactly what is stored. + + +
+ + +

+ A service is the repeating template (for example Sunday 9:00 AM). An + instance is one dated occurrence of that template, and the schedule is + built from instances. +

+ + +

Create a service template

+ + + Enter a clear name (“Sunday 9:00 AM”, “Sunday 5:00 PM”), start time, + length in minutes, and location. + + + Press Add service. New templates use the weekly + Sunday recurrence by default. + + + Press Generate upcoming Sundays to create the + rolling window of instances. Generation is idempotent — running it + twice does not duplicate weeks. + + + Deactivate a template when it stops running. Existing instances are + untouched; future generation skips it. + + + Delete removes a template permanently — use it for + one you added by mistake. It only works while the template has no + published, past, or assigned instances; anything with history has + to be deactivated instead, so the schedule record survives. + + + +

Build and publish a week

+ + + + Open Schedule. The toggle switches between week, + month, and year; the arrows move one week, month, or year at a time. + + + In week view, each column is a position and each row is a service + instance. Press an empty seat to assign someone, or use the row + actions to clear a seat. + + + Auto-fill proposes ranked volunteers for the open + seats. Review every suggestion; the ranking respects skills, + availability, and conflicts, but it does not know the relational + context. + + + Press Publish when the week is ready. Publishing + queues assignment email and reminder rules for that instance. + + + Unpublish only when you intend to withdraw the week; volunteers may + already have received mail. + + + +

+ A hard conflict blocks an assignment (already serving elsewhere in + the same service, a blackout, or a missing core skill). A soft + conflict is a warning you may override, such as exceeding a monthly + serving cap. The app shows which is which before you save. +

+
+
+ + +

+ The Coverage dashboard summarises the next five weeks: filled and open + seats, unconfirmed assignments, pending people, and the queues that + need a coordinator. Coverage is the working queue for + swaps and outside requests. +

+ + + +

Handle a swap request

+ + + Open Coverage. Each request names the volunteer, + the seat, and the service, with the reason they gave. + + + Review the ranked eligible replacements and their warnings. Pick + someone whose skills and availability fit, not just the top score. + + + Choose Approve with replacement. The original + assignment is cancelled, the new person is placed as a proposed + swap, and the seat stays covered. If the week is published, the new + person is emailed. + + + Choose Approve and release when nobody can take it. + The seat becomes open and the original assignment is cancelled but + kept in history. + + + Choose Decline if the request should not be granted; + the original volunteer stays on the seat. + + + +

+ A pending request does not remove the volunteer. They remain + responsible until you approve something, so the service always has a + named owner. +

+
+ +

Requests from outside the team

+

+ Ministry leaders can submit the public form at{" "} + /request-coverage without an account. Submissions are + rate-limited and appear under Coverage as new requests. Read the brief, + then either Create event (which opens an event with + the requester and ministry attached) or Decline. The + event is where you assign photographers and folders. +

+
+ + +

+ Every service instance has one run sheet: speaker, message title, + stream and slides links, team notes, an ordered cue list, and a pre/post + checklist. Open it from the Home page’s next-serve card or from the + schedule/dashboard links. +

+ + + + Fill in speaker, message title, stream link, slides link, and notes + for the team, then press Save details. + + + Edit a cue’s time, title, or owner inline and press the save icon on + that row. Use the trash icon to remove a cue, or the add row at the + bottom to insert one. + + + Tick checklist items as they are completed. The sheet records who + ticked each item and when. + + + Add checklist items for this service with{" "} + Add pre-service item or{" "} + Add post-service item. Delete custom items you no + longer need. + + + Press Print for a clean booth copy with the app + chrome removed. + + + +

+ A new instance receives five standard cues and a seven-step + pre-service / four-step post-service checklist the first time the + sheet is opened. Deleting rows does not re-seed them, so the team can + shape a sheet without it resetting. +

+
+
+ + +

+ Reminder rules decide when assignment email goes out relative to the + service. They are data, not code: a change here affects the next + publish with no deploy. +

+ + + + Give the rule a short key (for example friday). + + + Set days from the service and the local send time. Use{" "} + -2 for two days before, 0 for the day of. + + + Choose the channels: email, SMS, or both. SMS depends on the + deployment having an SMS transport configured. + + + Press Add rule. Disable a rule instead of deleting + it when you want to pause sends without losing the configuration. + + + +

The notification log

+

+ Every message the app queues lands in the Notifications card, newest + first. Publishing and reminder rules write here; a background + dispatcher drains the queue. +

+ + +

+ Send test email sends a message to the signed-in admin + through the configured transport. Use it before publishing a large + week and after changing Gmail settings. +

+
+ + +

+ Outbound mail is sent through the team’s Gmail account with an app + password, so messages come from a real church address and land in + recipients’ normal inboxes. +

+ + + + Turn on 2-Step Verification for the Google account. + + + Create an app password in the Google Account security settings. + + + Paste the Gmail address and the 16-character app password here and + press Save. The password is encrypted at rest and never returned to + the browser. + + + Send a test email from the Notifications card to confirm delivery. + + + Use Disconnect Gmail only when switching transports; + mail then falls back to Postmark (if configured) or the console + outbox. + + +

+ On Settings, admins also see the From address, the + admin notification inbox, church timezone, and the media archive + destination with a readiness check. Change the From address only to a + mailbox the Gmail account is allowed to send as. +

+ +
+ + +

+ The backup ZIP contains the Postgres database, training and event + uploads, video derivatives, and the mounted NFS media archive, + including original videos. It does not contain the environment file. +

+ + + + Press Download backup and wait for the ZIP to + finish. Large libraries can take a while. + + + Store the ZIP somewhere safe and keep the deployment’s{" "} + NEXTAUTH_SECRET with it — that secret decrypts stored + settings such as the Gmail app password. + + + To restore, choose the ZIP, type RESTORE, and confirm. + This replaces the database, uploads, and archive on this deployment. + + + +

+ Restoring replaces current data; it is not a merge. Database changes + are transactional, so a failed SQL load leaves the database as it + was, but files and the archive are replaced as part of the restore. + Take a fresh backup first if the current state matters. +

+
+
+ + +

+ Announcements and training lessons are authored in the app, so the team + does not need a deploy to publish news or a new how-to. +

+

Announcements

+ + + Open Announcements. Admins and coordinators see the + authoring form; volunteers see published posts only. + + + Write a title and message. Bodies are plain text, never HTML, so + pasted formatting will not run. + + + Keep Published ticked to make it visible, or untick + it to save a draft. + + + Use the row actions to publish/unpublish or delete a post. + + + +

Training lessons

+ + + Open Training. Admins get the New lesson form above + the published lessons. + + + Add a title, one-line summary, and the lesson body. Line breaks are + preserved, so numbered steps stay readable. + + + Set a sort order to control the list position. Lower numbers appear + first. + + + Publish when ready. Drafts are visible only to admins. + + + Attach a PDF, image, or document with the file control on the lesson, + then Upload. Volunteers open attachments from the + lesson; admins can remove them. + + + +

+ The Platform administration guide and the Volunteer guide appear at + the top of Training as web pages with screenshots and as downloadable + PDFs. They are documentation for this deployment, not editable + lessons, so they stay consistent for every admin. +

+
+
+ + +

+ Three exports cover the notice board, the booth, and a spreadsheet. +

+ + +
+ + + +
+ ); +} diff --git a/src/app/(app)/training/guides/user/page.tsx b/src/app/(app)/training/guides/user/page.tsx new file mode 100644 index 0000000..dda6951 --- /dev/null +++ b/src/app/(app)/training/guides/user/page.tsx @@ -0,0 +1,591 @@ +import type { Metadata } from "next"; +import { + GuideCallout, + GuideFields, + GuideFigure, + GuideSection, + GuideShell, + GuideStep, + GuideSteps, +} from "@/components/app/training/guide"; + +export const metadata: Metadata = { + title: "Volunteer guide", +}; + +const SECTIONS = [ + { id: "sign-in", title: "Signing in" }, + { id: "home", title: "Your home page" }, + { id: "schedule", title: "Reading the schedule" }, + { id: "availability", title: "Telling us when you are away" }, + { id: "coverage", title: "Swaps and coverage" }, + { id: "run-sheet", title: "The run sheet and checklist" }, + { id: "events", title: "Events and photo folders" }, + { id: "media", title: "The media library" }, + { id: "training", title: "Training" }, + { id: "announcements", title: "Announcements" }, + { id: "profile", title: "Your profile and reminders" }, + { id: "settings", title: "Settings and password" }, + { id: "roster", title: "The roster" }, + { id: "help", title: "When you need help" }, +]; + +export default function VolunteerGuidePage() { + return ( + + +

+ The hub is private to the media team. There is no public sign-up form + inside the app; a coordinator adds you, and you receive a one-time + sign-in link by email. +

+ + + + Open the site and go to Sign in. Your username is + your email address unless an admin told you otherwise. + + + Enter your password. If you do not have one yet, use the email-link + option: type your email and the app sends a one-time sign-in link. + + + The first time you follow a link, the app asks you to choose a + username and password. Use at least eight characters and keep it + somewhere safe. + + + After that, you land on Schedule. Use the same + account on your phone; there is no separate app to install. + + + +

+ Magic links work once and expire after ten minutes. If yours has + expired, request a new one. Never forward a sign-in link to someone + else. +

+
+
+ + +

+ Home answers three questions: when am I serving next, what do I need to + respond to, and what else is coming up. +

+ + + + + Press Confirm as soon as you know you can serve. The + coordinator sees the confirmation immediately. + + + Press Can’t make it if you cannot serve. Tell a + coordinator as well if the service is close; a declined seat needs a + replacement. + + + Use Availability and My profile at + the top for the two things volunteers change most often. + + + +
+ + +

+ The schedule has three lenses. Week is the detailed view; month and + year are overviews for planning. +

+ + + + Open Schedule. Use the arrows beside the week to + move one week at a time. + + + Read across the row for your service: each position column shows who + is assigned and whether they have confirmed. + + + The call time is earlier than the service start. Arrive at the call + time on your next-serve card, not at the service time. + + + Switch to Month to see every service in a month, or{" "} + Year to see how much of the year is built and + published. + + + + +

+ A week that has not been published does not appear on your schedule + and does not generate assignment email. If you expected a date and + cannot see it, the week is probably still a draft. +

+
+
+ + +

+ Availability is the most useful thing you can keep current. It feeds + the ranked candidate list, so blocking a date keeps you from being + suggested while you are away. +

+ + + + Open Availability from Home or the navigation. + + + Choose a type: vacation, away, recurring commitment, or preference. + The type is a label for coordinators, not a different calculation. + + + Pick the first and last unavailable date. A single day uses the same + date twice. + + + Choose a repeat pattern if the commitment is regular: every week, + every other week, every four weeks, the 1st and 3rd of the month, or + the last of the month. The pattern is anchored to the weekday of the + start date. + + + Add a short note (“work travel”, “school term”) and press{" "} + Add unavailable dates. + + +

+ Active ranges appear on the right with their repeat label. Use{" "} + Edit to change one, or Remove to end + it. Removing a recurring entry stops the whole pattern. +

+ +

+ If you are already scheduled for a date, blocking it afterwards does + not remove you. Use Request coverage on that + assignment and tell a coordinator. +

+
+
+ + +

+ When life changes, request coverage rather than simply not showing up. + The request keeps you on the seat until a coordinator resolves it, so + the team is never left guessing. +

+ + + On Home, find the serve under Your next serve or{" "} + Upcoming serves. + + + Press Request coverage and add a short reason. A + specific reason helps the coordinator find the right replacement. + + + The button changes to a pending state. You are still responsible for + the seat until you hear that the request was resolved. + + + If the service is within 48 hours, also message a coordinator + directly. The app does not page anyone. + + + +

+ They see the request with a ranked list of eligible replacements. + Approving places someone else and cancels your assignment; approving + without a replacement releases the seat; declining leaves you on it. + You will see the change on Home once it is resolved. +

+
+

+ Ministry leaders outside the team can request coverage through the + public form at /request-coverage. If you are asked to + share a link, that is the one to send. +

+ +
+ + +

+ The run sheet is the shared plan for one service: speaker, message, + links, cues, and the pre/post checklist. Open it from the next-serve + card on Home. +

+ + + + Read the speaker, message title, stream and slides links, and the + team notes before the service. + + + Follow the cue list in time order. The owner column says who is + responsible for each cue. + + + Tick pre-service items as you complete them. Tick post-service items + during teardown. The app records who ticked each item and when. + + + Press Print if you want a paper copy for the booth. + + + +

+ The checklist is shared in real time. Two people ticking the same + item is harmless; an unticked item is the signal that something still + needs doing. +

+
+
+ + +

+ Events are photoshoots, weddings, outreach nights, and other coverage + outside the weekly services. You see the events you are assigned to; + coordinators see all of them. +

+ + + + Open Events and choose an event. + + + Read the shot brief, location, time, and assigned team before you + arrive. + + + Open a folder to upload originals or edited files. Use the folder + kind as a guide: RAW/originals, edited exports, or mixed. + + + Download individual files, or use{" "} + Download all on the event to get every photo in one + ZIP. + + + After the event, upload your selects and tell the coordinator the + folder is ready. Archived events remain readable but stop accepting + new uploads. + + + +
+ + +

+ Media collects the event photos and videos you can access in one + ad-free library. It is a convenience view, not a second copy: access + still follows event assignment. +

+ + + +

+ A media link only works for someone with access. Do not post a + private event photo or video publicly; ask a manager to publish an + approved version if the church needs it public. +

+
+
+ + +

+ Training is the team’s how-to library. Lessons are written by admins + and can carry attachments such as PDFs, checklists, or reference + images. +

+ + + + Open Training from the navigation. + + + Read the Volunteer guide once end to end; it covers + every screen in this app. + + + Open an attachment to read or download it. Links open in a new tab so + you do not lose your place. + + + Use the PDF download on either guide for an offline copy you can keep + on your phone. + + + +

+ The run sheet and checklist are the two things new volunteers most + often ask about. Reading that section once saves a lot of questions + on a Sunday morning. +

+
+
+ + +

+ Announcements carry team news: schedule changes, gear notes, training + dates, and reminders. Everyone signed in can read published posts; + coordinators and admins can write them. +

+ +

+ Posts are plain text, so links are shown as text rather than clickable + formatting. If a post raises a question, reply through your normal team + channel. +

+
+ + +

+ Your profile is where the team gets your contact details and where you + control how the app talks to you. +

+ + + + + Open My profile from Home or Settings. + + + Edit contact details and press Save profile. + + + Adjust reminder preferences and press{" "} + Save preferences. + + + Move the comfort sliders and press Save comfort ratings{" "} + when you have changed several. + + + Press Copy calendar link and add it as a subscribed + calendar in your calendar app. Press Reset link only + if the old link needs to stop working. + + +
+ + +

+ Settings holds your account credentials and the church facts the app + uses for scheduling and messages. +

+ + + + Open Settings. + + + Change your username if the email-as-username default does not suit + you. It must stay unique. + + + Enter a new password twice and save. Use at least eight characters. + + + If you have forgotten the current password, sign out and use the + email-link option on the sign-in page instead. + + + +

+ The church schedules in its own timezone. Your profile timezone + controls how times appear to you, so keep it correct when you travel + or move. +

+
+
+ + +

+ The roster lists active team members with their role and email, so you + can put a name to a seat and reach the right person. +

+ +

+ Trainees do not see the roster. If you need a contact and cannot see + one, ask a coordinator. +

+
+ + + +

+ The team’s rule is simple: communicate early. A covered seat and a + clear run sheet are worth far more than a perfect attendance record + nobody knew about. +

+
+
+ ); +} diff --git a/src/app/(app)/training/page.tsx b/src/app/(app)/training/page.tsx index 9603842..b08fdd1 100644 --- a/src/app/(app)/training/page.tsx +++ b/src/app/(app)/training/page.tsx @@ -1,16 +1,101 @@ -import { StateMessage } from "@/components/app/state-message"; +import Link from "next/link"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listLessons } from "@/db/training"; +import { TrainingPanel } from "@/components/app/training-panel"; +import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react"; export const metadata = { title: "Training" }; -export default function TrainingPage() { +/** + * Training content. Volunteers see published lessons and attachments; admins + * can author, publish, upload, and delete. Content is stored in Postgres and + * attachments under the uploads volume, so it is editable with no deploy. + */ +export default async function TrainingPage() { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole; + const canEdit = hasPermission(role, "training.author"); + const lessons = await listLessons({ includeUnpublished: canEdit }); + return ( - <> -

Training

-

How-tos and tutorials, with progress tied to your roles.

- - +
+
+

Training

+

+ How-tos and checklists for serving on the media team. +

+
+
+
+

+ Full guides +

+

+ Complete, illustrated walkthroughs with screenshots. Read them here + or download the PDF for printing and offline use. +

+
+
+
+
+
+

+ Platform administration guide +

+

+ People and access, skill verification, positions, services and + publishing, coverage, run sheets, email, notifications, backups, + and exports. +

+
+ +
+
+ +
+
+
+

Volunteer guide

+

+ Signing in, your next serve, the schedule, availability, swaps, + run sheets, events and media, training, profile, and reminders. +

+
+ +
+
+
+
+ + +
); } diff --git a/src/app/api/account/calendar-feed/route.ts b/src/app/api/account/calendar-feed/route.ts new file mode 100644 index 0000000..703dc7e --- /dev/null +++ b/src/app/api/account/calendar-feed/route.ts @@ -0,0 +1,20 @@ +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { rotateCalendarFeedToken } from "@/db/volunteer"; +import { requestOrigin } from "@/auth/magic-link"; +import { jsonResponse, errorResponse } from "@/lib/http"; + +const bodySchema = z.object({ action: z.literal("rotate") }); + +/** POST /api/account/calendar-feed { action: "rotate" } */ +export async function POST(req: Request) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const parsed = bodySchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) return errorResponse(400, "invalid action"); + + const token = await rotateCalendarFeedToken(gate.id); + const origin = requestOrigin(req as Request & { headers: Headers }); + return jsonResponse({ token, url: `${origin}/api/calendar/${token}` }); +} diff --git a/src/app/api/account/password/route.ts b/src/app/api/account/password/route.ts new file mode 100644 index 0000000..1c63f9e --- /dev/null +++ b/src/app/api/account/password/route.ts @@ -0,0 +1,95 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { + hashPassword, + normalizeUsername, + validatePassword, + validateUsername, + verifyPassword, +} from "@/auth/password"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + credentialTaken, + getUserSecurity, + updateUserCredentials, +} from "@/db/users"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (payload: unknown, status = 200) => + new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS }); +const bad = (message: string) => json({ error: message }, 400); +const conflict = (message: string) => json({ error: message }, 409); + +const bodySchema = z.object({ + username: z.string().min(1).max(100).optional(), + currentPassword: z.string().max(200).optional(), + newPassword: z.string().min(1).max(200), +}); + +/** + * Set or change the signed-in person's password. + * + * A magic-link session is enough for the first-time setup, where no password + * exists yet. Once one exists, the current password is required so a borrowed + * browser session cannot silently lock the owner out. + */ +export const POST = async (req: NextRequest) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + let body: unknown; + try { + body = await req.json(); + } catch { + return bad("A JSON body is required."); + } + const parsed = bodySchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + + const account = await getUserSecurity(gate.id); + if (!account) return json({ error: "unknown user" }, 404); + + if (account.passwordHash) { + if (!parsed.data.currentPassword) { + return bad("Enter your current password."); + } + if (!(await verifyPassword(parsed.data.currentPassword, account.passwordHash))) { + return bad("Your current password is incorrect."); + } + } + + const passwordError = validatePassword(parsed.data.newPassword); + if (passwordError) return bad(passwordError); + + const nextUsername = parsed.data.username + ? normalizeUsername(parsed.data.username) + : account.username; + if (parsed.data.username) { + const usernameError = validateUsername(nextUsername); + if (usernameError) return bad(usernameError); + if (await credentialTaken(nextUsername, gate.id)) { + return conflict("That username is already in use."); + } + } + + const passwordHash = await hashPassword(parsed.data.newPassword); + const updated = await updateUserCredentials(gate.id, { + username: nextUsername, + passwordHash, + }); + if (!updated) return json({ error: "unknown user" }, 404); + + await writeAudit(db, { + actorId: gate.id, + action: account.passwordHash + ? "user.password_changed" + : "user.password_set", + entityType: "user", + entityId: gate.id, + after: { username: updated.username, passwordSet: true }, + }); + + return json({ ok: true, username: updated.username, passwordSet: true }); +}; diff --git a/src/app/api/announcements/route.ts b/src/app/api/announcements/route.ts new file mode 100644 index 0000000..8b45343 --- /dev/null +++ b/src/app/api/announcements/route.ts @@ -0,0 +1,90 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser, gateSession } from "@/auth/api"; +import { hasPermission } from "@/auth/permissions"; +import { + createAnnouncement, + deleteAnnouncement, + listAnnouncements, + updateAnnouncement, +} from "@/db/announcements"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const createSchema = z.object({ + title: z.string().trim().min(1).max(200), + body: z.string().max(20_000).optional(), + published: z.boolean().optional(), +}); + +const patchSchema = z.object({ + id: z.string().min(1), + title: z.string().trim().min(1).max(200).optional(), + body: z.string().max(20_000).optional(), + published: z.boolean().optional(), +}); + +/** + * Announcements. Any signed-in user reads published posts; authors + * (`content.author` = admin/coordinator) also see drafts and can write. + * + * GET -> { announcements } + * POST -> { announcement } + * PATCH -> { announcement } edit or publish/unpublish + * DELETE ?id= -> { ok } + */ +export const GET = async () => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const canAuthor = hasPermission(gate.systemRole, "content.author"); + return jsonResponse({ + announcements: await listAnnouncements({ + includeUnpublished: canAuthor, + }), + }); +}; + +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("content.author"); + if (gate instanceof Response) return gate; + + const parsed = createSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post"); + } + + const announcement = await createAnnouncement({ + title: parsed.data.title, + body: parsed.data.body ?? "", + published: parsed.data.published ?? false, + createdBy: gate.id, + }); + return jsonResponse({ announcement }, 201); +}; + +export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("content.author"); + if (gate instanceof Response) return gate; + + const parsed = patchSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post"); + } + + const { id, ...patch } = parsed.data; + const announcement = await updateAnnouncement(id, patch); + if (!announcement) return errorResponse(404, "unknown announcement"); + return jsonResponse({ announcement }); +}; + +export const DELETE = async (req: NextRequest) => { + const gate = await gateOrUser("content.author"); + if (gate instanceof Response) return gate; + + const id = req.nextUrl.searchParams.get("id"); + if (!id) return errorResponse(400, "an id is required"); + + const deleted = await deleteAnnouncement(id); + if (!deleted) return errorResponse(404, "unknown announcement"); + return jsonResponse({ ok: true }); +}; diff --git a/src/app/api/assignments/[id]/respond/route.ts b/src/app/api/assignments/[id]/respond/route.ts new file mode 100644 index 0000000..e0d0b9f --- /dev/null +++ b/src/app/api/assignments/[id]/respond/route.ts @@ -0,0 +1,47 @@ +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { RespondError, respondToAssignment } from "@/db/respond"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) }); + +function errorStatus(code: RespondError["code"]): number { + switch (code) { + case "unknown_assignment": + return 404; + case "wrong_volunteer": + return 403; + case "not_actionable": + case "already_used": + return 409; + } +} + +/** POST /api/assignments/:id/respond { action: "confirm" | "decline" } */ +export async function POST( + req: Request, + { params }: { params: Promise<{ id: string }> }, +) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const parsed = bodySchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) return errorResponse(400, "invalid action"); + + const { id } = await params; + try { + const result = await respondToAssignment({ + assignmentId: id, + userId: gate.id, + action: parsed.data.action, + via: "app", + }); + return jsonResponse({ ok: true, ...result }); + } catch (error) { + if (error instanceof RespondError) { + return errorResponse(errorStatus(error.code), error.message, error.code); + } + console.error("[assignment-respond] ERROR", error); + return errorResponse(500, "failed to update the assignment"); + } +} diff --git a/src/app/api/assignments/candidates/route.ts b/src/app/api/assignments/candidates/route.ts new file mode 100644 index 0000000..4209277 --- /dev/null +++ b/src/app/api/assignments/candidates/route.ts @@ -0,0 +1,16 @@ +import { gateOrUser } from "@/auth/api"; +import { rankedCandidatesForSlot } from "@/db/rankedCandidates"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +/** GET /api/assignments/candidates?slotId=... — ranked eligible/excluded list. */ +export async function GET(req: Request) { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const slotId = new URL(req.url).searchParams.get("slotId")?.trim(); + if (!slotId) return errorResponse(400, "a slotId is required"); + + const result = await rankedCandidatesForSlot(slotId); + if (!result) return errorResponse(404, "slot not found"); + return jsonResponse(result); +} diff --git a/src/app/api/assignments/route.ts b/src/app/api/assignments/route.ts index d4f6bb8..82ea2d3 100644 --- a/src/app/api/assignments/route.ts +++ b/src/app/api/assignments/route.ts @@ -1,14 +1,25 @@ import { NextRequest } from "next/server"; import { z } from "zod"; -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import { auth } from "@/auth/config"; import { AuthError, requirePermission } from "@/auth/permissions"; import type { SystemRole } from "@/auth/roles"; import { db } from "@/db"; -import { assignments, slots } from "@/db/schema"; -import { writeAudit } from "@/db/audit"; -import { activeAssignmentInInstance } from "@/db/assignments"; -import { assignHardConflicts } from "@/domain/assign"; +import { + assignments, + auditLog, + serviceInstances, + slots, +} from "@/db/schema"; +import { auditRow } from "@/db/audit"; +import { + AssignFactError, + resolveAssignFacts, +} from "@/db/assignments"; +import { cancelAssignmentNotifications } from "@/db/outbox"; +import { enqueuePublishNotifications } from "@/db/outbox"; +import { enqueueRemindersForInstance } from "@/db/reminders"; +import { classifyConflicts, hardConflicts } from "@/domain/conflicts"; import { uuidv7 } from "@/lib/uuid"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -19,6 +30,8 @@ const bodySchema = z.object({ userId: z.string().min(1).optional(), }); +const ACTIVE_STATUSES = ["proposed", "confirmed", "completed"] as const; + /** Walk an error's cause chain to its SQLSTATE (23505 = unique, 23503 = FK). */ function sqlStateCode(err: unknown): string | undefined { let node = err as { code?: string; cause?: unknown } | null; @@ -30,18 +43,21 @@ function sqlStateCode(err: unknown): string | undefined { } /** - * Assign / clear an assignment (unit D8). + * Assign / clear an assignment (units D8 + D5/D9 integration). * * POST { action: "assign"|"clear", slotId, userId? } * - * - assign -> creates a `proposed`/`manual` assignment after the rule-1 - * duplicate-in-instance gate; writes an `assignment.created` - * audit row. - * - clear -> deletes the active assignment on the slot; writes an - * `assignment.cleared` audit row. + * - assign -> runs the full conflict engine (roster, one-per-instance, + * core-skill level, shadow pairing, blackout, cap, back-to-back) + * and rejects on any HARD conflict. Soft conflicts are returned + * as warnings. Creates `proposed`/`manual`, syncs the slot + * status, audits, and re-enqueues mail when the week is already + * published. + * - clear -> cancels that assignment's pending mail BEFORE deleting it (so + * a removed seat cannot still send "you're serving"), reopens the + * slot, audits. * - * Guarded by `schedule.publish` (coordinator + admin). Hard conflicts reject - * 409; a DB unique violation on the slot rejects 409 (rule 2). + * Guarded by `schedule.publish` (coordinator + admin). */ export const POST = async (req: NextRequest) => { let action: string | undefined; @@ -70,7 +86,10 @@ export const POST = async (req: NextRequest) => { try { const session = await auth(); - const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined); + const user = session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; if (!user) { return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), { status: 401, @@ -81,32 +100,45 @@ export const POST = async (req: NextRequest) => { const actorId = user.id; if (parsed.data.action === "clear") { - const active = await db - .select({ id: assignments.id }) + const [active] = await db + .select({ + id: assignments.id, + slotId: assignments.slotId, + }) .from(assignments) .where( and( eq(assignments.slotId, parsed.data.slotId), - sql`${assignments.status} IN ('proposed','confirmed','completed')`, + inArray(assignments.status, [...ACTIVE_STATUSES]), ), ) .limit(1); - if (active.length === 0) { + if (!active) { return new Response(JSON.stringify({ error: "no active assignment on this slot" }), { status: 404, headers: JSON_HEADERS, }); } - await db.delete(assignments).where(eq(assignments.id, active[0].id)); - await writeAudit(db, { - actorId, - action: "assignment.cleared", - entityType: "assignment", - entityId: active[0].id, - after: { slotId: parsed.data.slotId }, + await db.transaction(async (tx) => { + await cancelAssignmentNotifications(active.id, new Date(), tx); + await tx.delete(assignments).where(eq(assignments.id, active.id)); + await tx + .update(slots) + .set({ status: "open" }) + .where(eq(slots.id, active.slotId)); + await tx.insert(auditLog).values( + auditRow({ + actorId, + action: "assignment.cleared", + entityType: "assignment", + entityId: active.id, + after: { slotId: parsed.data.slotId }, + }), + ); }); + return new Response(JSON.stringify({ ok: true }), { status: 200, headers: JSON_HEADERS, @@ -114,70 +146,102 @@ export const POST = async (req: NextRequest) => { } // assign - if (!parsed.data.userId) { + const assignUserId = parsed.data.userId; + if (!assignUserId) { return new Response(JSON.stringify({ error: "a userId is required to assign" }), { status: 400, headers: JSON_HEADERS, }); } - const slotRows = await db - .select({ id: slots.id, serviceInstanceId: slots.serviceInstanceId }) + let facts; + try { + facts = await resolveAssignFacts({ + userId: assignUserId, + slotId: parsed.data.slotId, + }); + } catch (e) { + if (e instanceof AssignFactError) { + const status = e.code === "unknown_slot" || e.code === "unknown_user" ? 404 : 400; + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status, + headers: JSON_HEADERS, + }); + } + throw e; + } + + const conflicts = classifyConflicts(facts); + const hard = hardConflicts(conflicts); + if (hard.length > 0) { + return new Response( + JSON.stringify({ + error: hard.map((conflict) => conflict.message).join(" "), + code: hard[0].code, + conflicts: hard, + }), + { status: 409, headers: JSON_HEADERS }, + ); + } + + const [instance] = await db + .select({ + id: serviceInstances.id, + status: serviceInstances.status, + }) .from(slots) + .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId)) .where(eq(slots.id, parsed.data.slotId)) .limit(1); - if (slotRows.length === 0) { - return new Response(JSON.stringify({ error: "unknown slot" }), { - status: 404, - headers: JSON_HEADERS, - }); - } - const instanceId = slotRows[0].serviceInstanceId; - if (!instanceId) { - return new Response(JSON.stringify({ error: "slot is not attached to a service instance" }), { - status: 400, - headers: JSON_HEADERS, - }); - } - const existing = await activeAssignmentInInstance(db, { - userId: parsed.data.userId, - instanceId, - }); - const conflicts = assignHardConflicts({ alreadyAssignedInInstance: existing != null }); - if (conflicts.length > 0) { - return new Response(JSON.stringify({ error: conflicts[0].message, code: conflicts[0].code }), { - status: 409, - headers: JSON_HEADERS, - }); - } - - const result = await db - .insert(assignments) - .values({ - id: uuidv7(), + const assignmentId = uuidv7(); + await db.transaction(async (tx) => { + await tx.insert(assignments).values({ + id: assignmentId, slotId: parsed.data.slotId, - userId: parsed.data.userId, + userId: assignUserId, status: "proposed", source: "manual", assignedBy: actorId, assignedAt: new Date(), - }) - .returning({ id: assignments.id, status: assignments.status }); + }); + await tx + .update(slots) + .set({ status: "proposed" }) + .where(eq(slots.id, parsed.data.slotId)); + await tx.insert(auditLog).values( + auditRow({ + actorId, + action: "assignment.created", + entityType: "assignment", + entityId: assignmentId, + before: { slotId: parsed.data.slotId }, + after: { + slotId: parsed.data.slotId, + userId: assignUserId, + status: "proposed", + }, + }), + ); - await writeAudit(db, { - actorId, - action: "assignment.created", - entityType: "assignment", - entityId: result[0].id, - before: { slotId: parsed.data.slotId }, - after: { slotId: parsed.data.slotId, userId: parsed.data.userId, status: "proposed" }, + // A published week's mail is written at publish time; a seat added later + // would otherwise never be announced. Both enqueues are idempotent on + // dedupe_key, so existing rows are untouched. + if (instance?.status === "published") { + await enqueuePublishNotifications(tx, instance.id, { now: new Date() }); + await enqueueRemindersForInstance(tx, instance.id, { now: new Date() }); + } }); - return new Response(JSON.stringify({ ok: true, id: result[0].id, status: result[0].status }), { - status: 201, - headers: JSON_HEADERS, - }); + return new Response( + JSON.stringify({ + ok: true, + id: assignmentId, + status: "proposed", + warnings: conflicts.filter((conflict) => conflict.severity === "soft"), + }), + { status: 201, headers: JSON_HEADERS }, + ); } catch (e) { if (e instanceof AuthError) { return new Response(JSON.stringify({ error: e.message, code: e.code }), { @@ -191,6 +255,7 @@ export const POST = async (req: NextRequest) => { headers: JSON_HEADERS, }); } + console.error("[assignments] ERROR", e); return new Response(JSON.stringify({ error: "failed to assign" }), { status: 500, headers: JSON_HEADERS, diff --git a/src/app/api/auth/reset-password/route.ts b/src/app/api/auth/reset-password/route.ts new file mode 100644 index 0000000..e26ae66 --- /dev/null +++ b/src/app/api/auth/reset-password/route.ts @@ -0,0 +1,68 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { + consumeMagicToken, + getUser, + verifyPasswordResetToken, +} from "@/auth/magic-link"; +import { hashPassword, validatePassword } from "@/auth/password"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { updateUserCredentials } from "@/db/users"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (payload: unknown, status = 200) => + new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS }); + +const bodySchema = z.object({ + token: z.string().min(1), + newPassword: z.string().min(1).max(200), +}); + +/** + * Complete an admin-issued password reset. The token is single-use and is + * consumed before the new hash is written, so replaying the same link cannot + * reset the account twice. + */ +export const POST = async (req: NextRequest) => { + let body: unknown; + try { + body = await req.json(); + } catch { + return json({ error: "A JSON body is required." }, 400); + } + const parsed = bodySchema.safeParse(body); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + const passwordError = validatePassword(parsed.data.newPassword); + if (passwordError) return json({ error: passwordError }, 400); + + const payload = await verifyPasswordResetToken(parsed.data.token); + if (!payload) { + return json({ error: "This reset link is invalid or has expired." }, 400); + } + + const user = await getUser(payload.email); + if (!user || user.status !== "active" || user.deactivatedAt) { + return json({ error: "This account cannot reset its password." }, 400); + } + + const consumed = await consumeMagicToken(payload); + if (!consumed) { + return json({ error: "This reset link has already been used." }, 409); + } + + const passwordHash = await hashPassword(parsed.data.newPassword); + const updated = await updateUserCredentials(user.id, { passwordHash }); + if (!updated) return json({ error: "unknown user" }, 404); + + await writeAudit(db, { + actorId: user.id, + action: "user.password_reset", + entityType: "user", + entityId: user.id, + after: { passwordSet: true }, + }); + + return json({ ok: true }); +}; diff --git a/src/app/api/calendar/[token]/route.ts b/src/app/api/calendar/[token]/route.ts new file mode 100644 index 0000000..87320e7 --- /dev/null +++ b/src/app/api/calendar/[token]/route.ts @@ -0,0 +1,39 @@ +import { + calendarFeedForUser, + getCalendarFeedOwner, +} from "@/db/volunteer"; +import { buildCalendar } from "@/lib/ics"; + +export const dynamic = "force-dynamic"; + +/** + * Public, bearer-by-URL calendar feed. The token is long and random; it is not + * an account session and grants read-only access to that person's assignments. + */ +export async function GET( + _req: Request, + { params }: { params: Promise<{ token: string }> }, +) { + const { token } = await params; + if (!token || token.length < 20 || token.length > 128) { + return new Response("Calendar not found", { status: 404 }); + } + + const owner = await getCalendarFeedOwner(token); + if (!owner) return new Response("Calendar not found", { status: 404 }); + + const events = await calendarFeedForUser(owner.id); + const body = buildCalendar({ + calendarName: `${owner.displayName} — Media Team`, + events, + }); + + return new Response(body, { + status: 200, + headers: { + "content-type": "text/calendar; charset=utf-8", + "content-disposition": 'inline; filename="media-team.ics"', + "cache-control": "private, no-store, max-age=0", + }, + }); +} diff --git a/src/app/api/coverage-intake/route.ts b/src/app/api/coverage-intake/route.ts new file mode 100644 index 0000000..069f39a --- /dev/null +++ b/src/app/api/coverage-intake/route.ts @@ -0,0 +1,100 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { clientIp, gateOrUser } from "@/auth/api"; +import { rateLimit } from "@/lib/rate-limit"; +import { + IntakeError, + createCoverageIntake, + declineCoverageIntake, + scheduleCoverageIntake, +} from "@/db/intake"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: JSON_HEADERS }); + +const intakeSchema = z.object({ + requesterName: z.string().min(2).max(120), + requesterEmail: z.string().email().max(200), + requesterPhone: z.string().max(40).nullable().optional(), + ministry: z.string().max(120).nullable().optional(), + title: z.string().min(3).max(200), + eventType: z.string().max(60).optional(), + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + startTime: z.string().regex(/^\d{2}:\d{2}$/), + endTime: z.string().regex(/^\d{2}:\d{2}$/).nullable().optional(), + location: z.string().max(200).nullable().optional(), + description: z.string().max(2000).nullable().optional(), +}); + +const reviewSchema = z.object({ + id: z.string().min(1), + action: z.enum(["schedule", "decline"]), +}); + +async function body(req: NextRequest): Promise { + try { + return await req.json(); + } catch { + return null; + } +} + +/** + * Public submission endpoint. Rate-limited per IP; the response never reveals + * whether an identical request already exists. + */ +export const POST = async (req: NextRequest) => { + const limit = rateLimit(`coverage-intake:${clientIp(req)}`, 5, 60 * 60 * 1000); + if (!limit.ok) { + return new Response( + JSON.stringify({ error: "Too many requests. Please try again later." }), + { + status: 429, + headers: { + ...JSON_HEADERS, + "retry-after": String(limit.retryAfterSeconds), + }, + }, + ); + } + + const parsed = intakeSchema.safeParse(await body(req)); + if (!parsed.success) { + return json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, 400); + } + + try { + await createCoverageIntake(parsed.data); + return json({ ok: true }, 201); + } catch (err) { + if (err instanceof IntakeError) return json({ error: err.message }, err.status); + console.error("[coverage-intake] submit failed", err); + return json({ error: "Could not submit the request." }, 500); + } +}; + +/** Coordinator review: turn an accepted request into an event, or decline it. */ +export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const parsed = reviewSchema.safeParse(await body(req)); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + try { + if (parsed.data.action === "schedule") { + const row = await scheduleCoverageIntake({ + id: parsed.data.id, + actorId: gate.id, + }); + return json({ ok: true, ...row }); + } + await declineCoverageIntake({ id: parsed.data.id, actorId: gate.id }); + return json({ ok: true }); + } catch (err) { + if (err instanceof IntakeError) return json({ error: err.message }, err.status); + console.error("[coverage-intake] review failed", err); + return json({ error: "Could not review the request." }, 500); + } +}; diff --git a/src/app/api/coverage/route.ts b/src/app/api/coverage/route.ts new file mode 100644 index 0000000..4bcc9f4 --- /dev/null +++ b/src/app/api/coverage/route.ts @@ -0,0 +1,81 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser, gateSession } from "@/auth/api"; +import { + CoverageError, + createCoverageRequest, + resolveCoverageRequest, +} from "@/db/coverage"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: JSON_HEADERS }); + +const createSchema = z.object({ + assignmentId: z.string().min(1), + reason: z.string().max(500).nullable().optional(), +}); + +const resolveSchema = z.object({ + id: z.string().min(1), + action: z.enum(["approve", "decline", "cancel"]), + replacementUserId: z.string().min(1).nullable().optional(), +}); + +async function body(req: NextRequest): Promise { + try { + return await req.json(); + } catch { + return null; + } +} + +/** A volunteer asks for coverage on their own assignment. */ +export const POST = async (req: NextRequest) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const parsed = createSchema.safeParse(await body(req)); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + try { + const row = await createCoverageRequest({ + assignmentId: parsed.data.assignmentId, + userId: gate.id, + reason: parsed.data.reason ?? null, + }); + return json({ ok: true, ...row }, 201); + } catch (err) { + if (err instanceof CoverageError) { + return json({ error: err.message }, err.status); + } + console.error("[coverage] create failed", err); + return json({ error: "could not create the coverage request" }, 500); + } +}; + +/** A coordinator approves (with or without a replacement) or declines. */ +export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const parsed = resolveSchema.safeParse(await body(req)); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + try { + const result = await resolveCoverageRequest({ + requestId: parsed.data.id, + actorId: gate.id, + action: parsed.data.action, + replacementUserId: parsed.data.replacementUserId ?? null, + }); + return json({ ok: true, ...result }); + } catch (err) { + if (err instanceof CoverageError) { + return json({ error: err.message }, err.status); + } + console.error("[coverage] resolve failed", err); + return json({ error: "could not update the coverage request" }, 500); + } +}; diff --git a/src/app/api/dev/approve/route.ts b/src/app/api/dev/approve/route.ts index f518451..d490139 100644 --- a/src/app/api/dev/approve/route.ts +++ b/src/app/api/dev/approve/route.ts @@ -1,6 +1,10 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; import { approveUser } from "@/auth/invites"; +import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link"; +import { getUserById } from "@/db/users"; +import { sendWelcomeEmail } from "@/lib/welcome-email"; const JSON_HEADERS = { "content-type": "application/json" }; const bodySchema = z.object({ @@ -12,6 +16,9 @@ const bodySchema = z.object({ * Approve a pending user -> active. POST { userId, approvedBy? }. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + let userId: string | undefined; let approvedBy: string | undefined; try { @@ -33,12 +40,26 @@ export const POST = async (req: NextRequest) => { try { const user = await approveUser({ userId: parsed.data.userId, - approvedBy: parsed.data.approvedBy ?? "admin", - }); - return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), { - status: 200, - headers: JSON_HEADERS, + // Server-owned: a caller cannot attribute the approval to someone else. + approvedBy: gate.id, }); + + // The account can now sign in, so this is the moment to send its details. + const approved = await getUserById(user.id); + let welcome: { delivered: boolean; transport: string | null } | null = null; + if (approved) { + const token = await signMagicToken(approved.email); + const origin = requestOrigin(req) || APP_ORIGIN; + const url = `${origin}/api/dev/complete?token=${encodeURIComponent( + token, + )}&email=${encodeURIComponent(approved.email)}`; + welcome = await sendWelcomeEmail(approved, url); + } + + return new Response( + JSON.stringify({ ok: true, id: user.id, status: user.status, welcome }), + { status: 200, headers: JSON_HEADERS }, + ); } catch { return new Response(JSON.stringify({ error: "failed to approve user" }), { status: 500, diff --git a/src/app/api/dev/backup/restore/route.ts b/src/app/api/dev/backup/restore/route.ts new file mode 100644 index 0000000..b9dab59 --- /dev/null +++ b/src/app/api/dev/backup/restore/route.ts @@ -0,0 +1,193 @@ +import { NextRequest } from "next/server"; +import { constants } from "node:fs"; +import { + access, + mkdir, + mkdtemp, + readFile, + rm, + stat, +} from "node:fs/promises"; +import path from "node:path"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { getStorageSettings } from "@/db/storage-settings"; +import { + BACKUP_DATABASE_FILE, + BACKUP_MANIFEST_FILE, + assertRegularFile, + type BackupManifest, + backupManifestSchema, + backupTempRoot, + extractZip, + listZipEntries, + replaceDirectoryContents, + restoreDatabaseFromFile, + sha256File, + validateBackupEntries, + writeRequestBodyToFile, +} from "@/lib/backup"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { UPLOAD_DIR } from "@/lib/uploads"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * POST /api/dev/backup/restore + * + * Body: the backup ZIP bytes. Header: `x-restore-confirm: RESTORE`. + * + * The ZIP is validated before anything is changed. The database is loaded with + * `psql --single-transaction`, so a bad dump rolls back. Uploads and the archive + * are only replaced when the manifest says they were included. The signed-in + * admin should keep the same NEXTAUTH_SECRET if they need to retain encrypted + * settings such as the Gmail app password. + */ +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + if (req.headers.get("x-restore-confirm") !== "RESTORE") { + return errorResponse( + 400, + 'Type "RESTORE" in the confirmation field before restoring.', + ); + } + if (!req.body) return errorResponse(400, "A backup ZIP is required."); + + const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-restore-")); + const zipPath = path.join(temp, "backup.zip"); + const extractDir = path.join(temp, "unpacked"); + let databaseRestored = false; + + try { + await writeRequestBodyToFile(req.body, zipPath); + const zipInfo = await stat(zipPath); + if (!zipInfo.isFile() || zipInfo.size === 0) { + return errorResponse(400, "The uploaded backup is empty."); + } + + const entries = await listZipEntries(zipPath); + const entriesCheck = validateBackupEntries(entries); + if (!entriesCheck.ok) { + return errorResponse(400, entriesCheck.error); + } + + await mkdir(extractDir, { recursive: true }); + await extractZip(zipPath, extractDir); + + const manifestPath = path.join(extractDir, BACKUP_MANIFEST_FILE); + const dumpPath = path.join(extractDir, BACKUP_DATABASE_FILE); + await assertRegularFile(manifestPath); + await assertRegularFile(dumpPath); + + let manifest: BackupManifest; + try { + manifest = backupManifestSchema.parse( + JSON.parse(await readFile(manifestPath, "utf8")), + ); + } catch (error) { + const detail = + error instanceof z.ZodError + ? error.issues[0]?.message ?? "invalid manifest" + : error instanceof Error + ? error.message + : "invalid manifest"; + return errorResponse(400, `Invalid backup manifest: ${detail}`); + } + + const dumpInfo = await stat(dumpPath); + if (dumpInfo.size !== manifest.database.bytes) { + return errorResponse( + 400, + "The database dump size does not match the backup manifest.", + ); + } + const checksum = await sha256File(dumpPath); + if (checksum !== manifest.database.sha256) { + return errorResponse( + 400, + "The database dump checksum does not match the backup manifest.", + ); + } + + // Resolve the current archive destination before the database is replaced; + // the restored app_settings may point at a path that is not mounted here. + const storage = await getStorageSettings(); + if (manifest.includes.archive) { + const archiveRoot = path.parse(storage.archivePath).root; + if ( + !path.isAbsolute(storage.archivePath) || + path.resolve(storage.archivePath) === archiveRoot + ) { + return errorResponse( + 400, + "This backup contains an archive, but the current archive path is not safe. Fix it in Settings first.", + ); + } + await mkdir(storage.archivePath, { recursive: true }); + await access(storage.archivePath, constants.W_OK); + } + if (manifest.includes.uploads) { + await mkdir(UPLOAD_DIR, { recursive: true }); + await access(UPLOAD_DIR, constants.W_OK); + } + + await restoreDatabaseFromFile(dumpPath); + databaseRestored = true; + + if (manifest.includes.uploads) { + const source = path.join(extractDir, "uploads"); + await mkdir(source, { recursive: true }); + await replaceDirectoryContents(source, UPLOAD_DIR); + } + if (manifest.includes.archive) { + const source = path.join(extractDir, "archive"); + await mkdir(source, { recursive: true }); + await replaceDirectoryContents(source, storage.archivePath); + } + + try { + await writeAudit(db, { + actorId: gate.id, + action: "backup.restored", + entityType: "backup", + after: { + manifestCreatedAt: manifest.createdAt, + appVersion: manifest.appVersion, + databaseBytes: manifest.database.bytes, + includes: manifest.includes, + }, + }); + } catch (error) { + // The restore already succeeded; do not turn an audit failure into one. + console.error("backup restore: could not write audit row", error); + } + + return jsonResponse({ + ok: true, + restored: { + createdAt: manifest.createdAt, + appVersion: manifest.appVersion, + databaseBytes: manifest.database.bytes, + uploads: manifest.includes.uploads, + archive: manifest.includes.archive, + }, + }); + } catch (error) { + console.error("backup restore failed", error); + const detail = + error instanceof Error ? error.message : "restore could not be completed"; + return errorResponse( + 500, + databaseRestored + ? `The database was restored, but the files could not be replaced: ${detail}` + : detail, + ); + } finally { + await rm(temp, { recursive: true, force: true }).catch(() => undefined); + } +}; diff --git a/src/app/api/dev/backup/route.ts b/src/app/api/dev/backup/route.ts new file mode 100644 index 0000000..1ecf484 --- /dev/null +++ b/src/app/api/dev/backup/route.ts @@ -0,0 +1,143 @@ +import { ZipArchive } from "archiver"; +import { mkdtemp, rm } from "node:fs/promises"; +import { PassThrough, Readable } from "node:stream"; +import path from "node:path"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { getStorageSettings } from "@/db/storage-settings"; +import { + BACKUP_FORMAT, + BACKUP_FORMAT_VERSION, + BACKUP_DATABASE_FILE, + BACKUP_MANIFEST_FILE, + backupFilename, + backupManifestSchema, + backupTempRoot, + directoryExists, + dumpDatabaseToFile, +} from "@/lib/backup"; +import { errorResponse } from "@/lib/http"; +import { UPLOAD_DIR } from "@/lib/uploads"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +/** + * GET /api/dev/backup + * + * Streams one complete ZIP: manifest, full Postgres dump, uploads volume, and + * the mounted photo archive. Admin-only. The dump is written to a private temp + * folder first so the archive can include a checksum of the exact SQL bytes. + */ +export const GET = async () => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-backup-")); + const dumpPath = path.join(temp, BACKUP_DATABASE_FILE); + let keepTemp = true; + + try { + const dump = await dumpDatabaseToFile(dumpPath); + const storage = await getStorageSettings(); + const uploadsIncluded = await directoryExists(UPLOAD_DIR); + const archivePath = storage.archivePath; + const archiveIncluded = + (await directoryExists(archivePath)) && + path.resolve(archivePath) !== path.resolve(UPLOAD_DIR) && + !isInside(path.resolve(UPLOAD_DIR), path.resolve(archivePath)); + + const manifest = backupManifestSchema.parse({ + format: BACKUP_FORMAT, + formatVersion: BACKUP_FORMAT_VERSION, + createdAt: new Date().toISOString(), + appVersion: process.env.npm_package_version ?? "unknown", + database: { + file: BACKUP_DATABASE_FILE, + bytes: dump.bytes, + sha256: dump.sha256, + }, + includes: { + uploads: uploadsIncluded, + archive: archiveIncluded, + }, + }); + + try { + await writeAudit(db, { + actorId: gate.id, + action: "backup.created", + entityType: "backup", + after: { + databaseBytes: dump.bytes, + uploads: uploadsIncluded, + archive: archiveIncluded, + }, + }); + } catch (error) { + // A failed audit row must not stop an otherwise valid backup. + console.error("backup: could not write audit row", error); + } + + const output = new PassThrough(); + const archive = new ZipArchive({ zlib: { level: 6 } }); + const cleanup = () => { + if (!keepTemp) return; + keepTemp = false; + void rm(temp, { recursive: true, force: true }).catch(() => undefined); + }; + + output.on("close", cleanup); + output.on("error", cleanup); + archive.on("warning", (error) => { + console.warn("backup: zip warning", error); + }); + archive.on("error", (error) => { + console.error("backup: zip failed", error); + output.destroy(error); + }); + archive.pipe(output); + + archive.append(JSON.stringify(manifest, null, 2), { + name: BACKUP_MANIFEST_FILE, + }); + archive.file(dumpPath, { name: BACKUP_DATABASE_FILE }); + if (uploadsIncluded) archive.directory(UPLOAD_DIR, "uploads"); + if (archiveIncluded) archive.directory(archivePath, "archive"); + void archive.finalize().catch((error) => output.destroy(error)); + + const filename = backupFilename(); + return new Response( + Readable.toWeb(output) as unknown as ReadableStream, + { + status: 200, + headers: { + "content-type": "application/zip", + "content-disposition": `attachment; filename="${filename}"`, + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }, + }, + ); + } catch (error) { + if (keepTemp) { + keepTemp = false; + await rm(temp, { recursive: true, force: true }).catch(() => undefined); + } + const detail = + error instanceof Error ? error.message : "backup could not be created"; + console.error("backup: creation failed", error); + return errorResponse(500, detail); + } +}; + +function isInside(parent: string, candidate: string): boolean { + const relative = path.relative(parent, candidate); + return ( + relative !== "" && + !relative.startsWith("..") && + !path.isAbsolute(relative) + ); +} + diff --git a/src/app/api/dev/catalog/route.ts b/src/app/api/dev/catalog/route.ts index 691ce82..9464273 100644 --- a/src/app/api/dev/catalog/route.ts +++ b/src/app/api/dev/catalog/route.ts @@ -1,5 +1,6 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; import { listCatalog, deactivateCatalog, @@ -158,6 +159,9 @@ const dbError = (err: unknown) => { /** GET /api/dev/catalog?type=categories&active=true — list pickers rows. */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const type = typeSchema.safeParse(req.nextUrl.searchParams.get("type")); if (!type.success) { return new Response(JSON.stringify({ error: "invalid type" }), { @@ -175,6 +179,9 @@ export const GET = async (req: NextRequest) => { /** POST /api/dev/catalog { type, ...createFields } — create (slug generated). */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") { return new Response(JSON.stringify({ error: "invalid body" }), { @@ -223,6 +230,9 @@ export const POST = async (req: NextRequest) => { * `slug` is never accepted here: it freezes after creation. */ export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") { return new Response(JSON.stringify({ error: "invalid body" }), { diff --git a/src/app/api/dev/complete/route.ts b/src/app/api/dev/complete/route.ts index aaafbe9..2daa9d7 100644 --- a/src/app/api/dev/complete/route.ts +++ b/src/app/api/dev/complete/route.ts @@ -1,36 +1,48 @@ -import { NextRequest } from "next/server"; +import { NextRequest, NextResponse } from "next/server"; import { signIn } from "@/auth/config"; -import { verifyMagicToken } from "@/auth/magic-link"; - -const JSON_HEADERS = { "content-type": "application/json" }; +import { + consumeMagicToken, + getUser, + requestOrigin, + verifyMagicToken, +} from "@/auth/magic-link"; /** * Completes a magic-link sign-in. GET /api/dev/complete?token=... verifies the - * one-time token and establishes the Auth.js session. + * one-time token, establishes the Auth.js session, and redirects into the app. + * + * This is a browser endpoint (the link in the dev console transport / invite + * email is clicked), so it must answer with a redirect rather than JSON: the + * session cookie is set on the redirect response and the follow-up request + * arrives signed in. */ export const GET = async (req: NextRequest) => { - const token = new URL(req.url, "http://localhost").searchParams.get( - "token", - ) ?? undefined; + const origin = requestOrigin(req); + const token = new URL(req.url, origin).searchParams.get("token") ?? undefined; const payload = await verifyMagicToken(token); if (!payload) { - return new Response( - JSON.stringify({ error: "invalid or expired link" }), - { status: 400, headers: JSON_HEADERS }, - ); + // Expired or tampered link: send the person back to sign-in rather than + // dumping an error object in the browser. + return NextResponse.redirect(new URL("/login?error=invalid_link", origin)); + } + + // Single use: the jti is consumed before a session is created, so a link + // forwarded or leaked after first use cannot sign anyone in again. + const consumed = await consumeMagicToken(payload); + if (!consumed) { + return NextResponse.redirect(new URL("/login?error=link_used", origin)); } try { - const result = await signIn("magic-link", { token, redirect: false }); - return new Response(JSON.stringify({ ok: true, url: result.url }), { - status: 200, - headers: JSON_HEADERS, - }); + await signIn("magic-link", { token, redirect: false }); + // The first successful link opens credential setup; returning users go + // straight into the app. + const user = await getUser(payload.email); + return NextResponse.redirect( + new URL(user?.passwordHash ? "/schedule" : "/welcome", origin), + ); } catch (err) { console.error("[complete] signIn failed:", (err as Error).message, (err as Error).stack); - return new Response(JSON.stringify({ error: "failed to sign in" }), { - status: 500, - headers: JSON_HEADERS, - }); + return NextResponse.redirect(new URL("/login", origin)); } -}; \ No newline at end of file +}; diff --git a/src/app/api/dev/cron/complete/route.ts b/src/app/api/dev/cron/complete/route.ts new file mode 100644 index 0000000..8c0d41c --- /dev/null +++ b/src/app/api/dev/cron/complete/route.ts @@ -0,0 +1,34 @@ +import type { NextRequest } from "next/server"; +import { gateCron } from "@/auth/api"; +import { completePastAssignments } from "@/db/complete"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * GET /api/dev/cron/complete — close assignments for services that have ended. + * + * Marks past published assignments `completed` and updates the volunteer's + * `last_served_on` / `last_served_at`, which drive staleness and fairness. + * Idempotent: a second run has nothing left to complete. + * + * Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external + * scheduler, otherwise a session with `schedule.publish`. + */ +export const GET = async (req: NextRequest) => { + const gate = await gateCron(req); + if (gate instanceof Response) return gate; + + try { + const summary = await completePastAssignments(); + return new Response(JSON.stringify(summary), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + const message = e instanceof Error ? e.message : "completion failed"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/cron/instances/route.ts b/src/app/api/dev/cron/instances/route.ts index 0288658..6fe5fb1 100644 --- a/src/app/api/dev/cron/instances/route.ts +++ b/src/app/api/dev/cron/instances/route.ts @@ -1,15 +1,39 @@ +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; import { generateInstances } from "@/db/instances"; +const JSON_HEADERS = { "content-type": "application/json" }; + /** - * 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. + * Instance generator (ARCHITECTURE §5.1). Idempotent — a re-run creates 0 rows. + * Callable from the admin services panel; also safe for an external cron once + * it is given a service credential. Here it is guarded by `schedule.publish`. * * 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" }, - }); + try { + const session = await auth(); + requirePermission( + (session?.user as { systemRole: SystemRole } | null | undefined), + "schedule.publish", + ); + const result = await generateInstances(); + return new Response(JSON.stringify({ result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ error: "failed to generate instances" }), { + status: 500, + headers: JSON_HEADERS, + }); + } }; diff --git a/src/app/api/dev/cron/notifications/route.ts b/src/app/api/dev/cron/notifications/route.ts new file mode 100644 index 0000000..8b0118a --- /dev/null +++ b/src/app/api/dev/cron/notifications/route.ts @@ -0,0 +1,37 @@ +import type { NextRequest } from "next/server"; +import { gateCron } from "@/auth/api"; +import { dispatchDue } from "@/db/dispatcher"; +import { enqueueEventReminders } from "@/db/eventReminders"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * GET /api/dev/cron/notifications — the dispatcher tick (cron every 5 min). + * + * Queues any event reminders that are now inside their lead window, then drains + * due outbox rows through the guards (assignment active, volunteer active, + * channel consent, quiet hours) and the configured transport. Returns what + * happened; running it again with nothing due is a no-op. + * + * Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external + * scheduler, otherwise a session with `schedule.publish`. + */ +export const GET = async (req: NextRequest) => { + const gate = await gateCron(req); + if (gate instanceof Response) return gate; + + try { + const eventRemindersQueued = await enqueueEventReminders(); + const summary = await dispatchDue(); + return new Response(JSON.stringify({ ...summary, eventRemindersQueued }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + const message = e instanceof Error ? e.message : "dispatch failed"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/cron/slots/route.ts b/src/app/api/dev/cron/slots/route.ts index 96caac7..c5f1e8d 100644 --- a/src/app/api/dev/cron/slots/route.ts +++ b/src/app/api/dev/cron/slots/route.ts @@ -1,15 +1,32 @@ +import type { NextRequest } from "next/server"; +import { gateCron } from "@/auth/api"; import { materializeSlots } from "@/db/slots"; +const JSON_HEADERS = { "content-type": "application/json" }; + /** * Slot materialization (ARCHITECTURE §5.2). Drives `materializeSlots()` — * idempotent on (instance, role, seat). Re-runs create 0 rows. * * GET /api/dev/cron/slots + * Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external + * scheduler, otherwise a session with `schedule.publish`. */ -export const GET = async () => { - const result = await materializeSlots(); - return new Response(JSON.stringify({ result }), { - status: 200, - headers: { "content-type": "application/json" }, - }); +export const GET = async (req: NextRequest) => { + const gate = await gateCron(req); + if (gate instanceof Response) return gate; + + try { + const result = await materializeSlots(); + return new Response(JSON.stringify({ result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + const message = e instanceof Error ? e.message : "slot materialization failed"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } }; diff --git a/src/app/api/dev/deny/route.ts b/src/app/api/dev/deny/route.ts index 8ef9dcf..239563b 100644 --- a/src/app/api/dev/deny/route.ts +++ b/src/app/api/dev/deny/route.ts @@ -1,5 +1,6 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; import { denyUser } from "@/auth/invites"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -12,6 +13,9 @@ const bodySchema = z.object({ * Deny a pending user -> denied (cannot sign in). POST { userId, deniedBy? }. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + let userId: string | undefined; let deniedBy: string | undefined; try { @@ -33,7 +37,7 @@ export const POST = async (req: NextRequest) => { try { const user = await denyUser({ userId: parsed.data.userId, - deniedBy: parsed.data.deniedBy ?? "admin", + deniedBy: gate.id, }); return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), { status: 200, diff --git a/src/app/api/dev/invite/route.ts b/src/app/api/dev/invite/route.ts index 9762fb1..a85e190 100644 --- a/src/app/api/dev/invite/route.ts +++ b/src/app/api/dev/invite/route.ts @@ -1,6 +1,8 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; import { inviteUser } from "@/auth/invites"; +import { requestOrigin } from "@/auth/magic-link"; const JSON_HEADERS = { "content-type": "application/json" }; const bodySchema = z.object({ @@ -14,6 +16,9 @@ const bodySchema = z.object({ * signs a magic-link token, and enqueues an invite to the console outbox. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + let email: string | undefined; let invitedBy: string | undefined; try { @@ -35,7 +40,9 @@ export const POST = async (req: NextRequest) => { try { const result = await inviteUser({ email: parsed.data.email, - invitedBy: parsed.data.invitedBy ?? "admin", + // Server-owned: the signed-in admin is the inviter. + invitedBy: gate.id, + appOrigin: requestOrigin(req), }); return new Response(JSON.stringify(result), { status: 200, diff --git a/src/app/api/dev/magic-link/route.ts b/src/app/api/dev/magic-link/route.ts index 52b109b..d856765 100644 --- a/src/app/api/dev/magic-link/route.ts +++ b/src/app/api/dev/magic-link/route.ts @@ -1,6 +1,12 @@ import { NextRequest } from "next/server"; import { z } from "zod"; -import { requestMagicLink } from "@/auth/magic-link"; +import { clientIp } from "@/auth/api"; +import { + MAGIC_LINK_DEV_TRANSPORT, + requestMagicLink, + requestOrigin, +} from "@/auth/magic-link"; +import { rateLimit } from "@/lib/rate-limit"; const JSON_HEADERS = { "content-type": "application/json" }; const bodySchema = z.object({ email: z.string().email() }); @@ -28,8 +34,35 @@ export const POST = async (req: NextRequest) => { }); } + // Production: 5 requests per address and 20 per IP per 10 minutes blunts + // link spam and email enumeration. The console transport (local/dev/e2e) is + // deliberately not throttled, since the test harness signs in repeatedly. + const ip = clientIp(req); + const emailKey = parsed.data.email.trim().toLowerCase(); + const byAddress = MAGIC_LINK_DEV_TRANSPORT + ? { ok: true, retryAfterSeconds: 0 } + : rateLimit(`magic:${ip}:${emailKey}`, 5, 10 * 60_000); + const byIp = MAGIC_LINK_DEV_TRANSPORT + ? { ok: true, retryAfterSeconds: 0 } + : rateLimit(`magic-ip:${ip}`, 20, 10 * 60_000); + if (!byAddress.ok || !byIp.ok) { + const retry = Math.max(byAddress.retryAfterSeconds, byIp.retryAfterSeconds); + return new Response( + JSON.stringify({ + error: "too many sign-in requests; try again later", + code: "RATE_LIMITED", + }), + { + status: 429, + headers: { ...JSON_HEADERS, "retry-after": String(retry) }, + }, + ); + } + try { - const result = await requestMagicLink(parsed.data.email); + const result = await requestMagicLink(parsed.data.email, { + origin: requestOrigin(req), + }); return new Response(JSON.stringify(result), { status: 200, headers: JSON_HEADERS, diff --git a/src/app/api/dev/notification-rules/route.ts b/src/app/api/dev/notification-rules/route.ts new file mode 100644 index 0000000..581a297 --- /dev/null +++ b/src/app/api/dev/notification-rules/route.ts @@ -0,0 +1,153 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { createRule, listRules, updateRule } from "@/db/reminders"; +import { NOTIFICATION_RULE_EVENTS } from "@/db/schema"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const createSchema = z.object({ + key: z.string().min(1), + event: z.enum(NOTIFICATION_RULE_EVENTS).optional(), + offsetDays: z.number().int().min(-30).max(30), + sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/), + channelSet: z.enum(["email", "sms", "email+sms"]), + appliesToServiceId: z.string().nullable().optional(), + active: z.boolean().optional(), +}); + +const patchSchema = z.object({ + id: z.string().min(1), + offsetDays: z.number().int().min(-30).max(30).optional(), + sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/).optional(), + channelSet: z.enum(["email", "sms", "email+sms"]).optional(), + appliesToServiceId: z.string().nullable().optional(), + active: z.boolean().optional(), +}); + +async function requireActor() { + const session = await auth(); + const user = session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; + if (!user) { + return new Response( + JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), + { status: 401, headers: JSON_HEADERS }, + ); + } + requirePermission(user, "schedule.publish"); + return user; +} + +/** + * Reminder rules CRUD — unit E7 (ARCHITECTURE §6.2). + * + * GET -> all rules + * POST -> create a rule ({ key, offsetDays, sendAtLocalTime, channelSet }) + * PATCH -> edit a rule (partial) + * + * Guarded by `schedule.publish`. Reminder sends are computed from these rows at + * publish time, so changing an offset changes `scheduled_for` with no deploy. + */ +export const GET = async () => { + try { + const actor = await requireActor(); + if (actor instanceof Response) return actor; + return new Response(JSON.stringify({ rules: await listRules() }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ error: "failed to list rules" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const POST = async (req: NextRequest) => { + try { + const actor = await requireActor(); + if (actor instanceof Response) return actor; + const body = await req.json().catch(() => null); + const parsed = createSchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const rule = await createRule({ + key: parsed.data.key, + event: parsed.data.event ?? "assignment.created", + offsetDays: parsed.data.offsetDays, + sendAtLocalTime: parsed.data.sendAtLocalTime, + channelSet: parsed.data.channelSet, + appliesToServiceId: parsed.data.appliesToServiceId ?? null, + active: parsed.data.active ?? true, + }); + return new Response(JSON.stringify({ rule }), { + status: 201, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ error: "failed to create rule" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const PATCH = async (req: NextRequest) => { + try { + const actor = await requireActor(); + if (actor instanceof Response) return actor; + const body = await req.json().catch(() => null); + const parsed = patchSchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const { id, ...patch } = parsed.data; + const rule = await updateRule(id, patch); + if (!rule) { + return new Response(JSON.stringify({ error: "unknown rule" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ rule }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ error: "failed to update rule" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/notifications/route.ts b/src/app/api/dev/notifications/route.ts new file mode 100644 index 0000000..92d3ae3 --- /dev/null +++ b/src/app/api/dev/notifications/route.ts @@ -0,0 +1,170 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listNotifications, retryNotification } from "@/db/outbox"; +import { db } from "@/db"; +import { users } from "@/db/schema"; +import { resolveEmailTransport } from "@/lib/email"; +import { getEmailTransportSettings } from "@/db/settings"; +import { eq } from "drizzle-orm"; +import { NOTIFICATION_STATUSES, type NotificationStatus } from "@/db/schema"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +function isStatus(value: string | null): value is NotificationStatus { + return ( + value !== null && + (NOTIFICATION_STATUSES as readonly string[]).includes(value) + ); +} + +/** + * GET /api/dev/notifications?status=&limit= — the admin notification log + * (newest first), read straight from the outbox table (ARCHITECTURE §4/§6.1). + * Guarded by `schedule.publish`. + */ +export const GET = async (req: NextRequest) => { + try { + const session = await auth(); + const user = session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; + if (!user) { + return new Response( + JSON.stringify({ + error: "Authentication required", + code: "UNAUTHORIZED", + }), + { status: 401, headers: JSON_HEADERS }, + ); + } + requirePermission(user, "schedule.publish"); + + const statusParam = req.nextUrl.searchParams.get("status"); + if (statusParam !== null && !isStatus(statusParam)) { + return new Response( + JSON.stringify({ error: `unknown status: ${statusParam}` }), + { status: 400, headers: JSON_HEADERS }, + ); + } + const limitParam = Number(req.nextUrl.searchParams.get("limit") ?? "50"); + const notifications = await listNotifications({ + status: isStatus(statusParam) ? statusParam : undefined, + limit: Number.isFinite(limitParam) ? limitParam : 50, + }); + + return new Response(JSON.stringify({ notifications }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +const actionSchema = z.object({ + action: z.enum(["retry", "send_test"]), + id: z.string().min(1).optional(), +}); + +/** + * POST /api/dev/notifications — the admin log's actions (E6). + * { action: "retry", id } -> requeue a failed/suppressed row for the next tick + * { action: "send_test" } -> send a test email to the signed-in admin + */ +export const POST = async (req: NextRequest) => { + try { + const session = await auth(); + const user = session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; + if (!user) { + return new Response( + JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), + { status: 401, headers: JSON_HEADERS }, + ); + } + requirePermission(user, "schedule.publish"); + + const body = await req.json().catch(() => null); + const parsed = actionSchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + if (parsed.data.action === "retry") { + if (!parsed.data.id) { + return new Response(JSON.stringify({ error: "an id is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const row = await retryNotification(parsed.data.id); + if (!row) { + return new Response(JSON.stringify({ error: "unknown notification" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ ok: true, notification: row }), { + status: 200, + headers: JSON_HEADERS, + }); + } + + const [actor] = await db + .select({ email: users.email, firstName: users.firstName }) + .from(users) + .where(eq(users.id, user.id)) + .limit(1); + if (!actor) { + return new Response(JSON.stringify({ error: "unknown user" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + const settings = await getEmailTransportSettings(); + const transport = resolveEmailTransport(settings); + const result = await transport.send({ + to: settings.notificationEmail || actor.email, + subject: "Media Team Hub — test message", + html: `

${actor.firstName}, this is a test from Media Team Hub.

If you can read this, ${transport.name} delivery works.

`, + text: `${actor.firstName}, this is a test from Media Team Hub. If you can read this, ${transport.name} delivery works.`, + templateKey: "admin.send_test", + dedupeKey: `admin.send_test:${user.id}:${Date.now()}`, + }); + return new Response(JSON.stringify({ ok: true, transport: transport.name, ...result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/positions/requirements/route.ts b/src/app/api/dev/positions/requirements/route.ts index 08a8278..2ddad62 100644 --- a/src/app/api/dev/positions/requirements/route.ts +++ b/src/app/api/dev/positions/requirements/route.ts @@ -2,6 +2,7 @@ import { NextRequest } from "next/server"; import { z } from "zod"; import { getPositionSkills, setPositionSkills } from "@/db/positions"; import { validateRequirements } from "@/domain/positions"; +import { gateOrUser } from "@/auth/api"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -44,6 +45,9 @@ const ok = (row: unknown) => * core flag). */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const positionId = req.nextUrl.searchParams.get("positionId"); if (!positionId) return bad("missing positionId"); const row = await getPositionSkills(positionId); @@ -61,6 +65,9 @@ export const GET = async (req: NextRequest) => { * "weight": 3, "requiredLevel": "qualified" } ], "published": true } */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); diff --git a/src/app/api/dev/positions/route.ts b/src/app/api/dev/positions/route.ts index bfd34a6..a91aa9b 100644 --- a/src/app/api/dev/positions/route.ts +++ b/src/app/api/dev/positions/route.ts @@ -6,6 +6,7 @@ import { updatePosition, deactivatePosition, } from "@/db/positions"; +import { gateOrUser } from "@/auth/api"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -85,6 +86,9 @@ const dbError = (err: unknown) => { /** GET /api/dev/positions?active=true — list picker rows. */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const active = req.nextUrl.searchParams.get("active") !== "false"; const rows = await listPositions({ active }); return new Response(JSON.stringify({ rows }), { @@ -95,6 +99,9 @@ export const GET = async (req: NextRequest) => { /** POST /api/dev/positions { ...createFields } — create (slug generated). */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") { return bad("invalid body"); @@ -114,6 +121,9 @@ export const POST = async (req: NextRequest) => { * `slug` is never accepted here: it freezes after creation. */ export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") { return bad("invalid body"); diff --git a/src/app/api/dev/profile/route.ts b/src/app/api/dev/profile/route.ts index eb41ef6..01d9533 100644 --- a/src/app/api/dev/profile/route.ts +++ b/src/app/api/dev/profile/route.ts @@ -1,7 +1,12 @@ import { NextRequest } from "next/server"; import { z } from "zod"; -import { updateProfile, setSmsConsent } from "@/db/profile"; -import type { ProfilePatch } from "@/db/profile"; +import { clientIp, gateSelfOr } from "@/auth/api"; +import { + updateProfile, + setSmsConsent, + updateNotificationPreferences, +} from "@/db/profile"; +import type { ProfilePatch, NotificationPreferencePatch } from "@/db/profile"; import type { SmsConsentSource } from "@/db/schema"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -14,6 +19,11 @@ const profileSchema = z.object({ phoneE164: z.string().nullable().optional(), emergencyContact: z.string().nullable().optional(), timezone: z.string().optional(), + emailEnabled: z.boolean().optional(), + reminderLeadDays: z.number().int().min(1).max(14).optional(), + digestOnly: z.boolean().optional(), + quietHoursStart: z.string().regex(/^\d{2}:\d{2}$/).optional(), + quietHoursEnd: z.string().regex(/^\d{2}:\d{2}$/).optional(), }); const consentSchema = z.object({ @@ -45,6 +55,9 @@ export const PATCH = async (req: NextRequest) => { }); } + const gate = await gateSelfOr("users.manage", parsed.data.userId); + if (gate instanceof Response) return gate; + try { // Only update fields actually present in the body — a PATCH must not null // out unspecified fields (e.g. omitting phoneE164 must not wipe the phone). @@ -56,7 +69,25 @@ export const PATCH = async (req: NextRequest) => { if (parsed.data.emergencyContact !== undefined) patch.emergencyContact = parsed.data.emergencyContact; if (parsed.data.timezone !== undefined) patch.timezone = parsed.data.timezone; + const prefPatch: NotificationPreferencePatch = {}; + if (parsed.data.emailEnabled !== undefined) + prefPatch.emailEnabled = parsed.data.emailEnabled; + if (parsed.data.reminderLeadDays !== undefined) + prefPatch.reminderLeadDays = parsed.data.reminderLeadDays; + if (parsed.data.digestOnly !== undefined) + prefPatch.digestOnly = parsed.data.digestOnly; + if (parsed.data.quietHoursStart !== undefined) + prefPatch.quietHoursStart = parsed.data.quietHoursStart; + if (parsed.data.quietHoursEnd !== undefined) + prefPatch.quietHoursEnd = parsed.data.quietHoursEnd; + const result = await updateProfile(parsed.data.userId, patch); + if (Object.keys(prefPatch).length > 0) { + result.preferences = await updateNotificationPreferences( + parsed.data.userId, + prefPatch, + ); + } return new Response(JSON.stringify(result), { status: 200, headers: JSON_HEADERS, @@ -91,12 +122,16 @@ export const POST = async (req: NextRequest) => { }); } + const gate = await gateSelfOr("users.manage", parsed.data.userId); + if (gate instanceof Response) return gate; + try { const preferences = await setSmsConsent( parsed.data.userId, { source: parsed.data.source as SmsConsentSource, - ip: parsed.data.ip ?? null, + // TCPA evidence is recorded from the request, never from the client body. + ip: clientIp(req), }, ); return new Response(JSON.stringify({ ok: true, preferences }), { diff --git a/src/app/api/dev/reset/route.ts b/src/app/api/dev/reset/route.ts index 6ddbd94..aedcf98 100644 --- a/src/app/api/dev/reset/route.ts +++ b/src/app/api/dev/reset/route.ts @@ -1,35 +1,44 @@ -import { auth } from "@/auth/config"; -import { AuthError, requirePermission } from "@/auth/permissions"; -import type { SystemRole } from "@/auth/roles"; +import { gateOrUser } from "@/auth/api"; import { resetAndSeed } from "@/db/seed"; const JSON_HEADERS = { "content-type": "application/json" }; /** - * Dev console reset. Admin-only (admin.settings): truncates the seed-owned - * tables and repopulates them, so E2E tests start from a known-clean state on - * every run instead of accumulating the mutations of prior runs. Not wired into - * any UI — it exists only for test harnesses. + * Test-only database reset. + * + * Two gates, both required: + * 1. `ALLOW_DEV_RESET=true` must be set explicitly. This keeps a destructive + * truncate + reseed out of any deployment that did not ask for it. + * 2. The caller must be a signed-in admin (`admin.settings`). + * + * E2E sets `ALLOW_DEV_RESET=true` in `playwright.config.ts`; production + * compose does not. */ export const POST = async () => { - try { - const session = await auth(); - requirePermission( - (session?.user as { systemRole: SystemRole } | null | undefined), - "admin.settings", + if (process.env.ALLOW_DEV_RESET !== "true") { + return new Response( + JSON.stringify({ + error: "database reset is disabled in this environment", + code: "RESET_DISABLED", + }), + { status: 403, headers: JSON_HEADERS }, ); + } + + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + try { await resetAndSeed(); return new Response(JSON.stringify({ ok: true }), { status: 200, headers: JSON_HEADERS, }); } catch (e) { - if (e instanceof AuthError) { - return new Response(JSON.stringify({ error: e.message, code: e.code }), { - status: e.status, - headers: JSON_HEADERS, - }); - } - throw e; + const message = e instanceof Error ? e.message : "reset failed"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); } }; diff --git a/src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts b/src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts new file mode 100644 index 0000000..5b4efc8 --- /dev/null +++ b/src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts @@ -0,0 +1,138 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { writeAudit } from "@/db/audit"; +import { db } from "@/db"; +import { applyAutoFill, computeAutoFill } from "@/db/autoFill"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const bodySchema = z + .object({ + maxServicesPerMonth: z.number().int().positive().optional(), + }) + .optional(); + +/** + * Auto-fill proposals for one service instance (unit D9). + * + * GET /api/dev/schedule/:instanceId/auto-fill + * -> { proposals, unfilled } computed from the instance's open seats and + * the active volunteer pool. Nothing is written. + * + * POST /api/dev/schedule/:instanceId/auto-fill + * { maxServicesPerMonth? } + * -> writes one `proposed`/`auto` assignment per still-free proposal and + * an audit row. Idempotent: a re-run finds every seat already filled + * and writes 0 rows. + * + * Guarded by `schedule.publish` (coordinator + admin). + */ +export const GET = async ( + req: NextRequest, + { params }: { params: Promise<{ instanceId: string }> }, +) => { + try { + const session = await auth(); + const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined); + if (!user) { + return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), { + status: 401, + headers: JSON_HEADERS, + }); + } + requirePermission(user, "schedule.publish"); + + const { instanceId } = await params; + const result = await computeAutoFill(instanceId); + return new Response(JSON.stringify(result), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 404, + headers: JSON_HEADERS, + }); + } +}; + +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ instanceId: string }> }, +) => { + let maxServicesPerMonth: number | undefined; + try { + const body = await req.json().catch(() => null); + const parsed = bodySchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + maxServicesPerMonth = parsed.data?.maxServicesPerMonth; + } catch { + return new Response(JSON.stringify({ error: "invalid body" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const session = await auth(); + const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined); + if (!user) { + return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), { + status: 401, + headers: JSON_HEADERS, + }); + } + requirePermission(user, "schedule.publish"); + const actorId = user.id; + + const { instanceId } = await params; + const result = await applyAutoFill(instanceId, { + actorId, + maxServicesPerMonth, + }); + + await writeAudit(db, { + actorId, + action: "schedule.autofill", + entityType: "service_instance", + entityId: instanceId, + after: { + proposals: result.proposals.length, + written: result.written, + unfilled: result.unfilled.length, + }, + }); + + return new Response(JSON.stringify(result), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/schedule/[instanceId]/publish/route.ts b/src/app/api/dev/schedule/[instanceId]/publish/route.ts new file mode 100644 index 0000000..6ed95f1 --- /dev/null +++ b/src/app/api/dev/schedule/[instanceId]/publish/route.ts @@ -0,0 +1,147 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { auth } from "@/auth/config"; +import { requestOrigin } from "@/auth/magic-link"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { PublishError, publishInstance, unpublishInstance } from "@/db/publish"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const bodySchema = z.object({ + allowGaps: z.boolean().optional(), +}); + +/** Map a refused publish/unpublish to its HTTP status. */ +function errorStatus(code: PublishError["code"]): number { + switch (code) { + case "unknown_instance": + return 404; + case "instance_cancelled": + case "open_slots": + case "unpublish_blocked": + return 409; + } +} + +function jsonError(e: PublishError): Response { + return new Response( + JSON.stringify({ error: e.message, code: e.code, gaps: e.gaps }), + { status: errorStatus(e.code), headers: JSON_HEADERS }, + ); +} + +function authFailure(e: AuthError): Response { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); +} + +/** Resolve the session user or return the 401 response. */ +async function requireActor(): Promise< + { id: string; systemRole: SystemRole } | Response +> { + const session = await auth(); + const user = session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; + if (!user) { + return new Response( + JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), + { status: 401, headers: JSON_HEADERS }, + ); + } + requirePermission(user, "schedule.publish"); + return user; +} + +/** + * Publish / unpublish one service instance (unit D10, ARCHITECTURE §5.5). + * + * POST /api/dev/schedule/:instanceId/publish { allowGaps? } + * -> one transaction: validate coverage, set `status='published'` + + * `published_at`/`published_by`, write the `week.published` audit + * row. Blocked 409 with `gaps` when a covering seat is empty and + * `allowGaps` is false. Re-publishing is an idempotent no-op. + * + * DELETE /api/dev/schedule/:instanceId/publish + * -> back to draft, `week.unpublished` audit row. Refused 409 while a + * volunteer has confirmed. + * + * D10 sends nothing — notification wiring is E1. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ instanceId: string }> }, +) => { + let allowGaps: boolean | undefined; + try { + const body = await req.json().catch(() => null); + const parsed = bodySchema.safeParse(body ?? {}); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + allowGaps = parsed.data.allowGaps; + } catch { + return new Response(JSON.stringify({ error: "invalid body" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + try { + const actor = await requireActor(); + if (actor instanceof Response) return actor; + + const { instanceId } = await params; + const result = await publishInstance(instanceId, { + actorId: actor.id, + allowGaps, + // Confirmation links in the publish/reminder emails must point at the + // origin the schedule is being managed from (LAN IP or public domain). + appOrigin: requestOrigin(req), + }); + return new Response(JSON.stringify({ ok: true, ...result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + if (e instanceof PublishError) return jsonError(e); + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const DELETE = async ( + _req: NextRequest, + { params }: { params: Promise<{ instanceId: string }> }, +) => { + try { + const actor = await requireActor(); + if (actor instanceof Response) return actor; + + const { instanceId } = await params; + const result = await unpublishInstance(instanceId, { actorId: actor.id }); + return new Response(JSON.stringify({ ok: true, ...result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + if (e instanceof PublishError) return jsonError(e); + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/schedule/instances/route.ts b/src/app/api/dev/schedule/instances/route.ts new file mode 100644 index 0000000..f9e1650 --- /dev/null +++ b/src/app/api/dev/schedule/instances/route.ts @@ -0,0 +1,51 @@ +import type { NextRequest } from "next/server"; +import { eq } from "drizzle-orm"; +import { db } from "@/db"; +import { serviceInstances, services } from "@/db/schema"; +import { gateCron } from "@/auth/api"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * GET /api/dev/schedule/instances — the list of service instances (id, + * occursOn, serviceName) for the admin helper routes. Guarded by + * `schedule.publish` (coordinator + admin). + */ +export const GET = async (req: NextRequest) => { + const gate = await gateCron(req); + if (gate instanceof Response) return gate; + + try { + + // `serviceName` is the instance's title override when set, else the service + // template's name. Ordering includes `startsAt` so two instances on the same + // date (both Sunday services) always come back in the same order. + const rows = await db + .select({ + id: serviceInstances.id, + occursOn: serviceInstances.occursOn, + titleOverride: serviceInstances.titleOverride, + name: services.name, + status: serviceInstances.status, + }) + .from(serviceInstances) + .innerJoin(services, eq(services.id, serviceInstances.serviceId)) + .orderBy(serviceInstances.occursOn, serviceInstances.startsAt); + const instances = rows.map((r) => ({ + id: r.id, + occursOn: r.occursOn, + serviceName: r.titleOverride ?? r.name, + status: r.status, + })); + return new Response(JSON.stringify({ instances }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/services/route.ts b/src/app/api/dev/services/route.ts index b3cbd3e..32d790c 100644 --- a/src/app/api/dev/services/route.ts +++ b/src/app/api/dev/services/route.ts @@ -1,14 +1,38 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; import { listServices, createService, updateService, deactivateService, + deleteService, } from "@/db/services"; const JSON_HEADERS = { "content-type": "application/json" }; +/** Services are schedule data: only `schedule.publish` roles may change them. */ +async function requireEditor(): Promise { + const session = await auth(); + try { + requirePermission( + (session?.user as { systemRole: SystemRole } | null | undefined), + "schedule.publish", + ); + return null; + } catch (e) { + if (e instanceof AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); + } + throw e; + } +} + const idSchema = z.string().min(1); const serviceCreateSchema = z.object({ @@ -85,6 +109,8 @@ const constraintError = (err: unknown): Response | null => { /** GET /api/dev/services?active=true — list service templates. */ export const GET = async (req: NextRequest) => { + const failure = await requireEditor(); + if (failure) return failure; const active = req.nextUrl.searchParams.get("active") !== "false"; const rows = await listServices({ active }); return new Response(JSON.stringify({ rows }), { @@ -95,6 +121,8 @@ export const GET = async (req: NextRequest) => { /** POST /api/dev/services { ...fields } — create a service template. */ export const POST = async (req: NextRequest) => { + const failure = await requireEditor(); + if (failure) return failure; const body = await readBody(req); if (!body || typeof body !== "object") { return bad("invalid body"); @@ -110,12 +138,52 @@ export const POST = async (req: NextRequest) => { } }; +/** + * DELETE /api/dev/services?id=… — permanently remove a template that never ran. + * Refused (409) once an instance has started, been published, or carries an + * assignment; those must be deactivated so schedule history survives. + */ +export const DELETE = async (req: NextRequest) => { + const failure = await requireEditor(); + if (failure) return failure; + const id = idSchema.safeParse(req.nextUrl.searchParams.get("id")); + if (!id.success) return bad("a valid id is required"); + + const result = await deleteService(id.data); + if (result.ok) { + return new Response( + JSON.stringify({ ok: true, removedInstances: result.removedInstances }), + { status: 200, headers: JSON_HEADERS }, + ); + } + if (result.reason === "not_found") { + return new Response(JSON.stringify({ error: "unknown service" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + + const history = + result.assignments > 0 + ? `${result.instances} instance(s) and ${result.assignments} assignment(s)` + : `${result.instances} published or past instance(s)`; + return new Response( + JSON.stringify({ + error: `This service has ${history}. Deactivate it instead so the schedule history is preserved.`, + code: "HAS_HISTORY", + }), + { status: 409, headers: JSON_HEADERS }, + ); +}; + /** * PATCH /api/dev/services { id, ...fields } — edit. * PATCH { id, active: false } — deactivate (soft delete). * `name` is never accepted here: it freezes after creation. */ export const PATCH = async (req: NextRequest) => { + const failure = await requireEditor(); + if (failure) return failure; const body = await readBody(req); if (!body || typeof body !== "object") { return bad("invalid body"); diff --git a/src/app/api/dev/settings/route.ts b/src/app/api/dev/settings/route.ts new file mode 100644 index 0000000..ed4d11c --- /dev/null +++ b/src/app/api/dev/settings/route.ts @@ -0,0 +1,109 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + getEmailSettings, + saveEmailSettings, + type EmailSettings, +} from "@/db/settings"; +import { normalizeAppPassword } from "@/lib/secret"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const settingsSchema = z.object({ + emailFrom: z.string().email(), + notificationEmail: z.string().email().or(z.literal("")), + /** Empty string disconnects Gmail; omitted leaves the stored credentials. */ + smtpUser: z.union([z.literal(""), z.string().email()]).optional(), + /** Omitted/blank keeps the stored app password. */ + smtpAppPassword: z.string().max(200).optional(), +}); + +/** What goes in the audit trail — never the password. */ +function summary(settings: EmailSettings) { + return { + emailFrom: settings.emailFrom, + notificationEmail: settings.notificationEmail, + smtpUser: settings.smtpUser, + smtpConfigured: settings.smtpConfigured, + }; +} + +const bad = (message: string, status = 400) => + new Response(JSON.stringify({ error: message }), { + status, + headers: JSON_HEADERS, + }); + +/** + * GET /api/dev/settings — email identity, and whether a Gmail account is + * connected (the app password itself is never returned). + */ +export const GET = async () => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + return new Response(JSON.stringify({ settings: await getEmailSettings() }), { + status: 200, + headers: JSON_HEADERS, + }); +}; + +/** + * PUT /api/dev/settings + * { emailFrom, notificationEmail, smtpUser?, smtpAppPassword? } + * + * Saves the sender identity and, when given, the Gmail credentials. A blank + * app password keeps the stored one; `smtpUser: ""` disconnects Gmail and + * deletes both credential rows. Every save writes an audit row with the + * address but never the secret. + */ +export const PUT = async (req: NextRequest) => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + const body = await req.json().catch(() => null); + const parsed = settingsSchema.safeParse(body); + if (!parsed.success) return bad(parsed.error.message); + + const before = await getEmailSettings(); + const smtpUser = parsed.data.smtpUser; + const password = normalizeAppPassword(parsed.data.smtpAppPassword ?? ""); + + if (smtpUser !== undefined && smtpUser !== "") { + if (password !== "" && password.length < 8) { + return bad( + "That does not look like a Google app password — it should be 16 characters.", + ); + } + if (password === "" && !before.smtpConfigured) { + return bad("Enter the 16-character app password for this Gmail account."); + } + if (password === "" && smtpUser !== before.smtpUser) { + return bad("Enter the app password for the new Gmail account."); + } + } + + const settings = await saveEmailSettings({ + emailFrom: parsed.data.emailFrom, + notificationEmail: parsed.data.notificationEmail, + smtpUser, + smtpAppPassword: password, + }); + + await writeAudit(db, { + actorId: gate.id, + action: "settings.email.updated", + entityType: "app_settings", + entityId: "email", + before: summary(before), + after: summary(settings), + }); + + return new Response(JSON.stringify({ ok: true, settings }), { + status: 200, + headers: JSON_HEADERS, + }); +}; diff --git a/src/app/api/dev/skills/assessments/route.ts b/src/app/api/dev/skills/assessments/route.ts index 6f0942c..a1f2193 100644 --- a/src/app/api/dev/skills/assessments/route.ts +++ b/src/app/api/dev/skills/assessments/route.ts @@ -1,4 +1,5 @@ import { NextRequest } from "next/server"; +import { gateOrUser } from "@/auth/api"; import { listAssessments } from "@/db/assessments"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -16,6 +17,9 @@ const bad = (message: string) => * the verify modal. There is intentionally no update or delete endpoint. */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const params = req.nextUrl.searchParams; const rawLimit = params.get("limit"); let limit: number | undefined; diff --git a/src/app/api/dev/skills/compose/route.ts b/src/app/api/dev/skills/compose/route.ts index c6dcbcd..989d99e 100644 --- a/src/app/api/dev/skills/compose/route.ts +++ b/src/app/api/dev/skills/compose/route.ts @@ -1,5 +1,6 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; import { composeSkillName } from "@/domain/skills"; import { dedupeKey } from "@/db/positions"; @@ -39,6 +40,9 @@ const bad = (message: string) => * technologyName?, functionId?, functionName? } -> { name, dedupeKey }. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); const parsed = composeSchema.safeParse(body); diff --git a/src/app/api/dev/skills/matrix/route.ts b/src/app/api/dev/skills/matrix/route.ts index c7952db..eb318b2 100644 --- a/src/app/api/dev/skills/matrix/route.ts +++ b/src/app/api/dev/skills/matrix/route.ts @@ -1,6 +1,7 @@ import { NextRequest } from "next/server"; import { listSkillsMatrix } from "@/db/assessments"; import { isSkillLevel, SKILL_LEVELS, type SkillLevel } from "@/domain/assessments"; +import { gateOrUser } from "@/auth/api"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -19,6 +20,9 @@ const bad = (message: string) => * compose, so `?level=qualified` answers "who is currently signed off?". */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const params = req.nextUrl.searchParams; const level = params.get("level"); if (level !== null && !isSkillLevel(level)) { diff --git a/src/app/api/dev/skills/route.ts b/src/app/api/dev/skills/route.ts index 6b16cc3..ac8b2cd 100644 --- a/src/app/api/dev/skills/route.ts +++ b/src/app/api/dev/skills/route.ts @@ -6,6 +6,7 @@ import { updateSkill, deactivateSkill, } from "@/db/positions"; +import { gateOrUser } from "@/auth/api"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -95,6 +96,9 @@ const dbError = (err: unknown) => { /** GET /api/dev/skills?active=true — list picker rows. */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const active = req.nextUrl.searchParams.get("active") !== "false"; const rows = await listSkills({ active }); return new Response(JSON.stringify({ rows }), { @@ -105,6 +109,9 @@ export const GET = async (req: NextRequest) => { /** POST /api/dev/skills { ...createFields } — create (slug + dedupe_key generated). */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); const parsed = skillCreateSchema.safeParse(body); @@ -122,6 +129,9 @@ export const POST = async (req: NextRequest) => { * `slug` and the composing FKs are never accepted here: they freeze after creation. */ export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); const id = idSchema.safeParse((body as { id?: unknown }).id); diff --git a/src/app/api/dev/skills/verify/route.ts b/src/app/api/dev/skills/verify/route.ts index ad71cf6..95e43e9 100644 --- a/src/app/api/dev/skills/verify/route.ts +++ b/src/app/api/dev/skills/verify/route.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { AssessmentError, verifySkillLevel } from "@/db/assessments"; import { ASSESSMENT_KINDS } from "@/db/schema"; import { SKILL_LEVELS } from "@/domain/assessments"; +import { gateOrUser } from "@/auth/api"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -11,7 +12,6 @@ const verifySchema = z.object({ skillId: z.string().min(1), /** The level being signed off — validated again by the domain rule. */ level: z.enum(SKILL_LEVELS), - assessorId: z.string().min(1).nullable().optional(), kind: z.enum(ASSESSMENT_KINDS).optional(), notes: z.string().nullable().optional(), }); @@ -66,20 +66,24 @@ const dbError = (err: unknown) => { }; /** - * POST /api/dev/skills/verify { userId, skillId, level, assessorId?, kind?, notes? } + * POST /api/dev/skills/verify { userId, skillId, level, kind?, notes? } * * The verify-level modal's save: appends a `skill_assessments` row and moves * `user_skills.verified_level` in one transaction. The volunteer's - * `self_comfort` is untouched (C2's signal is not the gate). + * `self_comfort` is untouched (C2's signal is not the gate). The assessor is + * the signed-in admin — the client cannot name someone else as the sign-off. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("training.author"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); const parsed = verifySchema.safeParse(body); if (!parsed.success) return bad(parsed.error.message); try { - const result = await verifySkillLevel(parsed.data); + const result = await verifySkillLevel({ ...parsed.data, assessorId: gate.id }); return ok(result); } catch (err) { if (err instanceof AssessmentError) return bad(err.problems.join("; ")); diff --git a/src/app/api/dev/storage/route.ts b/src/app/api/dev/storage/route.ts new file mode 100644 index 0000000..b8a84cd --- /dev/null +++ b/src/app/api/dev/storage/route.ts @@ -0,0 +1,95 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + checkArchiveDestination, + getStorageSettings, + saveStorageSettings, + type StorageSettings, +} from "@/db/storage-settings"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const storageSchema = z.object({ + nfsShare: z + .string() + .trim() + .max(255) + .refine((value) => !/[\r\n]/.test(value), "Invalid NFS share"), + archivePath: z + .string() + .trim() + .min(1) + .max(500) + .refine((value) => value.startsWith("/"), "Archive path must be absolute"), + archiveFolder: z + .string() + .trim() + .min(1) + .max(120) + .refine( + (value) => !value.includes("/") && !value.includes("\\") && value !== "..", + "Archive folder must be one safe folder name", + ), +}); + +function publicSettings(settings: StorageSettings) { + return { + nfsShare: settings.nfsShare, + archivePath: settings.archivePath, + archiveFolder: settings.archiveFolder, + }; +} + +/** GET /api/dev/storage — NFS/archive destination and mount readiness. */ +export const GET = async () => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + const settings = await getStorageSettings(); + return jsonResponse({ + settings: publicSettings(settings), + status: await checkArchiveDestination(settings), + }); +}; + +/** + * PUT /api/dev/storage + * { nfsShare, archivePath, archiveFolder } + * + * The path must already be mounted into the container. Saving does not mount + * NFS; it records the operator's chosen export and the visible mount path, then + * verifies the path is a writable directory. + */ +export const PUT = async (req: NextRequest) => { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + const parsed = storageSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse( + 400, + parsed.error.issues[0]?.message ?? "Invalid storage settings", + ); + } + + const before = await getStorageSettings(); + const settings = await saveStorageSettings(parsed.data); + const status = await checkArchiveDestination(settings); + + await writeAudit(db, { + actorId: gate.id, + action: "settings.storage.updated", + entityType: "app_settings", + entityId: "storage", + before: publicSettings(before), + after: { ...publicSettings(settings), ready: status.ready }, + }); + + return jsonResponse({ + ok: true, + settings: publicSettings(settings), + status, + }); +}; diff --git a/src/app/api/dev/training/lessons/route.ts b/src/app/api/dev/training/lessons/route.ts new file mode 100644 index 0000000..babb684 --- /dev/null +++ b/src/app/api/dev/training/lessons/route.ts @@ -0,0 +1,160 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { unlink } from "node:fs/promises"; +import { auth } from "@/auth/config"; +import { AuthError, hasPermission, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { + createLesson, + deleteLesson, + listLessons, + listResourceStoredNames, + updateLesson, +} from "@/db/training"; +import { uploadPath } from "@/lib/uploads"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const lessonCreateSchema = z.object({ + title: z.string().min(1).max(200), + summary: z.string().max(1000).nullable().optional(), + body: z.string().max(100_000).optional(), + published: z.boolean().optional(), + sortOrder: z.number().int().min(0).max(999).optional(), +}); + +const lessonPatchSchema = lessonCreateSchema.partial().extend({ + id: z.string().min(1), +}); + +function authFailure(e: AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); +} + +async function sessionUser() { + const session = await auth(); + return session?.user as + | { id: string; systemRole: SystemRole } + | null + | undefined; +} + +/** + * Training lessons (F2 authoring). Reads are for any signed-in volunteer and + * hide unpublished drafts unless the caller can author. Writes require + * `training.author` (admin). + * + * GET -> { lessons } + * POST -> { lesson } create + * PATCH -> { lesson } edit / publish toggle + * DELETE ?id= -> { ok } removes the lesson, its rows, and its files + */ +export const GET = async () => { + const user = await sessionUser(); + if (!user) { + return new Response( + JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), + { status: 401, headers: JSON_HEADERS }, + ); + } + const canAuthor = hasPermission(user.systemRole, "training.author"); + return new Response( + JSON.stringify({ lessons: await listLessons({ includeUnpublished: canAuthor }) }), + { status: 200, headers: JSON_HEADERS }, + ); +}; + +export const POST = async (req: NextRequest) => { + try { + await requirePermission(await sessionUser(), "training.author"); + const body = await req.json().catch(() => null); + const parsed = lessonCreateSchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const lesson = await createLesson(parsed.data); + return new Response(JSON.stringify({ lesson }), { + status: 201, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + return new Response(JSON.stringify({ error: "failed to create lesson" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const PATCH = async (req: NextRequest) => { + try { + await requirePermission(await sessionUser(), "training.author"); + const body = await req.json().catch(() => null); + const parsed = lessonPatchSchema.safeParse(body); + if (!parsed.success) { + return new Response(JSON.stringify({ error: parsed.error.message }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const { id, ...patch } = parsed.data; + const lesson = await updateLesson(id, patch); + if (!lesson) { + return new Response(JSON.stringify({ error: "unknown lesson" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + return new Response(JSON.stringify({ lesson }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + return new Response(JSON.stringify({ error: "failed to update lesson" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const DELETE = async (req: NextRequest) => { + try { + await requirePermission(await sessionUser(), "training.author"); + const id = req.nextUrl.searchParams.get("id"); + if (!id) { + return new Response(JSON.stringify({ error: "an id is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const files = await listResourceStoredNames(id); + const deleted = await deleteLesson(id); + if (!deleted) { + return new Response(JSON.stringify({ error: "unknown lesson" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + // Metadata cascades; remove the bytes best-effort. + for (const storedName of files) { + await unlink(uploadPath(storedName)).catch(() => undefined); + } + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + return new Response(JSON.stringify({ error: "failed to delete lesson" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/training/resources/route.ts b/src/app/api/dev/training/resources/route.ts new file mode 100644 index 0000000..b3b3747 --- /dev/null +++ b/src/app/api/dev/training/resources/route.ts @@ -0,0 +1,146 @@ +import { NextRequest } from "next/server"; +import { unlink, writeFile } from "node:fs/promises"; +import { auth } from "@/auth/config"; +import { AuthError, requirePermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { addResource, deleteResource, getLesson, getResource } from "@/db/training"; +import { + MAX_UPLOAD_BYTES, + ensureUploadDir, + isAllowedUpload, + storedNameFor, + uploadPath, + uploadSignatureMatches, +} from "@/lib/uploads"; +import { uuidv7 } from "@/lib/uuid"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +function authFailure(e: AuthError) { + return new Response(JSON.stringify({ error: e.message, code: e.code }), { + status: e.status, + headers: JSON_HEADERS, + }); +} + +async function requireAuthor() { + const session = await auth(); + return requirePermission( + (session?.user as { id: string; systemRole: SystemRole } | null | undefined), + "training.author", + ); +} + +/** + * Training attachments. Bytes go to `UPLOAD_DIR` (a named volume in the + * deployment) and only metadata is stored in Postgres, so the database never + * carries binaries. + * + * POST multipart { lessonId, file } -> { resource } + * DELETE ?id= -> { ok } + */ +export const POST = async (req: NextRequest) => { + try { + const user = await requireAuthor(); + const form = await req.formData(); + const lessonId = form.get("lessonId"); + const file = form.get("file"); + + if (typeof lessonId !== "string" || !lessonId) { + return new Response(JSON.stringify({ error: "a lessonId is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + if (!file || typeof file === "string") { + return new Response(JSON.stringify({ error: "a file is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + if (!(await getLesson(lessonId))) { + return new Response(JSON.stringify({ error: "unknown lesson" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + if (file.size > MAX_UPLOAD_BYTES) { + return new Response(JSON.stringify({ error: "file is larger than 5 MB" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const mimeType = file.type || "application/octet-stream"; + if (!isAllowedUpload(mimeType)) { + return new Response( + JSON.stringify({ error: `file type not allowed: ${mimeType}` }), + { status: 400, headers: JSON_HEADERS }, + ); + } + + const bytes = new Uint8Array(await file.arrayBuffer()); + if (!uploadSignatureMatches(mimeType, bytes)) { + return new Response( + JSON.stringify({ + error: `file contents do not match the declared type: ${mimeType}`, + }), + { status: 400, headers: JSON_HEADERS }, + ); + } + + await ensureUploadDir(); + const storedName = storedNameFor(file.name, uuidv7()); + await writeFile(uploadPath(storedName), bytes); + + const resource = await addResource({ + lessonId, + filename: file.name || storedName, + mimeType, + sizeBytes: file.size, + storedName, + }); + void user; + return new Response(JSON.stringify({ resource }), { + status: 201, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + return new Response(JSON.stringify({ error: "failed to upload file" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; + +export const DELETE = async (req: NextRequest) => { + try { + await requireAuthor(); + const id = req.nextUrl.searchParams.get("id"); + if (!id) { + return new Response(JSON.stringify({ error: "an id is required" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + const resource = await getResource(id); + if (!resource) { + return new Response(JSON.stringify({ error: "unknown resource" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + await deleteResource(id); + await unlink(uploadPath(resource.storedName)).catch(() => undefined); + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof AuthError) return authFailure(e); + return new Response(JSON.stringify({ error: "failed to delete file" }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/unavailability/route.ts b/src/app/api/dev/unavailability/route.ts index c8b0511..a52290d 100644 --- a/src/app/api/dev/unavailability/route.ts +++ b/src/app/api/dev/unavailability/route.ts @@ -1,7 +1,10 @@ import { NextRequest } from "next/server"; import { z } from "zod"; +import { gateSelfOr, gateSession } from "@/auth/api"; +import { hasPermission } from "@/auth/permissions"; import { listUnavailability, + getUnavailability, createUnavailability, updateUnavailability, cancelUnavailability, @@ -87,10 +90,27 @@ const constraintError = (err: unknown): Response | null => { return null; }; -/** GET /api/dev/unavailability?userId=... — list blackouts (one per user). */ +/** + * GET /api/dev/unavailability?userId=... — list blackouts. + * A volunteer sees their own; a leader (`schedule.publish`) may see anyone's + * or, with no `userId`, the whole team's. + */ export const GET = async (req: NextRequest) => { - const userId = req.nextUrl.searchParams.get("userId") ?? undefined; - const rows = await listUnavailability({ userId }); + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const requested = req.nextUrl.searchParams.get("userId") ?? undefined; + const canManage = hasPermission(gate.systemRole, "schedule.publish"); + if (requested && requested !== gate.id && !canManage) { + return new Response( + JSON.stringify({ error: "not permitted to view another person's blackouts" }), + { status: 403, headers: JSON_HEADERS }, + ); + } + + const rows = await listUnavailability({ + userId: requested ?? (canManage ? undefined : gate.id), + }); return new Response(JSON.stringify({ rows }), { status: 200, headers: JSON_HEADERS, @@ -105,8 +125,14 @@ export const POST = async (req: NextRequest) => { } const parsed = unavailabilityCreateSchema.safeParse(body); if (!parsed.success) return bad(parsed.error.message); + + const gate = await gateSelfOr("schedule.publish", parsed.data.userId); + if (gate instanceof Response) return gate; + try { - return created(await createUnavailability(parsed.data)); + return created( + await createUnavailability({ ...parsed.data, createdBy: gate.id }), + ); } catch (err) { const constraint = constraintError(err); if (constraint) return constraint; @@ -126,6 +152,12 @@ export const PATCH = async (req: NextRequest) => { const id = idSchema.safeParse((body as { id?: unknown }).id); if (!id.success) return bad("invalid id"); + const existing = await getUnavailability(id.data); + if (!existing) return bad("blackout not found"); + + const gate = await gateSelfOr("schedule.publish", existing.userId); + if (gate instanceof Response) return gate; + // Cancel path: explicit status cancelled. if ((body as { status?: unknown }).status === "cancelled") { const row = await cancelUnavailability(id.data); diff --git a/src/app/api/dev/user-skills/route.ts b/src/app/api/dev/user-skills/route.ts index 1dda262..ffa5bc9 100644 --- a/src/app/api/dev/user-skills/route.ts +++ b/src/app/api/dev/user-skills/route.ts @@ -1,6 +1,16 @@ import { NextRequest } from "next/server"; import { z } from "zod"; -import { getUserSkills, setSelfComfort } from "@/db/userSkills"; +import { gateOrUser, gateSelfOr } from "@/auth/api"; +import { AssessmentError, verifySkillLevel } from "@/db/assessments"; +import { + addUserSkill, + deleteUserSkill, + getUserSkill, + getUserSkills, + setMentorApproval, + setSelfComfort, +} from "@/db/userSkills"; +import { SKILL_LEVELS } from "@/domain/assessments"; import { validateSelfComfort } from "@/domain/userSkills"; const JSON_HEADERS = { "content-type": "application/json" }; @@ -15,6 +25,19 @@ const selfComfortCreateSchema = z.object({ selfComfort: z.number().int().nullable().optional(), }); +/** An admin setting one person's verified level and/or mentor sign-off. */ +const levelPatchSchema = z + .object({ + userId: z.string().min(1), + skillId: z.string().min(1), + verifiedLevel: z.enum(SKILL_LEVELS).optional(), + mentorApproved: z.boolean().optional(), + }) + .refine( + (value) => value.verifiedLevel !== undefined || value.mentorApproved !== undefined, + { message: "nothing to update" }, + ); + async function readBody(req: NextRequest) { try { return await req.json(); @@ -70,8 +93,23 @@ const dbError = (err: unknown) => { }); }; -/** GET /api/dev/user-skills?userId= — a volunteer's competency records. */ +/** + * Competency records (`user_skills`). + * + * GET ?userId= -> { rows } (signed in) + * POST { userId, skillId, selfComfort } -> { row } volunteer slider: comfort only + * PATCH { userId, skillId, verifiedLevel } -> { row } admin: audited level move + * DELETE ?userId= &skillId= -> { row } admin: remove the entry + * + * The level path never writes `verified_level` directly: an existing record + * moves through `verifySkillLevel`, which appends a `skill_assessments` row in + * the same transaction. The one exception is adding a skill at `none` — the + * bottom of the ladder — which creates the record with nothing to audit. + */ export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.view"); + if (gate instanceof Response) return gate; + const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId")); if (!userId.success) return bad("invalid userId"); const rows = await getUserSkills(userId.data); @@ -79,15 +117,22 @@ export const GET = async (req: NextRequest) => { }; /** - * POST /api/dev/user-skills { userId, skillId, selfComfort } — set a - * volunteer's self-reported comfort (the profile slider). Only - * self_comfort / self_rated_at change; verified_level is never touched. + * POST { userId, skillId, selfComfort } — set a volunteer's self-reported + * comfort (the profile slider). Only self_comfort / self_rated_at change; + * verified_level is never touched. */ export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.view"); + if (gate instanceof Response) return gate; + const body = await readBody(req); if (!body || typeof body !== "object") return bad("invalid body"); const parsed = selfComfortCreateSchema.safeParse(body); if (!parsed.success) return bad(parsed.error.message); + // A volunteer may rate only their own comfort; admins may correct another + // person's record through this same path when needed. + const selfGate = await gateSelfOr("users.manage", parsed.data.userId); + if (selfGate instanceof Response) return selfGate; const selfComfort = parsed.data.selfComfort ?? null; const problems = validateSelfComfort(selfComfort); if (problems.length > 0) return bad(problems[0]); @@ -98,3 +143,86 @@ export const POST = async (req: NextRequest) => { return dbError(err); } }; + +/** + * PATCH { userId, skillId, verifiedLevel } — the admin's per-person level edit. + * + * A missing record is created at `none` (the default level) or, when a higher + * level is requested, through the audited verify path. An existing record always + * moves through the verify path, so demotions are recorded too. + */ +export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + const parsed = levelPatchSchema.safeParse(await readBody(req)); + if (!parsed.success) return bad(parsed.error.message); + const { userId, skillId, verifiedLevel, mentorApproved } = parsed.data; + + try { + const existing = await getUserSkill(userId, skillId); + let row = existing; + + if (!existing) { + if (!verifiedLevel || verifiedLevel === "none") { + row = await addUserSkill(userId, skillId); + } else { + const result = await verifySkillLevel({ + userId, + skillId, + level: verifiedLevel, + assessorId: gate.id, + kind: "admin", + }); + row = result.userSkill; + } + } else if (verifiedLevel !== undefined) { + if (existing.verifiedLevel === verifiedLevel) { + return bad("level is unchanged — nothing to assess"); + } + const result = await verifySkillLevel({ + userId, + skillId, + level: verifiedLevel, + assessorId: gate.id, + kind: "admin", + }); + row = result.userSkill; + } + + if (mentorApproved !== undefined) { + row = await setMentorApproval( + userId, + skillId, + mentorApproved, + gate.id, + ); + } + + return ok(row); + } catch (err) { + if (err instanceof AssessmentError) return bad(err.problems.join("; ")); + return dbError(err); + } +}; + +/** DELETE ?userId= &skillId= — remove one competency record. */ +export const DELETE = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId")); + const skillId = idSchema.safeParse(req.nextUrl.searchParams.get("skillId")); + if (!userId.success || !skillId.success) { + return bad("userId and skillId are required"); + } + + const row = await deleteUserSkill(userId.data, skillId.data); + if (!row) { + return new Response(JSON.stringify({ error: "unknown competency record" }), { + status: 404, + headers: JSON_HEADERS, + }); + } + return ok({ ok: true }); +}; diff --git a/src/app/api/dev/users/magic-link/route.ts b/src/app/api/dev/users/magic-link/route.ts new file mode 100644 index 0000000..5de06a1 --- /dev/null +++ b/src/app/api/dev/users/magic-link/route.ts @@ -0,0 +1,88 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { + APP_ORIGIN, + requestOrigin, + sendMagicLinkEmail, + signMagicToken, +} from "@/auth/magic-link"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { getUserById } from "@/db/users"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (payload: unknown, status = 200) => + new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS }); + +const bodySchema = z.object({ + userId: z.string().min(1), + deliver: z.boolean().optional(), +}); + +/** + * Admin emergency magic link (`users.manage`). + * + * { userId, deliver?: false } -> return a fresh 10-minute sign-in URL + * { userId, deliver: true } -> also send that URL through the configured + * email transport + * + * The URL is always returned so an admin can copy it when mail delivery is + * unavailable. Only active, non-deactivated accounts are eligible; otherwise + * the link would be rejected by the sign-in provider anyway. + */ +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + let body: unknown; + try { + body = await req.json(); + } catch { + return json({ error: "A JSON body is required." }, 400); + } + const parsed = bodySchema.safeParse(body); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + const user = await getUserById(parsed.data.userId); + if (!user) return json({ error: "unknown user" }, 404); + if (user.status !== "active" || user.deactivatedAt !== null) { + return json( + { error: "This account is not active — activate it first." }, + 409, + ); + } + + const token = await signMagicToken(user.email); + const origin = requestOrigin(req) || APP_ORIGIN; + const url = `${origin}/api/dev/complete?token=${encodeURIComponent( + token, + )}&email=${encodeURIComponent(user.email)}`; + + const delivery = parsed.data.deliver + ? await sendMagicLinkEmail(user, url) + : null; + + await writeAudit(db, { + actorId: gate.id, + action: parsed.data.deliver + ? "user.magic_link_sent_by_admin" + : "user.magic_link_created_by_admin", + entityType: "user", + entityId: user.id, + after: { + expiresInMinutes: 10, + delivered: delivery?.delivered ?? false, + transport: delivery?.transport ?? null, + }, + }); + + return json({ + ok: true, + email: user.email, + url, + expiresInMinutes: 10, + delivered: delivery?.delivered ?? false, + transport: delivery?.transport ?? null, + }); +}; diff --git a/src/app/api/dev/users/password/route.ts b/src/app/api/dev/users/password/route.ts new file mode 100644 index 0000000..1ef9362 --- /dev/null +++ b/src/app/api/dev/users/password/route.ts @@ -0,0 +1,87 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { + APP_ORIGIN, + requestOrigin, + signPasswordResetToken, +} from "@/auth/magic-link"; +import { hashPassword, validatePassword } from "@/auth/password"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { getUserById, updateUserCredentials } from "@/db/users"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (payload: unknown, status = 200) => + new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS }); + +const bodySchema = z.discriminatedUnion("action", [ + z.object({ + action: z.literal("set"), + userId: z.string().min(1), + password: z.string().min(1).max(200), + }), + z.object({ + action: z.literal("reset-link"), + userId: z.string().min(1), + }), +]); + +/** + * Admin password controls (`users.manage`). + * + * { action: "set", userId, password } -> change the password directly + * { action: "reset-link", userId } -> mint a one-hour single-use link + * + * The link is returned to the admin to hand over; it is deliberately not + * emailed automatically so an admin can verify the destination first. + */ +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + let body: unknown; + try { + body = await req.json(); + } catch { + return json({ error: "A JSON body is required." }, 400); + } + const parsed = bodySchema.safeParse(body); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + const before = await getUserById(parsed.data.userId); + if (!before) return json({ error: "unknown user" }, 404); + + if (parsed.data.action === "set") { + const passwordError = validatePassword(parsed.data.password); + if (passwordError) return json({ error: passwordError }, 400); + + const passwordHash = await hashPassword(parsed.data.password); + const updated = await updateUserCredentials(before.id, { passwordHash }); + if (!updated) return json({ error: "unknown user" }, 404); + + await writeAudit(db, { + actorId: gate.id, + action: "user.password_set_by_admin", + entityType: "user", + entityId: before.id, + after: { passwordSet: true }, + }); + + return json({ ok: true }); + } + + const token = await signPasswordResetToken(before.email); + const origin = requestOrigin(req) || APP_ORIGIN; + const url = `${origin}/reset-password?token=${encodeURIComponent(token)}`; + + await writeAudit(db, { + actorId: gate.id, + action: "user.password_reset_link_created", + entityType: "user", + entityId: before.id, + after: { expiresInMinutes: 60 }, + }); + + return json({ ok: true, url, expiresInMinutes: 60 }); +}; diff --git a/src/app/api/dev/users/route.ts b/src/app/api/dev/users/route.ts new file mode 100644 index 0000000..9bb39e0 --- /dev/null +++ b/src/app/api/dev/users/route.ts @@ -0,0 +1,276 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link"; +import { validateUsername } from "@/auth/password"; +import { SYSTEM_ROLES } from "@/auth/roles"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { USER_STATUSES } from "@/db/schema"; +import { hasEventUploads } from "@/db/events"; +import { + countOtherActiveAdmins, + createUser, + credentialTaken, + deleteUser, + getUserById, + hasAssignmentHistory, + listUsersForAdmin, + updateUser, +} from "@/db/users"; +import { isActiveAdmin, removalPlan, wouldLeaveNoAdmin } from "@/domain/users"; +import { sendWelcomeEmail } from "@/lib/welcome-email"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const json = (payload: unknown, status = 200) => + new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS }); + +const bad = (message: string) => json({ error: message }, 400); +const conflict = (message: string) => json({ error: message }, 409); + +const userCreateSchema = z.object({ + email: z.string().email(), + username: z.string().min(1).max(100).optional(), + firstName: z.string().min(1).max(80), + lastName: z.string().max(80).optional(), + displayName: z.string().max(120).nullable().optional(), + phoneE164: z.string().max(32).nullable().optional(), + systemRole: z.enum(SYSTEM_ROLES), + status: z.enum(USER_STATUSES).optional(), + timezone: z.string().min(1).max(64).optional(), + emergencyContact: z.string().max(200).nullable().optional(), + notes: z.string().max(2000).nullable().optional(), +}); + +const userPatchSchema = z.object({ + id: z.string().min(1), + email: z.string().email().optional(), + username: z.string().min(1).max(100).optional(), + firstName: z.string().min(1).max(80).optional(), + lastName: z.string().max(80).optional(), + displayName: z.string().max(120).nullable().optional(), + phoneE164: z.string().max(32).nullable().optional(), + systemRole: z.enum(SYSTEM_ROLES).optional(), + status: z.enum(USER_STATUSES).optional(), + timezone: z.string().min(1).max(64).optional(), + emergencyContact: z.string().max(200).nullable().optional(), + notes: z.string().max(2000).nullable().optional(), + /** Convenience flag: true sets `deactivated_at`, false clears it. */ + deactivated: z.boolean().optional(), +}); + +async function readBody(req: NextRequest) { + try { + return await req.json(); + } catch { + return null; + } +} + +/** Walk the cause chain for a Postgres SQLSTATE (pg nests it under `cause`). */ +function pgCode(err: unknown): string | undefined { + let node = err as { code?: string; cause?: unknown } | null; + while (node) { + if (typeof node.code === "string") return node.code; + node = (node.cause as { code?: string; cause?: unknown } | null) ?? null; + } + return undefined; +} + +/** + * User administration (admin-only, `users.manage`). + * + * GET -> { users } every account, full editable record + * POST -> { user, url, welcome } create (active, or pending approval) + * PATCH -> { user } edit any field / deactivate + * DELETE ?id= -> { ok } hard delete when the person has no + * scheduling history + * + * Every mutation writes an audit row. Two safety rules live in + * `src/domain/users.ts` and are enforced here: the last active admin can never + * be demoted, deactivated or deleted, and someone who has served is + * deactivated rather than deleted so past weeks stay readable. + */ +export const GET = async () => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + return json({ users: await listUsersForAdmin() }); +}; + +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + const parsed = userCreateSchema.safeParse(await readBody(req)); + if (!parsed.success) return bad(parsed.error.message); + + if (parsed.data.username) { + const usernameError = validateUsername(parsed.data.username); + if (usernameError) return bad(usernameError); + if (await credentialTaken(parsed.data.username)) { + return conflict("that username is already in use"); + } + } + + try { + const user = await createUser(parsed.data); + await writeAudit(db, { + actorId: gate.id, + action: "user.created", + entityType: "user", + entityId: user.id, + after: { + email: user.email, + systemRole: user.systemRole, + status: user.status, + }, + }); + + // Hand the admin a sign-in link, exactly like the invite flow does. The + // link only works once the account is active. + const token = await signMagicToken(user.email); + const origin = requestOrigin(req) || APP_ORIGIN; + const url = `${origin}/api/dev/complete?token=${encodeURIComponent( + token, + )}&email=${encodeURIComponent(user.email)}`; + + // A new active account gets its sign-in details by email. Pending accounts + // are mailed when they are approved, when the link can actually work. + const welcome = + user.status === "active" && user.deactivatedAt === null + ? await sendWelcomeEmail(user, url) + : null; + + return json({ user, url, welcome }, 201); + } catch (err) { + if (pgCode(err) === "23505") { + return conflict("a user with this email already exists"); + } + return json({ error: "failed to create user" }, 500); + } +}; + +export const PATCH = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + const parsed = userPatchSchema.safeParse(await readBody(req)); + if (!parsed.success) return bad(parsed.error.message); + + const { id, deactivated, ...fields } = parsed.data; + const before = await getUserById(id); + if (!before) return json({ error: "unknown user" }, 404); + + if (fields.username !== undefined) { + const usernameError = validateUsername(fields.username); + if (usernameError) return bad(usernameError); + if (await credentialTaken(fields.username, id)) { + return conflict("that username is already in use"); + } + } + if (fields.email !== undefined && fields.email !== before.email) { + if (await credentialTaken(fields.email, id)) { + return conflict("that email is already used as a username or email"); + } + } + + const nextRole = fields.systemRole ?? before.systemRole; + const nextStatus = fields.status ?? before.status; + const nextDeactivated = + deactivated === undefined ? before.deactivatedAt !== null : deactivated; + const nextEligible = nextStatus === "active" && !nextDeactivated; + + const otherActiveAdmins = await countOtherActiveAdmins(id); + if ( + wouldLeaveNoAdmin({ + targetIsActiveAdmin: isActiveAdmin(before), + nextRole, + nextEligible, + otherActiveAdmins, + }) + ) { + return conflict("the last active admin cannot be demoted or deactivated"); + } + + const patch = { + ...fields, + ...(deactivated === undefined + ? {} + : { deactivatedAt: deactivated ? new Date() : null }), + }; + + try { + const user = await updateUser(id, patch); + if (!user) return json({ error: "unknown user" }, 404); + + await writeAudit(db, { + actorId: gate.id, + action: "user.updated", + entityType: "user", + entityId: id, + before: { + email: before.email, + systemRole: before.systemRole, + status: before.status, + deactivated: before.deactivatedAt !== null, + }, + after: { + email: user.email, + systemRole: user.systemRole, + status: user.status, + deactivated: user.deactivatedAt !== null, + }, + }); + + return json({ user }); + } catch (err) { if (pgCode(err) === "23505") { + return conflict("a user with this email or username already exists"); + } + return json({ error: "failed to update user" }, 500); + } +}; + +export const DELETE = async (req: NextRequest) => { + const gate = await gateOrUser("users.manage"); + if (gate instanceof Response) return gate; + + const id = req.nextUrl.searchParams.get("id"); + if (!id) return bad("an id is required"); + + const before = await getUserById(id); + if (!before) return json({ error: "unknown user" }, 404); + + if (isActiveAdmin(before) && (await countOtherActiveAdmins(id)) === 0) { + return conflict("the last active admin cannot be deleted"); + } + + const plan = removalPlan({ + hasAssignmentHistory: await hasAssignmentHistory(id), + hasEventUploads: await hasEventUploads(id), + }); + if (!plan.allowed) return conflict(plan.reason); + + try { + await deleteUser(id); + await writeAudit(db, { + actorId: gate.id, + action: "user.deleted", + entityType: "user", + entityId: id, + before: { + email: before.email, + systemRole: before.systemRole, + status: before.status, + }, + }); + return json({ ok: true }); + } catch (err) { + // Assignment/upload rows are ON DELETE RESTRICT; the checks above should + // have caught this, but the database is the last word. + if (pgCode(err) === "23503") { + return conflict("this person has history and cannot be deleted — deactivate them instead"); + } + return json({ error: "failed to delete user" }, 500); + } +}; diff --git a/src/app/api/events/[id]/archive/route.ts b/src/app/api/events/[id]/archive/route.ts new file mode 100644 index 0000000..ec9408f --- /dev/null +++ b/src/app/api/events/[id]/archive/route.ts @@ -0,0 +1,120 @@ +import { NextRequest } from "next/server"; +import { rm } from "node:fs/promises"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + deleteEvent, + getEventAccess, + listEventPhotosForArchive, +} from "@/db/events"; +import { listEventVideos } from "@/db/videos"; +import { eventVideoUploadDir } from "@/lib/event-videos"; +import { + checkArchiveDestination, + getStorageSettings, +} from "@/db/storage-settings"; +import { + archiveEventPhotos, + EventArchiveError, +} from "@/lib/event-nfs-archive"; +import { eventPhotoDir } from "@/lib/event-photos"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +/** + * POST /api/events/:id/archive + * + * Manager-only. Copies every original and saved edit to the configured NFS + * mount, writes a manifest, then deletes the database rows and the live upload + * directory. The event is only removed after the archive rename succeeds. + */ +export const POST = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + if (!access.canManage) { + return errorResponse(403, "only an event manager may archive this event"); + } + + const storage = await getStorageSettings(); + const status = await checkArchiveDestination(storage); + if (!status.ready) { + return errorResponse( + 409, + `${status.message} Configure the NFS archive in Settings first.`, + ); + } + + const photos = await listEventPhotosForArchive(id); + const videos = await listEventVideos(id); + let archived; + try { + archived = await archiveEventPhotos({ + eventId: id, + title: access.event.title, + startsAt: access.event.startsAt, + endsAt: access.event.endsAt, + location: access.event.location, + description: access.event.description, + archivePath: storage.archivePath, + archiveFolder: storage.archiveFolder, + nfsShare: storage.nfsShare, + photos, + }); + } catch (error) { + if (error instanceof EventArchiveError) { + return errorResponse(409, error.message); + } + console.error(`event ${id}: archive failed`, error); + return errorResponse(500, "the event could not be archived"); + } + + const deleted = await deleteEvent(id); + if (!deleted) { + return errorResponse( + 500, + "the archive was written, but the event rows could not be removed", + ); + } + + try { + await rm(eventPhotoDir(id), { recursive: true, force: true }); + await rm(eventVideoUploadDir(id), { recursive: true, force: true }); + } catch (error) { + console.error(`event ${id}: archived but live files remain`, error); + } + + await writeAudit(db, { + actorId: gate.id, + action: "event.archived", + entityType: "event", + entityId: id, + before: { + title: deleted.event.title, + startsAt: deleted.event.startsAt.toISOString(), + photoCount: deleted.photoCount, + videoCount: videos.length, + }, + after: { + archivePath: archived.archivePath, + nfsShare: storage.nfsShare || null, + files: archived.files, + bytes: archived.bytes, + deleted: true, + videoOriginalsKeptOnNfs: videos.length, + }, + }); + + return jsonResponse({ + ok: true, + archivePath: archived.archivePath, + files: archived.files, + bytes: archived.bytes, + }); +}; diff --git a/src/app/api/events/[id]/download/route.ts b/src/app/api/events/[id]/download/route.ts new file mode 100644 index 0000000..24fed56 --- /dev/null +++ b/src/app/api/events/[id]/download/route.ts @@ -0,0 +1,122 @@ +import { ZipArchive } from "archiver"; +import { NextRequest } from "next/server"; +import { stat } from "node:fs/promises"; +import { PassThrough, Readable } from "node:stream"; +import { gateSession } from "@/auth/api"; +import { getEventAccess, listEventPhotosForArchive } from "@/db/events"; +import { assignArchivePaths, eventArchiveFilename } from "@/lib/event-archive"; +import { + editedPhotoFilename, + eventPhotoPath, + photoContentDisposition, +} from "@/lib/event-photos"; +import { errorResponse } from "@/lib/http"; + +/** + * GET /api/events/:id/download + * + * Streams every photo on the event as one ZIP, preserving folder names. Saved + * edits are included beside their originals as `-edited.jpg`. The + * archive is store-only: JPEGs and camera RAW files are already compressed, so + * deflating them would add CPU and latency without shrinking the download. + * Anyone assigned to the event (or a manager) can download it. + */ +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + + const photos = await listEventPhotosForArchive(id); + if (photos.length === 0) { + return errorResponse(404, "this event has no photos"); + } + + // Originals claim their names first, then generated edits join the same + // folder. A real upload named `photo-edited.jpg` therefore keeps its name and + // the generated version is numbered instead. + const entries: { + key: string; + folderName: string; + filename: string; + storedName: string; + }[] = []; + for (const photo of photos) { + entries.push({ + key: `${photo.id}:original`, + folderName: photo.folderName, + filename: photo.filename, + storedName: photo.storedName, + }); + } + for (const photo of photos) { + if (!photo.editedStoredName) continue; + entries.push({ + key: `${photo.id}:edited`, + folderName: photo.folderName, + filename: editedPhotoFilename(photo.filename), + storedName: photo.editedStoredName, + }); + } + + const names = assignArchivePaths( + entries.map((entry) => ({ + id: entry.key, + folderName: entry.folderName, + filename: entry.filename, + })), + ); + const available: { path: string; name: string }[] = []; + for (const entry of entries) { + const filePath = eventPhotoPath(entry.storedName); + try { + const info = await stat(filePath); + if (!info.isFile()) continue; + available.push({ path: filePath, name: names.get(entry.key)! }); + } catch { + console.warn(`event ${id}: skipping missing archive entry ${entry.key}`); + } + } + if (available.length === 0) { + return errorResponse(404, "the event photos are missing from storage"); + } + + // archiver uses readable-stream, so bridge through a core PassThrough before + // handing the response to the Web Streams API. + const output = new PassThrough(); + const archive = new ZipArchive({ store: true }); + archive.on("warning", (error) => { + console.warn(`event ${id}: zip warning`, error); + }); + archive.on("error", (error) => { + console.error(`event ${id}: zip failed`, error); + output.destroy(error); + }); + archive.pipe(output); + + for (const file of available) { + archive.file(file.path, { name: file.name }); + } + void archive.finalize().catch((error) => output.destroy(error)); + + return new Response( + Readable.toWeb(output) as unknown as ReadableStream, + { + status: 200, + headers: { + "content-type": "application/zip", + "content-disposition": photoContentDisposition( + eventArchiveFilename(access.event.title), + false, + ), + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }, + }, + ); +}; diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/edit/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/edit/route.ts new file mode 100644 index 0000000..c79246e --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/edit/route.ts @@ -0,0 +1,130 @@ +import { NextRequest } from "next/server"; +import { randomUUID } from "node:crypto"; +import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { gateSession } from "@/auth/api"; +import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events"; +import { + editedPhotoFilename, + editedStoredNameForEventPhoto, + eventPhotoPath, + isEditableEventPhoto, +} from "@/lib/event-photos"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { normalizePhotoAdjustments } from "@/lib/photo-adjustments"; +import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; + +const MAX_EDIT_BODY_BYTES = 32 * 1024; + +/** + * POST /api/events/:id/folders/:folderId/photos/:photoId/edit + * Body: { adjustments: PhotoAdjustments } + * + * Saves the recipe and renders a fresh full-resolution JPEG beside the + * original. The original file is never changed, so an edit can always be + * reopened and adjusted again. + */ +export const POST = async ( + req: NextRequest, + { + params, + }: { + params: Promise<{ id: string; folderId: string; photoId: string }>; + }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + if (Number(req.headers.get("content-length") ?? 0) > MAX_EDIT_BODY_BYTES) { + return errorResponse(413, "the edit settings are too large"); + } + + const { id, folderId, photoId } = await params; + const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole); + if ( + !access || + access.photo.folderId !== folderId || + access.eventId !== id + ) { + return errorResponse(404, "unknown photo"); + } + if (!isEditableEventPhoto(access.photo.filename)) { + return errorResponse(415, "this photo format cannot be edited"); + } + + const body = (await req.json().catch(() => null)) as + | { adjustments?: unknown } + | null; + const adjustments = normalizePhotoAdjustments(body?.adjustments); + if (!adjustments) { + return errorResponse(400, "invalid photo adjustments"); + } + + const sourcePath = eventPhotoPath(access.photo.storedName); + try { + const source = await stat(sourcePath); + if (!source.isFile()) return errorResponse(404, "the file is missing from storage"); + } catch { + return errorResponse(404, "the file is missing from storage"); + } + + const editedStoredName = editedStoredNameForEventPhoto( + access.eventId, + access.photo.id, + ); + const editedPath = eventPhotoPath(editedStoredName); + + let rendered: Awaited>; + try { + rendered = await renderPhotoJpeg({ + filePath: sourcePath, + kind: access.photo.kind, + adjustments, + }); + } catch (error) { + if (error instanceof PhotoRenderError) { + return errorResponse(422, error.message); + } + console.error("photo edit render failed", error); + return errorResponse(500, "the edited JPEG could not be generated"); + } + + await mkdir(path.dirname(editedPath), { recursive: true }); + const temporary = `${editedPath}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, rendered.data); + await rename(temporary, editedPath); + } catch (error) { + await unlink(temporary).catch(() => undefined); + console.error("photo edit write failed", error); + return errorResponse(500, "the edited JPEG could not be saved"); + } + + try { + const updated = await updateEventPhotoEdit({ + photoId: access.photo.id, + editJson: JSON.stringify(adjustments), + editedStoredName, + editedSizeBytes: rendered.data.byteLength, + editedBy: gate.id, + }); + if (!updated) { + await unlink(editedPath).catch(() => undefined); + return errorResponse(404, "unknown photo"); + } + + return jsonResponse({ + ok: true, + adjustments, + editedFilename: editedPhotoFilename(access.photo.filename), + editedSizeBytes: rendered.data.byteLength, + editedAt: updated.editedAt, + width: rendered.width, + height: rendered.height, + }); + } catch (error) { + await unlink(editedPath).catch(() => undefined); + console.error("photo edit metadata failed", error); + return errorResponse(500, "the edit was rendered but could not be recorded"); + } +}; diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/export/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/export/route.ts new file mode 100644 index 0000000..e1a5b48 --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/export/route.ts @@ -0,0 +1,99 @@ +import { NextRequest } from "next/server"; +import { stat } from "node:fs/promises"; +import sharp from "sharp"; +import { gateSession } from "@/auth/api"; +import { getEventPhotoAccess } from "@/db/events"; +import { + eventPhotoPath, + photoContentDisposition, +} from "@/lib/event-photos"; +import { + photoExportFilename, + photoExportPresetFor, +} from "@/lib/photo-exports"; +import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; +import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; +import { errorResponse } from "@/lib/http"; + +/** + * GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048 + * + * Renders a delivery-sized JPEG from the saved edit. The saved full-resolution + * JPEG is resized rather than re-decoded from RAW; if it is missing, the + * original is rendered from the stored recipe as a fallback. Only the four + * delivery sizes advertised by the editor are accepted. + */ +export const GET = async ( + req: NextRequest, + { + params, + }: { + params: Promise<{ id: string; folderId: string; photoId: string }>; + }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, folderId, photoId } = await params; + const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole); + if (!access || access.photo.folderId !== folderId || access.eventId !== id) { + return errorResponse(404, "unknown photo"); + } + + const preset = photoExportPresetFor(req.nextUrl.searchParams.get("size")); + if (!preset) { + return errorResponse(400, "unknown export size"); + } + + let data: Buffer; + try { + if (access.photo.editedStoredName) { + const editedPath = eventPhotoPath(access.photo.editedStoredName); + const info = await stat(editedPath); + if (!info.isFile()) throw new Error("missing edit"); + data = await sharp(editedPath) + .resize({ + width: preset.maxDimension, + height: preset.maxDimension, + fit: "inside", + withoutEnlargement: true, + }) + .jpeg({ quality: 90, mozjpeg: true, chromaSubsampling: "4:4:4" }) + .toBuffer(); + } else if (access.photo.editJson) { + const rendered = await renderPhotoJpeg({ + filePath: eventPhotoPath(access.photo.storedName), + kind: access.photo.kind, + adjustments: parseStoredPhotoAdjustments(access.photo.editJson), + maxDimension: preset.maxDimension, + }); + data = rendered.data; + } else { + return errorResponse( + 409, + "Save an edit before exporting a delivery-sized JPEG.", + ); + } + } catch (error) { + if (error instanceof PhotoRenderError) { + return errorResponse(422, error.message); + } + console.error("photo export failed", error); + return errorResponse(500, "the exported JPEG could not be generated"); + } + + return new Response(new Uint8Array(data), { + status: 200, + headers: { + "content-type": "image/jpeg", + "content-length": String(data.byteLength), + "content-disposition": photoContentDisposition( + photoExportFilename(access.photo.filename, preset), + false, + ), + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + "content-security-policy": "default-src 'none'; sandbox", + }, + }); +}; diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/preview/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/preview/route.ts new file mode 100644 index 0000000..1f09c01 --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/preview/route.ts @@ -0,0 +1,102 @@ +import { NextRequest } from "next/server"; +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { gateSession } from "@/auth/api"; +import { getEventPhotoAccess } from "@/db/events"; +import { + eventPhotoPath, + isEditableEventPhoto, + previewStoredNameForEventPhoto, +} from "@/lib/event-photos"; +import { errorResponse } from "@/lib/http"; +import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; +import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; + +/** + * GET /api/events/:id/folders/:folderId/photos/:photoId/preview + * + * A browser-sized JPEG of the untouched original. RAW files are decoded through + * LibRaw; the result is cached on disk because the original never changes. + * The client applies the live adjustment LUT to this proxy. + */ +export const GET = async ( + _req: NextRequest, + { + params, + }: { + params: Promise<{ id: string; folderId: string; photoId: string }>; + }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, folderId, photoId } = await params; + const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole); + if ( + !access || + access.photo.folderId !== folderId || + access.eventId !== id + ) { + return errorResponse(404, "unknown photo"); + } + if (!isEditableEventPhoto(access.photo.filename)) { + return errorResponse(415, "this photo format cannot be previewed in the editor"); + } + + const sourcePath = eventPhotoPath(access.photo.storedName); + try { + const source = await stat(sourcePath); + if (!source.isFile()) return errorResponse(404, "the file is missing from storage"); + } catch { + return errorResponse(404, "the file is missing from storage"); + } + + const previewPath = eventPhotoPath( + previewStoredNameForEventPhoto(access.eventId, access.photo.id), + ); + + try { + const cached = await stat(previewPath); + if (cached.isFile() && cached.size > 0) { + return imageResponse(await readFile(previewPath)); + } + } catch { + // Not generated yet. + } + + try { + const rendered = await renderPhotoJpeg({ + filePath: sourcePath, + kind: access.photo.kind, + adjustments: defaultPhotoAdjustments(), + maxDimension: 1800, + }); + + await mkdir(path.dirname(previewPath), { recursive: true }); + const temporary = `${previewPath}.${randomUUID()}.tmp`; + await writeFile(temporary, rendered.data); + await rename(temporary, previewPath); + return imageResponse(rendered.data); + } catch (error) { + if (error instanceof PhotoRenderError) { + return errorResponse(422, error.message); + } + console.error("photo preview failed", error); + return errorResponse(500, "the preview could not be generated"); + } +}; + +function imageResponse(data: Buffer): Response { + return new Response(new Uint8Array(data), { + status: 200, + headers: { + "content-type": "image/jpeg", + "content-length": String(data.byteLength), + "content-disposition": "inline", + "cache-control": "private, max-age=86400, immutable", + "x-content-type-options": "nosniff", + "content-security-policy": "default-src 'none'; sandbox", + }, + }); +} diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts new file mode 100644 index 0000000..049331e --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts @@ -0,0 +1,125 @@ +import { NextRequest } from "next/server"; +import { createReadStream } from "node:fs"; +import { stat, unlink } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { gateSession } from "@/auth/api"; +import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events"; +import { canDeleteEventPhoto } from "@/lib/event-access"; +import { + editedPhotoFilename, + eventPhotoPath, + isBrowserRenderablePhoto, + photoContentDisposition, +} from "@/lib/event-photos"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +/** + * GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited] + * + * Streams the original bytes to anyone assigned to the event (or a manager). + * `variant=edited` serves the generated full-resolution JPEG instead, so the + * gallery can show the saved look without replacing the original. RAW files + * always download; `?download=1` forces an attachment for JPEGs too. + */ +export const GET = async ( + req: NextRequest, + { + params, + }: { + params: Promise<{ id: string; folderId: string; photoId: string }>; + }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, folderId, photoId } = await params; + const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole); + if ( + !access || + access.photo.folderId !== folderId || + access.eventId !== id + ) { + return errorResponse(404, "unknown photo"); + } + + const wantsEdited = req.nextUrl.searchParams.get("variant") === "edited"; + if (wantsEdited && !access.photo.editedStoredName) { + return errorResponse(404, "this photo has no saved edit"); + } + + const filePath = eventPhotoPath( + wantsEdited + ? access.photo.editedStoredName! + : access.photo.storedName, + ); + const filename = wantsEdited + ? editedPhotoFilename(access.photo.filename) + : access.photo.filename; + let size: number; + try { + size = (await stat(filePath)).size; + } catch { + return errorResponse(404, "the file is missing from storage"); + } + + const inline = + req.nextUrl.searchParams.get("download") !== "1" && + (wantsEdited || isBrowserRenderablePhoto(access.photo.filename)); + + const stream = createReadStream(filePath); + return new Response( + Readable.toWeb(stream) as unknown as ReadableStream, + { + status: 200, + headers: { + "content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType, + "content-length": String(size), + "content-disposition": photoContentDisposition(filename, inline), + "cache-control": "private, max-age=0, must-revalidate", + "x-content-type-options": "nosniff", + "content-security-policy": "default-src 'none'; sandbox", + }, + }, + ); +}; + +/** DELETE — the uploader or an event manager can remove a photo. */ +export const DELETE = async ( + _req: NextRequest, + { + params, + }: { + params: Promise<{ id: string; folderId: string; photoId: string }>; + }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, folderId, photoId } = await params; + const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole); + if ( + !access || + access.photo.folderId !== folderId || + access.eventId !== id + ) { + return errorResponse(404, "unknown photo"); + } + if ( + !canDeleteEventPhoto({ + role: gate.systemRole, + userId: gate.id, + uploaderId: access.photo.uploaderId, + }) + ) { + return errorResponse(403, "only the uploader or a coordinator may delete this photo"); + } + + await deleteEventPhoto(photoId); + await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined); + if (access.photo.editedStoredName) { + await unlink(eventPhotoPath(access.photo.editedStoredName)).catch( + () => undefined, + ); + } + return jsonResponse({ ok: true }); +}; diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts new file mode 100644 index 0000000..535c381 --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts @@ -0,0 +1,156 @@ +import { NextRequest } from "next/server"; +import { createHash } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { mkdir, unlink } from "node:fs/promises"; +import path from "node:path"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { gateSession } from "@/auth/api"; +import { + addEventPhoto, + findEventPhotoByChecksum, + getEventFolderAccess, + isUniqueViolation, +} from "@/db/events"; +import { + MAX_EVENT_PHOTO_BYTES, + eventPhotoKindFor, + eventPhotoMimeFor, + eventPhotoPath, + sanitizePhotoFilename, + storedNameForEventPhoto, +} from "@/lib/event-photos"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { uuidv7 } from "@/lib/uuid"; + +class PhotoTooLarge extends Error {} + +function publicPhoto(photo: { + id: string; + folderId: string; + filename: string; + mimeType: string; + sizeBytes: number; + kind: "raw" | "image"; + createdAt: Date; +}) { + return { + id: photo.id, + folderId: photo.folderId, + filename: photo.filename, + mimeType: photo.mimeType, + sizeBytes: photo.sizeBytes, + kind: photo.kind, + createdAt: photo.createdAt, + }; +} + +/** + * POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3 + * + * A single photo is the raw request body (not multipart), so a 100 MB RAW file + * streams straight to disk instead of being buffered in memory. The filename is + * passed as a query parameter because headers cannot carry arbitrary Unicode. + * The SHA-256 is computed while streaming and dedupes a re-upload per folder. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string; folderId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, folderId } = await params; + const access = await getEventFolderAccess(folderId, gate.id, gate.systemRole); + if (!access || access.eventId !== id) { + return errorResponse(404, "unknown folder"); + } + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + + const suppliedName = req.nextUrl.searchParams.get("name"); + if (!suppliedName) return errorResponse(400, "a filename is required"); + const filename = sanitizePhotoFilename(suppliedName); + const kind = eventPhotoKindFor(filename); + if (!kind) { + return errorResponse( + 415, + "only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)", + ); + } + + const declaredLength = Number(req.headers.get("content-length") ?? 0); + if (declaredLength > MAX_EVENT_PHOTO_BYTES) { + return errorResponse(413, "that photo is larger than 200 MB"); + } + if (!req.body) return errorResponse(400, "a file body is required"); + + const photoId = uuidv7(); + const storedName = storedNameForEventPhoto(id, photoId, filename); + const destination = eventPhotoPath(storedName); + await mkdir(path.dirname(destination), { recursive: true }); + + const hash = createHash("sha256"); + let size = 0; + const meter = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + size += chunk.length; + if (size > MAX_EVENT_PHOTO_BYTES) { + callback(new PhotoTooLarge()); + return; + } + hash.update(chunk); + callback(null, chunk); + }, + }); + + try { + await pipeline( + Readable.from(req.body as unknown as AsyncIterable), + meter, + createWriteStream(destination, { flags: "wx" }), + ); + } catch (error) { + await unlink(destination).catch(() => undefined); + if (error instanceof PhotoTooLarge) { + return errorResponse(413, "that photo is larger than 200 MB"); + } + return errorResponse(500, "the upload did not complete"); + } + + if (size === 0) { + await unlink(destination).catch(() => undefined); + return errorResponse(400, "the uploaded file was empty"); + } + + const checksumSha256 = hash.digest("hex"); + const existing = await findEventPhotoByChecksum(folderId, checksumSha256); + if (existing) { + await unlink(destination).catch(() => undefined); + return jsonResponse({ photo: publicPhoto(existing), duplicate: true }); + } + + try { + const photo = await addEventPhoto({ + folderId, + uploaderId: gate.id, + filename, + mimeType: eventPhotoMimeFor(filename), + sizeBytes: size, + storedName, + checksumSha256, + kind, + }); + return jsonResponse({ photo: publicPhoto(photo) }, 201); + } catch (error) { + await unlink(destination).catch(() => undefined); + if (isUniqueViolation(error)) { + const raced = await findEventPhotoByChecksum(folderId, checksumSha256); + if (raced) { + return jsonResponse({ photo: publicPhoto(raced), duplicate: true }); + } + } + throw error; + } +}; diff --git a/src/app/api/events/[id]/folders/route.ts b/src/app/api/events/[id]/folders/route.ts new file mode 100644 index 0000000..c1c241e --- /dev/null +++ b/src/app/api/events/[id]/folders/route.ts @@ -0,0 +1,53 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { + createEventFolder, + getEventAccess, + isUniqueViolation, +} from "@/db/events"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const folderSchema = z.object({ + name: z.string().trim().min(1).max(80), + kind: z.enum(["originals", "edited", "mixed"]).optional(), +}); + +/** + * POST /api/events/:id/folders — create a folder inside an event. + * Any assigned photographer, coordinator or admin may create one. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + + const parsed = folderSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid folder"); + } + + try { + const folder = await createEventFolder({ + eventId: id, + name: parsed.data.name, + kind: parsed.data.kind ?? "originals", + createdBy: gate.id, + }); + return jsonResponse({ folder }, 201); + } catch (error) { + if (isUniqueViolation(error)) { + return errorResponse(409, "a folder with that name already exists"); + } + throw error; + } +}; diff --git a/src/app/api/events/[id]/photographers/route.ts b/src/app/api/events/[id]/photographers/route.ts new file mode 100644 index 0000000..8e4d7a4 --- /dev/null +++ b/src/app/api/events/[id]/photographers/route.ts @@ -0,0 +1,67 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { + assignEventPhotographer, + getEventAccess, + removeEventPhotographer, +} from "@/db/events"; +import { EVENT_PHOTOGRAPHER_ROLES } from "@/db/schema"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const assignmentSchema = z.object({ + userId: z.string().min(1), + role: z.enum(EVENT_PHOTOGRAPHER_ROLES).optional(), +}); + +/** + * POST /api/events/:id/photographers — assign a photographer/editor. + * DELETE ?userId= — remove them. Managers only (`schedule.publish`). + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + + const parsed = assignmentSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid assignment"); + } + + const assignment = await assignEventPhotographer({ + eventId: id, + userId: parsed.data.userId, + role: parsed.data.role ?? "photographer", + assignedBy: gate.id, + }); + if (!assignment) { + return errorResponse(400, "that account is not an active team member"); + } + + return jsonResponse({ assignment }, 201); +}; + +export const DELETE = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + + const userId = req.nextUrl.searchParams.get("userId"); + if (!userId) return errorResponse(400, "a userId is required"); + + const removed = await removeEventPhotographer(id, userId); + if (!removed) return errorResponse(404, "that person is not assigned"); + return jsonResponse({ ok: true }); +}; diff --git a/src/app/api/events/[id]/route.ts b/src/app/api/events/[id]/route.ts new file mode 100644 index 0000000..186a7ac --- /dev/null +++ b/src/app/api/events/[id]/route.ts @@ -0,0 +1,77 @@ +import { NextRequest } from "next/server"; +import { rm } from "node:fs/promises"; +import { gateOrUser } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { deleteEvent, getEventAccess } from "@/db/events"; +import { listEventVideos } from "@/db/videos"; +import { getStorageSettings } from "@/db/storage-settings"; +import { eventPhotoDir } from "@/lib/event-photos"; +import { + eventVideoArchiveDir, + eventVideoUploadDir, +} from "@/lib/event-videos"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +/** + * DELETE /api/events/:id — manager-only. Removes the event, its folders/photos + * and the event's directory on the uploads volume. The database cascade commits + * first; bytes are then removed best-effort so a storage hiccup cannot leave a + * half-deleted event row. Any orphaned bytes are reported in the server log. + */ +export const DELETE = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + const videos = await listEventVideos(id); + + const deleted = await deleteEvent(id); + if (!deleted) return errorResponse(404, "unknown event"); + + try { + await rm(eventPhotoDir(id), { recursive: true, force: true }); + await rm(eventVideoUploadDir(id), { recursive: true, force: true }); + } catch (error) { + console.error(`event ${id}: database deleted but files remain`, error); + } + + // Video originals are the largest files; remove each one from the archive + // after the cascade has removed its row, so a deletion cannot orphan GBs. + try { + const storage = await getStorageSettings(); + for (const video of videos) { + await rm( + eventVideoArchiveDir( + storage.archivePath, + video.archiveFolder, + id, + video.id, + ), + { recursive: true, force: true }, + ); + } + } catch (error) { + console.error(`event ${id}: NFS video originals were not removed`, error); + } + + await writeAudit(db, { + actorId: gate.id, + action: "event.deleted", + entityType: "event", + entityId: id, + before: { + title: deleted.event.title, + startsAt: deleted.event.startsAt.toISOString(), + photoCount: deleted.photoCount, + videoCount: videos.length, + }, + }); + + return jsonResponse({ ok: true }); +}; diff --git a/src/app/api/events/[id]/videos/[videoId]/edit/route.ts b/src/app/api/events/[id]/videos/[videoId]/edit/route.ts new file mode 100644 index 0000000..6964647 --- /dev/null +++ b/src/app/api/events/[id]/videos/[videoId]/edit/route.ts @@ -0,0 +1,152 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + getEventVideoAccess, + updateEventVideo, + type EventVideoPatch, +} from "@/db/videos"; +import { EVENT_VIDEO_VISIBILITIES } from "@/db/schema"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { processEventVideo } from "@/lib/video-processing"; +import { videoView } from "@/lib/video-view"; + +const MAX_BODY_BYTES = 64 * 1024; + +const editSchema = z.object({ + title: z.string().trim().min(1).max(200).optional(), + description: z.string().max(5000).nullable().optional(), + visibility: z.enum(EVENT_VIDEO_VISIBILITIES).optional(), + trimStartMs: z.number().int().min(0).optional(), + trimEndMs: z.number().int().min(0).nullable().optional(), +}); + +/** + * POST /api/events/:id/videos/:videoId/edit + * + * Metadata is saved immediately. A changed trim marks the video processing and + * re-renders the web MP4 with FFmpeg; the NFS original is never altered. Only a + * manager may publish a video as unlisted/public. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string; videoId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) { + return errorResponse(413, "the video edit is too large"); + } + + const { id, videoId } = await params; + const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole); + if (!access || access.video.eventId !== id) { + return errorResponse(404, "unknown video"); + } + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + + const parsed = editSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) { + return errorResponse( + 400, + parsed.error.issues[0]?.message ?? "invalid video edit", + ); + } + const body = parsed.data; + if (Object.keys(body).length === 0) { + return errorResponse(400, "no changes were supplied"); + } + if ( + body.visibility && + body.visibility !== "team" && + !access.canManage + ) { + return errorResponse( + 403, + "only a coordinator or admin can publish a video publicly", + ); + } + + const video = access.video; + const patch: EventVideoPatch = {}; + if (body.title !== undefined) patch.title = body.title; + if (body.description !== undefined) { + patch.description = body.description?.trim() || null; + } + if (body.visibility !== undefined) patch.visibility = body.visibility; + + let trimChanged = false; + if (body.trimStartMs !== undefined || body.trimEndMs !== undefined) { + if (!video.durationMs || video.durationMs <= 0) { + return errorResponse( + 409, + "this video is still being processed; wait until it is ready before trimming", + ); + } + const duration = video.durationMs; + const minimum = Math.min(1000, duration); + const currentEnd = video.trimEndMs ?? duration; + const requestedStart = body.trimStartMs ?? video.trimStartMs; + const requestedEnd = body.trimEndMs ?? currentEnd; + const start = Math.min( + Math.max(0, requestedStart), + Math.max(0, duration - minimum), + ); + const end = Math.min( + Math.max(requestedEnd, start + minimum), + duration, + ); + trimChanged = start !== video.trimStartMs || end !== currentEnd; + patch.trimStartMs = start; + patch.trimEndMs = end; + } + + if (trimChanged) { + patch.status = "processing"; + patch.errorMessage = null; + } + + const updated = await updateEventVideo(video.id, patch); + if (!updated) return errorResponse(404, "unknown video"); + + if (trimChanged) { + void processEventVideo(updated.id).catch((error) => { + console.error(`video ${updated.id}: background trim failed`, error); + }); + } + + await writeAudit(db, { + actorId: gate.id, + action: "video.edited", + entityType: "event_video", + entityId: video.id, + before: { + title: video.title, + visibility: video.visibility, + trimStartMs: video.trimStartMs, + trimEndMs: video.trimEndMs, + }, + after: { + title: updated.title, + visibility: updated.visibility, + trimStartMs: updated.trimStartMs, + trimEndMs: updated.trimEndMs, + processing: trimChanged, + }, + }); + + return jsonResponse({ + video: videoView({ + ...updated, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }), + canManage: access.canManage, + canContribute: access.canContribute, + }); +}; diff --git a/src/app/api/events/[id]/videos/[videoId]/original/route.ts b/src/app/api/events/[id]/videos/[videoId]/original/route.ts new file mode 100644 index 0000000..15f016e --- /dev/null +++ b/src/app/api/events/[id]/videos/[videoId]/original/route.ts @@ -0,0 +1,77 @@ +import { NextRequest } from "next/server"; +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { gateSession } from "@/auth/api"; +import { getStorageSettings } from "@/db/storage-settings"; +import { getEventVideoAccess } from "@/db/videos"; +import { + eventVideoArchivePath, + videoContentDisposition, +} from "@/lib/event-videos"; +import { errorResponse } from "@/lib/http"; +import { parseByteRange } from "@/lib/range"; + +/** Download the untouched camera original from the NFS archive. */ +export const GET = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string; videoId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, videoId } = await params; + const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole); + if (!access || access.video.eventId !== id) { + return errorResponse(404, "unknown video"); + } + + let filePath: string; + try { + const storage = await getStorageSettings(); + filePath = eventVideoArchivePath( + storage.archivePath, + access.video.archiveFolder, + access.video.originalStoredName, + ); + } catch { + return errorResponse(404, "the NFS archive is not configured"); + } + + const info = await stat(filePath).catch(() => null); + if (!info?.isFile()) { + return errorResponse(404, "the original video is missing from the NFS archive"); + } + + const range = parseByteRange(req.headers.get("range"), info.size); + if (range === "invalid") { + return new Response(null, { + status: 416, + headers: { "content-range": `bytes */${info.size}` }, + }); + } + const start = range?.start ?? 0; + const end = range?.end ?? info.size - 1; + const stream = createReadStream(filePath, { start, end }); + + return new Response( + Readable.toWeb(stream) as unknown as ReadableStream, + { + status: range ? 206 : 200, + headers: { + "content-type": access.video.mimeType, + "content-length": String(end - start + 1), + "accept-ranges": "bytes", + ...(range + ? { "content-range": `bytes ${start}-${end}/${info.size}` } + : {}), + "content-disposition": videoContentDisposition( + access.video.filename, + false, + ), + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }, + }, + ); +}; diff --git a/src/app/api/events/[id]/videos/[videoId]/process/route.ts b/src/app/api/events/[id]/videos/[videoId]/process/route.ts new file mode 100644 index 0000000..a02311a --- /dev/null +++ b/src/app/api/events/[id]/videos/[videoId]/process/route.ts @@ -0,0 +1,47 @@ +import { NextRequest } from "next/server"; +import { gateSession } from "@/auth/api"; +import { + getEventVideoAccess, + markVideoProcessing, +} from "@/db/videos"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { processEventVideo } from "@/lib/video-processing"; +import { videoView } from "@/lib/video-view"; + +/** Retry a failed encode; the NFS original is still intact. */ +export const POST = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string; videoId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, videoId } = await params; + const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole); + if (!access || access.video.eventId !== id) { + return errorResponse(404, "unknown video"); + } + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + if (access.video.status === "processing") { + return errorResponse(409, "this video is already processing"); + } + if (access.video.status === "ready") { + return errorResponse(409, "this video is already ready; save an edit to re-render it"); + } + + const updated = await markVideoProcessing(videoId); + if (!updated) return errorResponse(404, "unknown video"); + void processEventVideo(videoId).catch((error) => { + console.error(`video ${videoId}: retry failed`, error); + }); + + return jsonResponse({ + video: videoView({ + ...updated, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }), + }); +}; diff --git a/src/app/api/events/[id]/videos/[videoId]/route.ts b/src/app/api/events/[id]/videos/[videoId]/route.ts new file mode 100644 index 0000000..87f31a0 --- /dev/null +++ b/src/app/api/events/[id]/videos/[videoId]/route.ts @@ -0,0 +1,104 @@ +import { NextRequest } from "next/server"; +import { rm } from "node:fs/promises"; +import path from "node:path"; +import { gateSession } from "@/auth/api"; +import { db } from "@/db"; +import { writeAudit } from "@/db/audit"; +import { + deleteEventVideo, + getEventVideoAccess, +} from "@/db/videos"; +import { getStorageSettings } from "@/db/storage-settings"; +import { + eventVideoArchiveDir, + eventVideoUploadPath, + webStoredNameForEventVideo, +} from "@/lib/event-videos"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { videoView } from "@/lib/video-view"; + +/** GET /api/events/:id/videos/:videoId — metadata + processing status. */ +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string; videoId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, videoId } = await params; + const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole); + if (!access || access.video.eventId !== id) { + return errorResponse(404, "unknown video"); + } + + return jsonResponse({ + video: videoView({ + ...access.video, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }), + canManage: access.canManage, + canContribute: access.canContribute, + }); +}; + +/** DELETE — uploader or an event manager; removes NFS original + derivatives. */ +export const DELETE = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string; videoId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id, videoId } = await params; + const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole); + if (!access || access.video.eventId !== id) { + return errorResponse(404, "unknown video"); + } + if (!access.canManage && access.video.uploaderId !== gate.id) { + return errorResponse(403, "only the uploader or a coordinator may delete this video"); + } + + const removed = await deleteEventVideo(videoId); + if (!removed) return errorResponse(404, "unknown video"); + + const derivativeDir = path.dirname( + eventVideoUploadPath( + removed.webStoredName ?? + webStoredNameForEventVideo(removed.eventId, removed.id), + ), + ); + await rm(derivativeDir, { recursive: true, force: true }).catch((error) => { + console.error(`video ${videoId}: derivatives were not removed`, error); + }); + + try { + const storage = await getStorageSettings(); + await rm( + eventVideoArchiveDir( + storage.archivePath, + removed.archiveFolder, + removed.eventId, + removed.id, + ), + { recursive: true, force: true }, + ); + } catch (error) { + console.error(`video ${videoId}: NFS original was not removed`, error); + } + + await writeAudit(db, { + actorId: gate.id, + action: "video.deleted", + entityType: "event_video", + entityId: videoId, + before: { + eventId: removed.eventId, + title: removed.title, + filename: removed.filename, + sizeBytes: removed.sizeBytes, + }, + }); + + return jsonResponse({ ok: true }); +}; diff --git a/src/app/api/events/[id]/videos/chunk/route.ts b/src/app/api/events/[id]/videos/chunk/route.ts new file mode 100644 index 0000000..da1fd7a --- /dev/null +++ b/src/app/api/events/[id]/videos/chunk/route.ts @@ -0,0 +1,257 @@ +import { NextRequest } from "next/server"; +import { createWriteStream } from "node:fs"; +import { mkdir, stat, truncate, unlink } from "node:fs/promises"; +import path from "node:path"; +import { Readable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { gateSession } from "@/auth/api"; +import { getEventAccess } from "@/db/events"; +import { + checkArchiveDestination, + getStorageSettings, +} from "@/db/storage-settings"; +import { + EVENT_VIDEO_VISIBILITIES, + type EventVideoVisibility, +} from "@/db/schema"; +import { finalizeEventVideo, checksumFile } from "@/lib/event-video-finalize"; +import { + eventVideoArchivePath, + isAllowedEventVideo, + originalStoredNameForEventVideo, + sanitizeVideoFilename, +} from "@/lib/event-videos"; +import { uuidv7 } from "@/lib/uuid"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { + EVENT_VIDEO_CHUNK_BYTES, + MAX_EVENT_VIDEO_BYTES, + MAX_EVENT_VIDEO_LABEL, +} from "@/lib/video-limits"; +import { videoView } from "@/lib/video-view"; + +const UPLOAD_ID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +function integerParam(value: string | null): number | null { + if (!value || !/^\d+$/.test(value)) return null; + const parsed = Number(value); + return Number.isSafeInteger(parsed) ? parsed : null; +} + +function isMissing(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { code?: string }).code === "ENOENT" + ); +} + +/** + * POST /api/events/:id/videos/chunk + * ?uploadId=&offset=&size= + * &name=...&title=...&visibility=team + * + * Raw body, one slice of the file at a time. Cloudflare rejects bodies over + * 100 MB, so the browser sends 50 MB slices and this route appends them to the + * NFS temporary original. The final slice hashes the complete file, inserts the + * metadata row, and starts FFmpeg through the same finalizer as the single-shot + * upload route. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + + const uploadId = req.nextUrl.searchParams.get("uploadId") ?? ""; + if (!UPLOAD_ID_PATTERN.test(uploadId)) { + return errorResponse(400, "a valid upload id is required"); + } + + const offset = integerParam(req.nextUrl.searchParams.get("offset")); + const total = integerParam(req.nextUrl.searchParams.get("size")); + if (offset === null || total === null) { + return errorResponse(400, "the upload offset and total size are required"); + } + if (total <= 0 || total > MAX_EVENT_VIDEO_BYTES) { + return errorResponse( + 413, + `that video is larger than ${MAX_EVENT_VIDEO_LABEL}`, + ); + } + if (offset >= total) { + return errorResponse(400, "the upload offset is outside the video"); + } + + const declaredLength = Number(req.headers.get("content-length") ?? 0); + if (!Number.isSafeInteger(declaredLength) || declaredLength <= 0) { + return errorResponse(400, "the chunk has no content length"); + } + if (declaredLength > EVENT_VIDEO_CHUNK_BYTES) { + return errorResponse( + 413, + "upload chunks must be 50 MB or smaller", + ); + } + if (offset + declaredLength > total) { + return errorResponse(400, "the chunk extends past the end of the video"); + } + const isFinal = offset + declaredLength === total; + + const suppliedName = req.nextUrl.searchParams.get("name"); + if (!suppliedName) return errorResponse(400, "a filename is required"); + const filename = sanitizeVideoFilename(suppliedName); + if (!isAllowedEventVideo(filename)) { + return errorResponse( + 415, + "unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP", + ); + } + + const visibilityText = + req.nextUrl.searchParams.get("visibility") ?? "team"; + if ( + !EVENT_VIDEO_VISIBILITIES.includes( + visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number], + ) + ) { + return errorResponse(400, "invalid video visibility"); + } + const visibility = visibilityText as EventVideoVisibility; + if (visibility !== "team" && !access.canManage) { + return errorResponse( + 403, + "only a coordinator or admin can publish a video publicly", + ); + } + + const title = + (req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) || + path.parse(filename).name.slice(0, 200); + const description = + (req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) || + null; + + const storage = await getStorageSettings(); + const archiveStatus = await checkArchiveDestination(storage); + if (!archiveStatus.ready) { + return errorResponse( + 409, + `${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`, + ); + } + + // Stage under a client-scoped name, never under a final video id. The final + // id is generated by the server when the last chunk arrives, so a caller + // cannot overwrite another video's original by guessing its id. + const stagingDir = eventVideoArchivePath( + storage.archivePath, + storage.archiveFolder, + `videos/${id}/.uploads`, + ); + const temporary = path.join(stagingDir, `${uploadId}.upload`); + await mkdir(stagingDir, { recursive: true }); + + let existingSize = 0; + try { + existingSize = (await stat(temporary)).size; + } catch (error) { + if (!isMissing(error)) throw error; + } + if (existingSize !== offset) { + return errorResponse( + 409, + "the upload offset does not match the bytes already received; restart the upload", + "UPLOAD_OFFSET_MISMATCH", + ); + } + if (!req.body) return errorResponse(400, "a video body is required"); + + const writeStream = createWriteStream( + temporary, + existingSize === 0 + ? { flags: "w", mode: 0o640 } + : { flags: "r+", start: offset, mode: 0o640 }, + ); + + try { + await pipeline( + Readable.from(req.body as unknown as AsyncIterable), + writeStream, + ); + } catch (error) { + if (existingSize === 0) { + await unlink(temporary).catch(() => undefined); + } else { + await truncate(temporary, offset).catch(() => undefined); + } + console.error(`event ${id}: video chunk upload failed`, error); + return errorResponse(500, "the video chunk did not complete"); + } + + const written = (await stat(temporary)).size; + if (written !== offset + declaredLength) { + if (existingSize === 0) { + await unlink(temporary).catch(() => undefined); + } else { + await truncate(temporary, offset).catch(() => undefined); + } + return errorResponse( + 400, + "the video chunk was incomplete; restart the upload", + ); + } + + if (!isFinal) { + return jsonResponse({ complete: false, receivedBytes: written }); + } + + try { + const checksumSha256 = await checksumFile(temporary); + const videoId = uuidv7(); + const storedName = originalStoredNameForEventVideo(id, videoId, filename); + const destination = eventVideoArchivePath( + storage.archivePath, + storage.archiveFolder, + storedName, + ); + await mkdir(path.dirname(destination), { recursive: true }); + const result = await finalizeEventVideo({ + eventId: id, + videoId, + temporary, + destination, + checksumSha256, + sizeBytes: total, + filename, + title, + description, + originalStoredName: storedName, + archiveFolder: storage.archiveFolder, + visibility, + uploaderId: gate.id, + event: access.event, + }); + + return jsonResponse( + result.duplicate + ? { video: videoView(result.video), duplicate: true } + : { video: videoView(result.video) }, + result.duplicate ? 200 : 201, + ); + } catch (error) { + await unlink(temporary).catch(() => undefined); + console.error(`event ${id}: video finalization failed`, error); + return errorResponse(500, "the video could not be finalized"); + } +}; diff --git a/src/app/api/events/[id]/videos/route.ts b/src/app/api/events/[id]/videos/route.ts new file mode 100644 index 0000000..6f0b7cb --- /dev/null +++ b/src/app/api/events/[id]/videos/route.ts @@ -0,0 +1,213 @@ +import { NextRequest } from "next/server"; +import { createHash } from "node:crypto"; +import { createWriteStream } from "node:fs"; +import { mkdir, unlink } from "node:fs/promises"; +import path from "node:path"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { gateSession } from "@/auth/api"; +import { getEventAccess } from "@/db/events"; +import { listEventVideos } from "@/db/videos"; +import { checkArchiveDestination, getStorageSettings } from "@/db/storage-settings"; +import { + MAX_EVENT_VIDEO_BYTES, + eventVideoArchivePath, + isAllowedEventVideo, + originalStoredNameForEventVideo, + sanitizeVideoFilename, +} from "@/lib/event-videos"; +import { finalizeEventVideo } from "@/lib/event-video-finalize"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { uuidv7 } from "@/lib/uuid"; +import { videoView } from "@/lib/video-view"; +import { + EVENT_VIDEO_VISIBILITIES, + type EventVideoVisibility, +} from "@/db/schema"; + +class VideoTooLarge extends Error {} + +/** + * POST /api/events/:id/videos?name=service.mp4&title=Sunday&visibility=team + * + * Raw request body. The camera original streams straight to the NFS archive and + * is hashed while it writes, so a 4 GB file never sits in memory. The stored + * row starts as `processing`; FFmpeg creates the web MP4/poster in the + * background and the browser polls the video endpoint for readiness. + */ +export const POST = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + if (!access.canContribute) { + return errorResponse(403, "you are not assigned to this event"); + } + + const suppliedName = req.nextUrl.searchParams.get("name"); + if (!suppliedName) return errorResponse(400, "a filename is required"); + const filename = sanitizeVideoFilename(suppliedName); + if (!isAllowedEventVideo(filename)) { + return errorResponse( + 415, + "unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP", + ); + } + + const visibilityText = + req.nextUrl.searchParams.get("visibility") ?? "team"; + if ( + !EVENT_VIDEO_VISIBILITIES.includes( + visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number], + ) + ) { + return errorResponse(400, "invalid video visibility"); + } + const visibility = visibilityText as EventVideoVisibility; + if (visibility !== "team" && !access.canManage) { + return errorResponse( + 403, + "only a coordinator or admin can publish a video publicly", + ); + } + + const title = + (req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) || + path.parse(filename).name.slice(0, 200); + const description = + (req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) || + null; + + const declaredLength = Number(req.headers.get("content-length") ?? 0); + if (declaredLength > MAX_EVENT_VIDEO_BYTES) { + return errorResponse(413, "that video is larger than 4 GB"); + } + if (!req.body) return errorResponse(400, "a video body is required"); + + const storage = await getStorageSettings(); + const archiveStatus = await checkArchiveDestination(storage); + if (!archiveStatus.ready) { + return errorResponse( + 409, + `${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`, + ); + } + + const videoId = uuidv7(); + const storedName = originalStoredNameForEventVideo(id, videoId, filename); + const destination = eventVideoArchivePath( + storage.archivePath, + storage.archiveFolder, + storedName, + ); + await mkdir(path.dirname(destination), { recursive: true }); + const temporary = `${destination}.${uuidv7()}.upload`; + + const hash = createHash("sha256"); + let size = 0; + const meter = new Transform({ + transform(chunk: Buffer, _encoding, callback) { + size += chunk.length; + if (size > MAX_EVENT_VIDEO_BYTES) { + callback(new VideoTooLarge()); + return; + } + hash.update(chunk); + callback(null, chunk); + }, + }); + + try { + await pipeline( + Readable.from(req.body as unknown as AsyncIterable), + meter, + createWriteStream(temporary, { flags: "wx", mode: 0o640 }), + ); + } catch (error) { + await unlink(temporary).catch(() => undefined); + if (error instanceof VideoTooLarge) { + return errorResponse(413, "that video is larger than 4 GB"); + } + console.error(`event ${id}: video upload failed`, error); + return errorResponse(500, "the video upload did not complete"); + } + + if (size === 0) { + await unlink(temporary).catch(() => undefined); + return errorResponse(400, "the uploaded video was empty"); + } + + // Never accept a short body as an original. A proxy or middleware body limit + // used to truncate large uploads while still returning 201, which produced a + // corrupt NFS file and a video that could not be processed. + if (declaredLength > 0 && size !== declaredLength) { + await unlink(temporary).catch(() => undefined); + return errorResponse( + 400, + "the video upload did not complete; check your connection and try again", + ); + } + + const checksumSha256 = hash.digest("hex"); + + try { + const result = await finalizeEventVideo({ + eventId: id, + videoId, + temporary, + destination, + checksumSha256, + sizeBytes: size, + filename, + title, + description, + originalStoredName: storedName, + archiveFolder: storage.archiveFolder, + visibility, + uploaderId: gate.id, + event: access.event, + }); + + return jsonResponse( + result.duplicate + ? { video: videoView(result.video), duplicate: true } + : { video: videoView(result.video) }, + result.duplicate ? 200 : 201, + ); + } catch (error) { + await unlink(temporary).catch(() => undefined); + console.error(`event ${id}: video finalization failed`, error); + return errorResponse(500, "the video could not be finalized"); + } +}; + +/** GET /api/events/:id/videos — video list for one event. */ +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { id } = await params; + const access = await getEventAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown event"); + + const videos = await listEventVideos(id); + return jsonResponse({ + videos: videos.map((video) => + videoView({ + ...video, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }), + ), + canManage: access.canManage, + canContribute: access.canContribute, + }); +}; diff --git a/src/app/api/events/route.ts b/src/app/api/events/route.ts new file mode 100644 index 0000000..43a4464 --- /dev/null +++ b/src/app/api/events/route.ts @@ -0,0 +1,72 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser, gateSession } from "@/auth/api"; +import { createEvent, listEventsForUser } from "@/db/events"; +import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const LOCAL_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/; + +const createSchema = z.object({ + title: z.string().trim().min(1).max(200), + eventType: z.string().trim().min(1).max(50).optional(), + startsAtLocal: z.string().regex(LOCAL_DATE_TIME, "invalid start time"), + endsAtLocal: z + .string() + .regex(LOCAL_DATE_TIME, "invalid end time") + .nullable() + .optional(), + location: z.string().trim().max(300).nullable().optional(), + description: z.string().max(5000).nullable().optional(), +}); + +function localDate(value: string): Date { + const [date, time] = value.split("T"); + return localToUtc(date, time, CHURCH_TIMEZONE); +} + +/** GET /api/events — events the signed-in user may open. */ +export const GET = async () => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const events = await listEventsForUser(gate.id, gate.systemRole); + return jsonResponse({ events }); +}; + +/** + * POST /api/events — create an event (coordinator/admin). + * + * Times are sent as church-local wall clock (`YYYY-MM-DDTHH:mm`), so the server + * — not the browser's timezone — decides the UTC instant. + */ +export const POST = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const body = await req.json().catch(() => null); + const parsed = createSchema.safeParse(body); + if (!parsed.success) { + return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid event"); + } + + const startsAt = localDate(parsed.data.startsAtLocal); + const endsAt = parsed.data.endsAtLocal + ? localDate(parsed.data.endsAtLocal) + : null; + if (endsAt && endsAt <= startsAt) { + return errorResponse(400, "the end time must be after the start time"); + } + + const event = await createEvent({ + title: parsed.data.title, + eventType: parsed.data.eventType ?? "photoshoot", + startsAt, + endsAt, + location: parsed.data.location ?? null, + description: parsed.data.description ?? null, + createdBy: gate.id, + }); + + return jsonResponse({ event }, 201); +}; diff --git a/src/app/api/export/history/route.ts b/src/app/api/export/history/route.ts new file mode 100644 index 0000000..cd01683 --- /dev/null +++ b/src/app/api/export/history/route.ts @@ -0,0 +1,18 @@ +import { gateOrUser } from "@/auth/api"; +import { servingHistoryCsv } from "@/db/exports"; + +/** GET /api/export/history — completed / no-show assignments as CSV. */ +export const GET = async () => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const csv = await servingHistoryCsv(); + return new Response(csv, { + status: 200, + headers: { + "content-type": "text/csv; charset=utf-8", + "content-disposition": 'attachment; filename="serving-history.csv"', + "cache-control": "no-store", + }, + }); +}; diff --git a/src/app/api/export/schedule/route.ts b/src/app/api/export/schedule/route.ts new file mode 100644 index 0000000..a331caa --- /dev/null +++ b/src/app/api/export/schedule/route.ts @@ -0,0 +1,34 @@ +import { NextRequest } from "next/server"; +import { gateOrUser } from "@/auth/api"; +import { scheduleCsv } from "@/db/exports"; +import { addDaysISO, dateInTimezone, CHURCH_TIMEZONE } from "@/lib/tz"; + +/** + * GET /api/export/schedule?from=YYYY-MM-DD&to=YYYY-MM-DD + * Defaults to the next four weeks. CSV only — printing is a browser action. + */ +export const GET = async (req: NextRequest) => { + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + const today = dateInTimezone(new Date(), CHURCH_TIMEZONE); + const from = req.nextUrl.searchParams.get("from") ?? today; + const to = req.nextUrl.searchParams.get("to") ?? addDaysISO(from, 27); + + if (!/^\d{4}-\d{2}-\d{2}$/.test(from) || !/^\d{4}-\d{2}-\d{2}$/.test(to)) { + return new Response(JSON.stringify({ error: "invalid date" }), { + status: 400, + headers: { "content-type": "application/json" }, + }); + } + + const csv = await scheduleCsv(from, to); + return new Response(csv, { + status: 200, + headers: { + "content-type": "text/csv; charset=utf-8", + "content-disposition": `attachment; filename="schedule-${from}-to-${to}.csv"`, + "cache-control": "no-store", + }, + }); +}; diff --git a/src/app/api/media/[id]/poster/route.ts b/src/app/api/media/[id]/poster/route.ts new file mode 100644 index 0000000..f282ca5 --- /dev/null +++ b/src/app/api/media/[id]/poster/route.ts @@ -0,0 +1,57 @@ +import { NextRequest } from "next/server"; +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { gateSession } from "@/auth/api"; +import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos"; +import { eventVideoUploadPath } from "@/lib/event-videos"; +import { errorResponse } from "@/lib/http"; + +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const { id } = await params; + let video = await getPublicEventVideo(id); + let publicVideo = Boolean(video); + + if (!video) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + const access = await getEventVideoAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown video"); + video = { + ...access.video, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }; + publicVideo = false; + } + + if (!video.posterStoredName) { + return errorResponse(404, "this video has no poster yet"); + } + let filePath: string; + try { + filePath = eventVideoUploadPath(video.posterStoredName); + } catch { + return errorResponse(404, "unknown poster"); + } + const info = await stat(filePath).catch(() => null); + if (!info?.isFile()) return errorResponse(404, "the poster is missing"); + + const stream = createReadStream(filePath); + return new Response( + Readable.toWeb(stream) as unknown as ReadableStream, + { + headers: { + "content-type": "image/jpeg", + "content-length": String(info.size), + "cache-control": publicVideo + ? "public, max-age=86400" + : "private, max-age=0, must-revalidate", + "x-content-type-options": "nosniff", + }, + }, + ); +}; diff --git a/src/app/api/media/[id]/stream/route.ts b/src/app/api/media/[id]/stream/route.ts new file mode 100644 index 0000000..b33ef75 --- /dev/null +++ b/src/app/api/media/[id]/stream/route.ts @@ -0,0 +1,110 @@ +import { NextRequest } from "next/server"; +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import { Readable } from "node:stream"; +import { gateSession } from "@/auth/api"; +import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos"; +import { + eventVideoUploadPath, + sanitizeVideoFilename, + videoContentDisposition, + webRenditionStoredNameForEventVideo, +} from "@/lib/event-videos"; +import { errorResponse } from "@/lib/http"; +import { parseByteRange } from "@/lib/range"; + +/** + * GET /api/media/:id/stream + * + * Serves the processed web MP4 or a lower-resolution rendition via + * `?quality=720|480`. Public/unlisted ready videos need no session; team videos + * reuse event access. Byte ranges keep browser seeking and mobile social embeds + * working. + */ +export const GET = async ( + req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const { id } = await params; + let video = await getPublicEventVideo(id); + let publicVideo = Boolean(video); + + if (!video) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + const access = await getEventVideoAccess(id, gate.id, gate.systemRole); + if (!access) return errorResponse(404, "unknown video"); + video = { + ...access.video, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }; + publicVideo = false; + } + + if (video.status !== "ready" || !video.webStoredName) { + return errorResponse(409, "this video is still processing"); + } + + let filePath: string; + let info: Awaited> | null = null; + try { + filePath = eventVideoUploadPath(video.webStoredName); + info = await stat(filePath).catch(() => null); + + const quality = req.nextUrl.searchParams.get("quality"); + if ((quality === "720" || quality === "480") && info?.isFile()) { + const renditionPath = eventVideoUploadPath( + webRenditionStoredNameForEventVideo( + video.eventId, + video.id, + Number(quality), + ), + ); + const renditionInfo = await stat(renditionPath).catch(() => null); + if (renditionInfo?.isFile()) { + filePath = renditionPath; + info = renditionInfo; + } + } + } catch { + return errorResponse(404, "unknown video"); + } + if (!info?.isFile()) { + return errorResponse(404, "the processed video is missing"); + } + + const range = parseByteRange(req.headers.get("range"), info.size); + if (range === "invalid") { + return new Response(null, { + status: 416, + headers: { "content-range": `bytes */${info.size}` }, + }); + } + const start = range?.start ?? 0; + const end = range?.end ?? info.size - 1; + const stream = createReadStream(filePath, { start, end }); + + return new Response( + Readable.toWeb(stream) as unknown as ReadableStream, + { + status: range ? 206 : 200, + headers: { + "content-type": "video/mp4", + "content-length": String(end - start + 1), + "accept-ranges": "bytes", + ...(range + ? { "content-range": `bytes ${start}-${end}/${info.size}` } + : {}), + "content-disposition": videoContentDisposition( + `${sanitizeVideoFilename(video.title).replace(/\.mp4$/i, "")}.mp4`, + true, + ), + "cache-control": publicVideo + ? "public, max-age=3600" + : "private, max-age=0, must-revalidate", + "x-content-type-options": "nosniff", + }, + }, + ); +}; diff --git a/src/app/api/oembed/route.ts b/src/app/api/oembed/route.ts new file mode 100644 index 0000000..2d248b6 --- /dev/null +++ b/src/app/api/oembed/route.ts @@ -0,0 +1,55 @@ +import { NextRequest } from "next/server"; +import { getPublicEventVideo } from "@/db/videos"; +import { requestOrigin } from "@/auth/magic-link"; +import { errorResponse } from "@/lib/http"; +import { videoView } from "@/lib/video-view"; + +/** + * GET /api/oembed?url=https://host/watch/:id&format=json + * + * A standard oEmbed video response for WordPress, LMS pages, and other + * consumers that do not read Open Graph tags. Only public/unlisted ready videos + * are exposed. + */ +export const GET = async (req: NextRequest) => { + const rawUrl = req.nextUrl.searchParams.get("url"); + if (!rawUrl) return errorResponse(400, "a url parameter is required"); + + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + return errorResponse(400, "invalid url"); + } + const match = /^\/(?:watch|embed)\/([A-Za-z0-9_-]+)\/?$/.exec(parsed.pathname); + if (!match) return errorResponse(404, "no embeddable media at that url"); + + const video = await getPublicEventVideo(match[1]); + if (!video) return errorResponse(404, "no embeddable media at that url"); + + const origin = requestOrigin(req); + const view = videoView(video, origin); + const payload = { + version: "1.0", + type: "video", + provider_name: "Glenloch Baptist Church", + provider_url: origin, + title: video.title, + author_name: video.eventTitle, + url: view.watchUrl, + html: view.embedCode, + width: view.embedWidth, + height: view.embedHeight, + thumbnail_url: view.posterUrl, + thumbnail_width: Math.min(1280, video.width ?? 1280), + thumbnail_height: Math.min(720, video.height ?? 720), + }; + + return new Response(JSON.stringify(payload), { + headers: { + "content-type": "application/json; charset=utf-8", + "access-control-allow-origin": "*", + "cache-control": "public, max-age=300", + }, + }); +}; diff --git a/src/app/api/respond/route.ts b/src/app/api/respond/route.ts new file mode 100644 index 0000000..8204e73 --- /dev/null +++ b/src/app/api/respond/route.ts @@ -0,0 +1,117 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { clientIp } from "@/auth/api"; +import { RespondError, applyRespond } from "@/db/respond"; +import { verifyRespondToken } from "@/lib/respond"; +import { rateLimit } from "@/lib/rate-limit"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +const bodySchema = z.object({ + token: z.string().min(1), + action: z.enum(["confirm", "decline"]), +}); + +/** Map a refused respond action to its HTTP status. */ +function errorStatus(code: RespondError["code"]): number { + switch (code) { + case "already_used": + case "not_actionable": + return 409; + case "unknown_assignment": + return 404; + case "wrong_volunteer": + return 403; + } +} + +/** + * POST /api/respond — { token, action: "confirm" | "decline" } + * + * The no-login confirm/decline endpoint (ARCHITECTURE §5.6). The signed token + * carries the assignment, volunteer, action and `jti`; the `jti` is consumed + * exactly once. `GET /respond` renders the page and never mutates, so a link + * preview cannot accept a shift. + */ +export const POST = async (req: NextRequest) => { + let parsedBody: z.infer; + try { + const body = await req.json().catch(() => null); + const parsed = bodySchema.safeParse(body); + if (!parsed.success) { + return new Response( + JSON.stringify({ error: "a token and action are required" }), + { status: 400, headers: JSON_HEADERS }, + ); + } + parsedBody = parsed.data; + } catch { + return new Response(JSON.stringify({ error: "invalid body" }), { + status: 400, + headers: JSON_HEADERS, + }); + } + + // Public endpoint: cap attempts per IP so tokens cannot be brute-forced. + const limit = rateLimit(`respond:${clientIp(req)}`, 30, 60_000); + if (!limit.ok) { + return new Response( + JSON.stringify({ + error: "too many attempts; try again shortly", + code: "RATE_LIMITED", + }), + { + status: 429, + headers: { + ...JSON_HEADERS, + "retry-after": String(limit.retryAfterSeconds), + }, + }, + ); + } + + const payload = await verifyRespondToken(parsedBody.token); + if (!payload) { + return new Response( + JSON.stringify({ + error: "this link is invalid or has expired", + code: "invalid_token", + }), + { status: 400, headers: JSON_HEADERS }, + ); + } + if (payload.action !== parsedBody.action) { + return new Response( + JSON.stringify({ + error: "this link is for a different action", + code: "action_mismatch", + }), + { status: 400, headers: JSON_HEADERS }, + ); + } + + try { + const result = await applyRespond({ + assignmentId: payload.assignmentId, + userId: payload.userId, + action: payload.action, + jti: payload.jti, + }); + return new Response(JSON.stringify({ ok: true, ...result }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (e) { + if (e instanceof RespondError) { + return new Response( + JSON.stringify({ error: e.message, code: e.code }), + { status: errorStatus(e.code), headers: JSON_HEADERS }, + ); + } + const message = e instanceof Error ? e.message : "internal error"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/run-sheet/route.ts b/src/app/api/run-sheet/route.ts new file mode 100644 index 0000000..b5528f4 --- /dev/null +++ b/src/app/api/run-sheet/route.ts @@ -0,0 +1,165 @@ +import { NextRequest } from "next/server"; +import { z } from "zod"; +import { gateOrUser, gateSession } from "@/auth/api"; +import { + addChecklistItem, + addRunSheetItem, + deleteChecklistItem, + deleteRunSheetItem, + saveRunSheetHeader, + toggleChecklistItem, + updateRunSheetItem, +} from "@/db/runSheet"; + +const JSON_HEADERS = { "content-type": "application/json" }; +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: JSON_HEADERS }); + +const headerSchema = z.object({ + action: z.literal("save-header"), + instanceId: z.string().min(1), + speaker: z.string().max(200).nullable().optional(), + sermonTitle: z.string().max(300).nullable().optional(), + streamUrl: z.string().max(500).nullable().optional(), + slidesUrl: z.string().max(500).nullable().optional(), + notes: z.string().max(4000).nullable().optional(), +}); + +const itemAddSchema = z.object({ + action: z.literal("add-item"), + instanceId: z.string().min(1), + title: z.string().min(1).max(200), + timeLabel: z.string().max(20).nullable().optional(), + owner: z.string().max(120).nullable().optional(), + notes: z.string().max(1000).nullable().optional(), +}); + +const itemUpdateSchema = z.object({ + action: z.literal("update-item"), + id: z.string().min(1), + title: z.string().min(1).max(200).optional(), + timeLabel: z.string().max(20).nullable().optional(), + owner: z.string().max(120).nullable().optional(), + notes: z.string().max(1000).nullable().optional(), + sortOrder: z.number().int().optional(), +}); + +const itemDeleteSchema = z.object({ + action: z.literal("delete-item"), + id: z.string().min(1), +}); + +const checkToggleSchema = z.object({ + action: z.literal("toggle-check"), + id: z.string().min(1), + done: z.boolean(), +}); + +const checkAddSchema = z.object({ + action: z.literal("add-check"), + instanceId: z.string().min(1), + phase: z.enum(["pre", "post"]), + label: z.string().min(1).max(200), +}); + +const checkDeleteSchema = z.object({ + action: z.literal("delete-check"), + id: z.string().min(1), +}); + +const bodySchema = z.discriminatedUnion("action", [ + headerSchema, + itemAddSchema, + itemUpdateSchema, + itemDeleteSchema, + checkToggleSchema, + checkAddSchema, + checkDeleteSchema, +]); + +async function body(req: NextRequest): Promise { + try { + return await req.json(); + } catch { + return null; + } +} + +/** + * Run-sheet mutations. Anyone signed in can tick a checklist item (the team + * shares the Sunday checklist); editing the sheet, adding or deleting rows is a + * coordinator action. + */ +export const POST = async (req: NextRequest) => { + const parsed = bodySchema.safeParse(await body(req)); + if (!parsed.success) return json({ error: parsed.error.message }, 400); + + if (parsed.data.action === "toggle-check") { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + const row = await toggleChecklistItem( + parsed.data.id, + gate.id, + parsed.data.done, + ); + if (!row) return json({ error: "checklist item not found" }, 404); + return json({ ok: true, row }); + } + + const gate = await gateOrUser("schedule.publish"); + if (gate instanceof Response) return gate; + + switch (parsed.data.action) { + case "save-header": { + const data = parsed.data; + await saveRunSheetHeader(data.instanceId, gate.id, { + speaker: data.speaker, + sermonTitle: data.sermonTitle, + streamUrl: data.streamUrl, + slidesUrl: data.slidesUrl, + notes: data.notes, + }); + return json({ ok: true }); + } + case "add-item": { + const data = parsed.data; + const row = await addRunSheetItem(data.instanceId, { + title: data.title, + timeLabel: data.timeLabel, + owner: data.owner, + notes: data.notes, + }); + return json({ ok: true, row }, 201); + } + case "update-item": { + const data = parsed.data; + const row = await updateRunSheetItem(data.id, { + title: data.title, + timeLabel: data.timeLabel, + owner: data.owner, + notes: data.notes, + sortOrder: data.sortOrder, + }); + if (!row) return json({ error: "run sheet item not found" }, 404); + return json({ ok: true, row }); + } + case "delete-item": { + const deleted = await deleteRunSheetItem(parsed.data.id); + if (!deleted) return json({ error: "run sheet item not found" }, 404); + return json({ ok: true }); + } + case "add-check": { + const row = await addChecklistItem( + parsed.data.instanceId, + parsed.data.phase, + parsed.data.label, + ); + return json({ ok: true, row }, 201); + } + case "delete-check": { + const deleted = await deleteChecklistItem(parsed.data.id); + if (!deleted) return json({ error: "checklist item not found" }, 404); + return json({ ok: true }); + } + } +}; diff --git a/src/app/api/training/files/[id]/route.ts b/src/app/api/training/files/[id]/route.ts new file mode 100644 index 0000000..466dd7e --- /dev/null +++ b/src/app/api/training/files/[id]/route.ts @@ -0,0 +1,49 @@ +import { NextRequest } from "next/server"; +import { readFile } from "node:fs/promises"; +import { auth } from "@/auth/config"; +import { getResource } from "@/db/training"; +import { uploadPath } from "@/lib/uploads"; + +/** + * Serve a training attachment to a signed-in team member. + * + * GET /api/training/files/:id + * + * Files are private (no public/ directory), so authoring uploads cannot be + * fetched without a session. Content is served inline; the original filename is + * preserved for downloads. + */ +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) => { + const session = await auth(); + if (!session?.user) { + return new Response("Authentication required", { status: 401 }); + } + + const { id } = await params; + const resource = await getResource(id); + if (!resource) { + return new Response("Not found", { status: 404 }); + } + + try { + const data = await readFile(uploadPath(resource.storedName)); + const safeName = resource.filename.replaceAll('"', ""); + return new Response(new Uint8Array(data), { + status: 200, + headers: { + "content-type": resource.mimeType, + "content-length": String(data.length), + // Only images render inline; everything else is a download, so an + // uploaded HTML/SVG payload cannot execute in this origin. + "content-disposition": `${resource.mimeType.startsWith("image/") ? "inline" : "attachment"}; filename="${safeName}"; filename*=UTF-8''${encodeURIComponent(resource.filename)}`, + "cache-control": "private, max-age=0, must-revalidate", + "x-content-type-options": "nosniff", + }, + }); + } catch { + return new Response("Not found", { status: 404 }); + } +}; diff --git a/src/app/embed/[id]/page.tsx b/src/app/embed/[id]/page.tsx new file mode 100644 index 0000000..f307f9c --- /dev/null +++ b/src/app/embed/[id]/page.tsx @@ -0,0 +1,42 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { getPublicEventVideo } from "@/db/videos"; +import { mediaOrigin } from "@/lib/media-url"; +import { videoView } from "@/lib/video-view"; +import { availableRenditionHeights } from "@/lib/video-renditions"; +import { AdaptiveVideo } from "@/components/public/adaptive-video"; + +export const dynamic = "force-dynamic"; + +export const metadata: Metadata = { + robots: { index: false, follow: false }, + title: "Video", +}; + +/** Minimal iframe player. No app shell, no ads, no navigation. */ +export default async function EmbedPage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + const video = await getPublicEventVideo(id); + if (!video) notFound(); + + const origin = await mediaOrigin(); + const view = videoView(video, origin); + const renditions = await availableRenditionHeights(video); + + return ( +
+ +
+ ); +} diff --git a/src/app/globals.css b/src/app/globals.css index 6b30228..056418c 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -2,74 +2,77 @@ @plugin "tailwindcss-animate"; :root { + color-scheme: light; --radius: 0.625rem; - --background: oklab(1 0 0); - --foreground: oklab(0.145 0 0); - --card: oklab(1 0 0); - --card-foreground: oklab(0.145 0 0); - --popover: oklab(1 0 0); - --popover-foreground: oklab(0.145 0 0); - --primary: oklab(0.205 0 0); - --primary-foreground: oklab(0.985 0 0); - --secondary: oklab(0.97 0.006 0.015); - --secondary-foreground: oklab(0.205 0 0); - --muted: oklab(0.97 0.006 0.015); - --muted-foreground: oklab(0.451 0 0); - --accent: oklab(0.97 0.006 0.015); - --accent-foreground: oklab(0.205 0 0); - --destructive: oklab(0.583 0.185 -0.047); - --destructive-foreground: oklab(0.985 0 0); - --border: oklab(0.922 0.005 0.082); - --input: oklab(0.922 0.005 0.082); - --ring: oklab(0.708 0 0); - --chart-1: oklab(0.646 0.222 0.107); - --chart-2: oklab(0.6 0.115 -0.064); - --chart-3: oklab(0.398 0.063 0.064); - --chart-4: oklab(0.826 0.185 -0.024); - --chart-5: oklab(0.89 0.049 0.344); - --sidebar: oklab(0.985 0 0); - --sidebar-foreground: oklab(0.145 0 0); - --sidebar-primary: oklab(0.205 0 0); - --sidebar-primary-foreground: oklab(0.985 0 0); - --sidebar-accent: oklab(0.97 0.006 0.015); - --sidebar-accent-foreground: oklab(0.205 0 0); - --sidebar-border: oklab(0.922 0.005 0.082); - --sidebar-ring: oklab(0.708 0 0); + /* Glenloch Baptist Church: logo maroon, charcoal, white, warm grey. */ + --background: #fbfaf8; + --foreground: #231f20; + --card: #ffffff; + --card-foreground: #231f20; + --popover: #ffffff; + --popover-foreground: #231f20; + --primary: #932822; + --primary-foreground: #ffffff; + --secondary: #f3f1ee; + --secondary-foreground: #231f20; + --muted: #f3f1ee; + --muted-foreground: #6e6664; + --accent: #f6e7e4; + --accent-foreground: #6d1e19; + --destructive: #b42318; + --destructive-foreground: #ffffff; + --border: #e5e0dc; + --input: #e5e0dc; + --ring: #932822; + --chart-1: #932822; + --chart-2: #c1685d; + --chart-3: #6e6664; + --chart-4: #d9b3ad; + --chart-5: #3f3534; + --sidebar: #ffffff; + --sidebar-foreground: #231f20; + --sidebar-primary: #932822; + --sidebar-primary-foreground: #ffffff; + --sidebar-accent: #f6e7e4; + --sidebar-accent-foreground: #6d1e19; + --sidebar-border: #e5e0dc; + --sidebar-ring: #932822; } .dark { - --background: oklab(0.145 0 0); - --foreground: oklab(0.985 0 0); - --card: oklab(0.205 0 0); - --card-foreground: oklab(0.985 0 0); - --popover: oklab(0.205 0 0); - --popover-foreground: oklab(0.985 0 0); - --primary: oklab(0.985 0 0); - --primary-foreground: oklab(0.205 0 0); - --secondary: oklab(0.269 0 0); - --secondary-foreground: oklab(0.985 0 0); - --muted: oklab(0.269 0 0); - --muted-foreground: oklab(0.637 0 0); - --accent: oklab(0.269 0 0); - --accent-foreground: oklab(0.985 0 0); - --destructive: oklab(0.396 0.141 -0.093); - --destructive-foreground: oklab(0.985 0 0); - --border: oklab(0.269 0 0); - --input: oklab(0.269 0 0); - --ring: oklab(0.544 0 0); - --chart-1: oklab(0.488 0.24 -0.021); - --chart-2: oklab(0.617 0.229 -0.111); - --chart-3: oklab(0.395 0.124 0.174); - --chart-4: oklab(0.714 0.203 -0.028); - --chart-5: oklab(0.691 0.128 -0.042); - --sidebar: oklab(0.205 0 0); - --sidebar-foreground: oklab(0.985 0 0); - --sidebar-primary: oklab(0.488 0.24 -0.021); - --sidebar-primary-foreground: oklab(0.985 0 0); - --sidebar-accent: oklab(0.269 0 0); - --sidebar-accent-foreground: oklab(0.985 0 0); - --sidebar-border: oklab(0.269 0 0); - --sidebar-ring: oklab(0.544 0 0); + color-scheme: dark; + --background: #171314; + --foreground: #f7f2ef; + --card: #211c1d; + --card-foreground: #f7f2ef; + --popover: #211c1d; + --popover-foreground: #f7f2ef; + --primary: #df8a80; + --primary-foreground: #2a1210; + --secondary: #2c2627; + --secondary-foreground: #f7f2ef; + --muted: #2b2526; + --muted-foreground: #b9aaa6; + --accent: #3b2321; + --accent-foreground: #f3d7d2; + --destructive: #f27a70; + --destructive-foreground: #2a0e0b; + --border: #3a3132; + --input: #3a3132; + --ring: #df8a80; + --chart-1: #df8a80; + --chart-2: #c1685d; + --chart-3: #b9aaa6; + --chart-4: #d9b3ad; + --chart-5: #8f7a75; + --sidebar: #1d1819; + --sidebar-foreground: #f7f2ef; + --sidebar-primary: #df8a80; + --sidebar-primary-foreground: #2a1210; + --sidebar-accent: #3b2321; + --sidebar-accent-foreground: #f3d7d2; + --sidebar-border: #3a3132; + --sidebar-ring: #df8a80; } @theme inline { @@ -118,4 +121,8 @@ @apply bg-background text-foreground; font-family: var(--font-sans); } + ::selection { + background: var(--primary); + color: var(--primary-foreground); + } } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 092e0d1..74e6aa3 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,4 +1,4 @@ -import type { Metadata } from "next"; +import type { Metadata, Viewport } from "next"; import { Geist, Geist_Mono } from "next/font/google"; import "./globals.css"; @@ -17,6 +17,10 @@ export const metadata: Metadata = { description: "Church media team scheduling and training platform.", }; +export const viewport: Viewport = { + themeColor: "#932822", +}; + export default function RootLayout({ children, }: Readonly<{ diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index 8b51509..a345eda 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -1,54 +1,149 @@ "use client"; import { useState } from "react"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { signIn } from "next-auth/react"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; /** - * Magic-link sign-in (v1, no passwords). Enter an email; the dev console - * transport prints a sign-in link. Clicking it completes the Auth.js session. - * At launch there is no email/SMS delivery, so the link is shown here as a - * fallback and printed to the console (see /api/dev/magic-link). + * Sign in with the username/password set after the first magic link, or request + * a new one-time link by email. The magic-link path remains the recovery path + * when someone has not set credentials yet. */ export default function LoginPage() { - const [email, setEmail] = useState(""); - const [status, setStatus] = useState<{ kind: "idle" | "sending" | "sent" | "error"; message?: string }>({ - kind: "idle", - }); + const [login, setLogin] = useState(""); + const [password, setPassword] = useState(""); + const [passwordStatus, setPasswordStatus] = useState<{ + kind: "idle" | "signing" | "error"; + message?: string; + }>({ kind: "idle" }); - async function onSubmit(e: React.FormEvent) { + const [email, setEmail] = useState(""); + const [linkStatus, setLinkStatus] = useState<{ + kind: "idle" | "sending" | "sent" | "error"; + message?: string; + }>({ kind: "idle" }); + + async function onPasswordSubmit(e: React.FormEvent) { e.preventDefault(); - setStatus({ kind: "sending" }); + setPasswordStatus({ kind: "signing" }); + try { + const result = await signIn("password", { + login, + password, + redirect: false, + }); + if (!result || result.error) { + setPasswordStatus({ + kind: "error", + message: "That username or password did not match an active account.", + }); + return; + } + // Full navigation lets the server layout read the new session cookie. + window.location.assign("/schedule"); + } catch { + setPasswordStatus({ kind: "error", message: "Network error." }); + } + } + + async function onLinkSubmit(e: React.FormEvent) { + e.preventDefault(); + setLinkStatus({ kind: "sending" }); try { const res = await fetch("/api/dev/magic-link", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email }), }); - const body = (await res.json()) as { ok?: boolean; url?: string; error?: string }; - if (res.ok && body.url) { - setStatus({ kind: "sent", message: body.url }); + const body = (await res.json()) as { + ok?: boolean; + url?: string; + error?: string; + }; + if (res.ok) { + setLinkStatus({ kind: "sent", message: body.url }); } else { - setStatus({ kind: "error", message: body.error ?? "Something went wrong." }); + setLinkStatus({ + kind: "error", + message: body.error ?? "Something went wrong.", + }); } } catch { - setStatus({ kind: "error", message: "Network error." }); + setLinkStatus({ kind: "error", message: "Network error." }); } } return ( -
- - - Sign in - Enter your work email — no password required. - - -
-
- +
+
+
+

+ Glenloch Baptist Church +

+

+ Media Team Hub +

+
+ + + Sign in + + Use your username and password, or request a one-time email link. + + + + +
+ + setLogin(e.target.value)} + placeholder="you@church.local" + /> +
+
+ + setPassword(e.target.value)} + /> +
+ + {passwordStatus.kind === "error" && passwordStatus.message && ( +

+ {passwordStatus.message} +

+ )} + + +
+ + or + +
+ +
+ setEmail(e.target.value)} placeholder="you@church.local" /> -
- - {status.kind === "sent" && status.message && ( -

- Sign-in link (dev console transport):
- {status.message} -

- )} - {status.kind === "error" && status.message && ( -

{status.message}

- )} - - - + + {linkStatus.kind === "sent" && + (linkStatus.message ? ( +

+ Sign-in link (dev console transport):
+ + {linkStatus.message} + +

+ ) : ( +

+ Check your email for a single-use sign-in link. It expires in + 10 minutes. +

+ ))} + {linkStatus.kind === "error" && linkStatus.message && ( +

+ {linkStatus.message} +

+ )} + + +

+ First time here? The magic link will ask you to set a username and + password. If you are locked out, ask an admin for a reset link. +

+ + +
); } diff --git a/src/app/page.tsx b/src/app/page.tsx index a932894..ca416d7 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,103 +1,11 @@ -import Image from "next/image"; +import { redirect } from "next/navigation"; +/** + * Root route. The app lives under the authenticated `(app)` group, so `/` + * simply forwards into the schedule; that layout redirects a visitor without a + * session to `/login`. (The create-next-app starter page that used to live here + * was the "Deploy now" screen users landed on.) + */ export default function Home() { - return ( -
-
- Next.js logo -
    -
  1. - Get started by editing{" "} - - src/app/page.tsx - - . -
  2. -
  3. - Save and see your changes instantly. -
  4. -
- - -
- -
- ); + redirect("/home"); } diff --git a/src/app/request-coverage/page.tsx b/src/app/request-coverage/page.tsx new file mode 100644 index 0000000..5532cc9 --- /dev/null +++ b/src/app/request-coverage/page.tsx @@ -0,0 +1,42 @@ +import Link from "next/link"; +import { CoverageIntakeForm } from "@/components/app/requests/coverage-intake-form"; + +export const metadata = { + title: "Request media coverage", + description: "Ask the media team to cover an event.", +}; + +/** + * Public, unauthenticated intake. Kept outside the `(app)` group so no session + * is required; submission is rate-limited server-side. + */ +export default function RequestCoveragePage() { + return ( +
+
+

+ Glenloch Baptist Church +

+

+ Request media coverage +

+

+ Weddings, baptisms, outreach nights, productions, and other events. + Tell us what is happening and a media coordinator will follow up. +

+
+ +
+ +
+ +

+ Media team member?{" "} + + Sign in + + . +

+
+ ); +} diff --git a/src/app/reset-password/page.tsx b/src/app/reset-password/page.tsx new file mode 100644 index 0000000..6a1b1dc --- /dev/null +++ b/src/app/reset-password/page.tsx @@ -0,0 +1,62 @@ +import Link from "next/link"; +import { verifyPasswordResetToken } from "@/auth/magic-link"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { ResetPasswordForm } from "@/components/app/reset-password-form"; + +export const metadata = { title: "Reset password" }; + +export default async function ResetPasswordPage({ + searchParams, +}: { + searchParams: Promise<{ token?: string }>; +}) { + const { token } = await searchParams; + const payload = await verifyPasswordResetToken(token); + + return ( +
+
+
+

+ Glenloch Baptist Church +

+

+ Media Team Hub +

+
+ + + + Reset password + + + Choose a new password for your Media Team Hub account. + + + + {payload && token ? ( + + ) : ( +
+

+ This reset link is invalid or has expired. Ask an admin for a + new link. +

+ +
+ )} +
+
+
+
+ ); +} diff --git a/src/app/respond/page.tsx b/src/app/respond/page.tsx new file mode 100644 index 0000000..cc9181a --- /dev/null +++ b/src/app/respond/page.tsx @@ -0,0 +1,73 @@ +import { getRespondAssignment } from "@/db/respond"; +import { verifyRespondToken } from "@/lib/respond"; +import { RespondForm } from "@/components/app/respond-form"; + +/** + * Public respond page — unit E4 (ARCHITECTURE §5.6). + * + * `GET /respond?t=&a=confirm|decline` renders the assignment and the two + * buttons. It never mutates: the token is consumed only by the form's POST. + */ +export default async function RespondPage({ + searchParams, +}: { + searchParams: Promise<{ t?: string }>; +}) { + const { t } = await searchParams; + const payload = await verifyRespondToken(t); + + if (!payload || !t) { + return ( +
+

This link isn't valid

+

+ It may have expired. Ask a coordinator to send a new one. +

+
+ ); + } + + const assignment = await getRespondAssignment(payload.assignmentId); + if (!assignment) { + return ( +
+

Assignment not found

+

+ It may have been removed. Ask a coordinator to check the schedule. +

+
+ ); + } + + const alreadyAnswered = + assignment.status === "confirmed" || assignment.status === "declined"; + + return ( +
+

Hi {assignment.volunteerName}

+

+ {assignment.roleName} — {assignment.serviceName} +

+

+ {assignment.occursOnLabel} at {assignment.startTimeLabel} + {assignment.callTimeLabel ? ` · call time ${assignment.callTimeLabel}` : ""} +

+ {assignment.location && ( +

{assignment.location}

+ )} + + {alreadyAnswered ? ( +

+ You already responded — this assignment is {assignment.status}. +

+ ) : ( + + )} + +

+ No login needed. The links are single-use; if you can't serve, decline + so a coordinator can find cover. +

+
+ ); +} diff --git a/src/app/watch/[id]/page.tsx b/src/app/watch/[id]/page.tsx new file mode 100644 index 0000000..b6f7140 --- /dev/null +++ b/src/app/watch/[id]/page.tsx @@ -0,0 +1,209 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { CalendarDays, Share2 } from "lucide-react"; +import { getPublicEventVideo } from "@/db/videos"; +import { mediaOrigin } from "@/lib/media-url"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { formatVideoDuration } from "@/lib/event-videos"; +import { videoView } from "@/lib/video-view"; +import { availableRenditionHeights } from "@/lib/video-renditions"; +import { AdaptiveVideo } from "@/components/public/adaptive-video"; + +export const dynamic = "force-dynamic"; + +export async function generateMetadata({ + params, +}: { + params: Promise<{ id: string }>; +}): Promise { + const { id } = await params; + const video = await getPublicEventVideo(id); + if (!video) return { title: "Video not found" }; + + const origin = await mediaOrigin(); + const view = videoView(video, origin); + const description = + video.description ?? `${video.title} from ${video.eventTitle}.`; + const oembed = `${origin}/api/oembed?url=${encodeURIComponent( + view.watchUrl ?? `${origin}/watch/${id}`, + )}&format=json`; + + return { + title: video.title, + description, + alternates: { + canonical: view.watchUrl ?? undefined, + types: { + "application/json+oembed": oembed, + }, + }, + robots: + video.visibility === "unlisted" + ? { index: false, follow: false } + : undefined, + openGraph: { + type: "video.other", + title: video.title, + description, + siteName: "Glenloch Baptist Church", + url: view.watchUrl ?? undefined, + videos: [ + { + url: view.streamUrl, + secureUrl: view.streamUrl, + type: "video/mp4", + width: video.width ?? 1280, + height: video.height ?? 720, + }, + ], + images: [{ url: view.posterUrl }], + }, + twitter: { + card: "player", + title: video.title, + description, + images: [view.posterUrl], + }, + other: { + "twitter:player": view.embedUrl ?? "", + "twitter:player:width": String(view.embedWidth), + "twitter:player:height": String(view.embedHeight), + }, + }; +} + +export default async function WatchPage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const { id } = await params; + const video = await getPublicEventVideo(id); + if (!video) notFound(); + + const origin = await mediaOrigin(); + const view = videoView(video, origin); + const renditions = await availableRenditionHeights(video); + const shareText = encodeURIComponent(video.title); + const shareUrl = encodeURIComponent(view.watchUrl ?? ""); + + return ( +
+
+
+
+
+ +
+
+ +
+ +
+

+ Watch +

+

+ {video.title} +

+

+ {video.eventTitle} + + + + + {formatVideoDuration(video.durationMs)} +

+ {video.description && ( +

+ {video.description} +

+ )} +
+ + + +
+ + Embed this video + +

+ Paste this code into a website, LMS, or social platform that accepts + an iframe embed. +

+