From 5adf1cef1f634215c005a239941f67ac1e762f26 Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Fri, 20 Nov 2026 04:07:02 +0000 Subject: [PATCH] push to maple-street --- .agent/HANDOFF-C2.md | 59 - .agent/PROGRESS.md | 494 +- .env.example | 55 +- .github/workflows/ci.yml | 38 +- .pi/DEAD_ENDS.md | 25 + A4_HANDOFF.md | 126 - Dockerfile | 26 +- README.md | 52 +- docker-compose.yml | 50 +- docs/FEATURE-SUMMARY.md | 6 +- docs/PROJECT-STATE.md | 731 +++ docs/superpowers/D9-HANDOFF.md | 60 + drizzle/0010_friendly_oracle.sql | 37 + drizzle/0011_pretty_lilith.sql | 16 + drizzle/0012_admin_content.sql | 30 + drizzle/0013_fearless_gravity.sql | 11 + drizzle/0014_nifty_calypso.sql | 60 + drizzle/0015_vengeful_sabra.sql | 12 + drizzle/0016_orange_synch.sql | 6 + drizzle/0017_dear_mandarin.sql | 5 + drizzle/0018_brave_rick_jones.sql | 33 + drizzle/0019_raise_event_video_limit.sql | 1 + drizzle/0020_square_wolfpack.sql | 2 + drizzle/0021_sparkling_exiles.sql | 81 + drizzle/meta/0010_snapshot.json | 2828 ++++++++++ drizzle/meta/0011_snapshot.json | 2944 ++++++++++ drizzle/meta/0012_snapshot.json | 3143 +++++++++++ drizzle/meta/0013_snapshot.json | 3192 +++++++++++ drizzle/meta/0014_snapshot.json | 3688 +++++++++++++ drizzle/meta/0015_snapshot.json | 3782 +++++++++++++ drizzle/meta/0016_snapshot.json | 3825 +++++++++++++ drizzle/meta/0017_snapshot.json | 3852 +++++++++++++ drizzle/meta/0018_snapshot.json | 4107 ++++++++++++++ drizzle/meta/0019_snapshot.json | 4107 ++++++++++++++ drizzle/meta/0020_snapshot.json | 4128 ++++++++++++++ drizzle/meta/0021_snapshot.json | 4798 +++++++++++++++++ drizzle/meta/_journal.json | 84 + e2e/admin.spec.ts | 309 ++ e2e/announcements.spec.ts | 60 + e2e/assign-mutations.spec.ts | 60 +- e2e/auto-fill.spec.ts | 96 + e2e/backup.spec.ts | 87 + e2e/calendar.spec.ts | 29 + e2e/dev.ts | 35 +- e2e/events.spec.ts | 197 + e2e/media.spec.ts | 330 ++ e2e/notifications.spec.ts | 186 + e2e/passwords.spec.ts | 177 + e2e/photo-archive.spec.ts | 149 + e2e/publish.spec.ts | 121 + e2e/services.spec.ts | 34 + e2e/settings.spec.ts | 34 + e2e/shell.spec.ts | 34 +- e2e/training.spec.ts | 77 + next.config.ts | 39 +- package.json | 8 +- playwright.config.ts | 24 +- pnpm-lock.yaml | 691 ++- public/training/media-team-admin-guide.pdf | Bin 0 -> 3842525 bytes public/training/media-team-user-guide.pdf | Bin 0 -> 2991185 bytes public/training/screens/admin-backup.png | Bin 0 -> 110754 bytes public/training/screens/admin-coverage.png | Bin 0 -> 92764 bytes public/training/screens/admin-dashboard.png | Bin 0 -> 114589 bytes public/training/screens/admin-email.png | Bin 0 -> 103115 bytes .../training/screens/admin-notifications.png | Bin 0 -> 88531 bytes public/training/screens/admin-overview.png | Bin 0 -> 121472 bytes public/training/screens/admin-people.png | Bin 0 -> 121472 bytes public/training/screens/admin-positions.png | Bin 0 -> 128975 bytes public/training/screens/admin-print.png | Bin 0 -> 44302 bytes public/training/screens/admin-reminders.png | Bin 0 -> 103115 bytes public/training/screens/admin-run-sheet.png | Bin 0 -> 79341 bytes public/training/screens/admin-schedule.png | Bin 0 -> 89209 bytes public/training/screens/admin-services.png | Bin 0 -> 128975 bytes public/training/screens/admin-settings.png | Bin 0 -> 91668 bytes public/training/screens/admin-skills.png | Bin 0 -> 138588 bytes .../training/screens/user-announcements.png | Bin 0 -> 50155 bytes public/training/screens/user-availability.png | Bin 0 -> 64713 bytes public/training/screens/user-event.png | Bin 0 -> 84881 bytes public/training/screens/user-events.png | Bin 0 -> 46296 bytes public/training/screens/user-home-mobile.png | Bin 0 -> 57436 bytes public/training/screens/user-home.png | Bin 0 -> 81160 bytes public/training/screens/user-login.png | Bin 0 -> 55747 bytes public/training/screens/user-media.png | Bin 0 -> 77765 bytes public/training/screens/user-profile.png | Bin 0 -> 83659 bytes .../screens/user-request-coverage.png | Bin 0 -> 60496 bytes public/training/screens/user-roster.png | Bin 0 -> 57824 bytes public/training/screens/user-run-sheet.png | Bin 0 -> 94515 bytes .../training/screens/user-schedule-month.png | Bin 0 -> 53708 bytes public/training/screens/user-schedule.png | Bin 0 -> 61757 bytes public/training/screens/user-settings.png | Bin 0 -> 81234 bytes public/training/screens/user-training.png | Bin 0 -> 121731 bytes src/app/(app)/admin/page.tsx | 289 + src/app/(app)/announcements/page.tsx | 57 +- src/app/(app)/availability/page.tsx | 126 + src/app/(app)/coverage/page.tsx | 108 + src/app/(app)/dashboard/page.tsx | 301 ++ .../events/[id]/folders/[folderId]/page.tsx | 102 + src/app/(app)/events/[id]/page.tsx | 325 ++ src/app/(app)/events/page.tsx | 148 + src/app/(app)/home/page.tsx | 310 ++ src/app/(app)/layout.tsx | 17 +- src/app/(app)/media/[id]/page.tsx | 78 + src/app/(app)/media/page.tsx | 263 + src/app/(app)/profile/page.tsx | 73 + src/app/(app)/roster/page.tsx | 80 +- src/app/(app)/run-sheet/[instanceId]/page.tsx | 28 + src/app/(app)/schedule/page.tsx | 130 +- src/app/(app)/schedule/print/page.tsx | 154 + src/app/(app)/settings/page.tsx | 177 +- src/app/(app)/training/guides/admin/page.tsx | 779 +++ src/app/(app)/training/guides/user/page.tsx | 591 ++ src/app/(app)/training/page.tsx | 105 +- src/app/api/account/calendar-feed/route.ts | 20 + src/app/api/account/password/route.ts | 95 + src/app/api/announcements/route.ts | 90 + src/app/api/assignments/[id]/respond/route.ts | 47 + src/app/api/assignments/candidates/route.ts | 16 + src/app/api/assignments/route.ts | 207 +- src/app/api/auth/reset-password/route.ts | 68 + src/app/api/calendar/[token]/route.ts | 39 + src/app/api/coverage-intake/route.ts | 100 + src/app/api/coverage/route.ts | 81 + src/app/api/dev/approve/route.ts | 31 +- src/app/api/dev/backup/restore/route.ts | 193 + src/app/api/dev/backup/route.ts | 143 + src/app/api/dev/catalog/route.ts | 10 + src/app/api/dev/complete/route.ts | 56 +- src/app/api/dev/cron/complete/route.ts | 34 + src/app/api/dev/cron/instances/route.ts | 38 +- src/app/api/dev/cron/notifications/route.ts | 37 + src/app/api/dev/cron/slots/route.ts | 29 +- src/app/api/dev/deny/route.ts | 6 +- src/app/api/dev/invite/route.ts | 9 +- src/app/api/dev/magic-link/route.ts | 37 +- src/app/api/dev/notification-rules/route.ts | 153 + src/app/api/dev/notifications/route.ts | 170 + .../api/dev/positions/requirements/route.ts | 7 + src/app/api/dev/positions/route.ts | 10 + src/app/api/dev/profile/route.ts | 41 +- src/app/api/dev/reset/route.ts | 47 +- .../schedule/[instanceId]/auto-fill/route.ts | 138 + .../schedule/[instanceId]/publish/route.ts | 147 + src/app/api/dev/schedule/instances/route.ts | 51 + src/app/api/dev/services/route.ts | 68 + src/app/api/dev/settings/route.ts | 109 + src/app/api/dev/skills/assessments/route.ts | 4 + src/app/api/dev/skills/compose/route.ts | 4 + src/app/api/dev/skills/matrix/route.ts | 4 + src/app/api/dev/skills/route.ts | 10 + src/app/api/dev/skills/verify/route.ts | 12 +- src/app/api/dev/storage/route.ts | 95 + src/app/api/dev/training/lessons/route.ts | 160 + src/app/api/dev/training/resources/route.ts | 146 + src/app/api/dev/unavailability/route.ts | 40 +- src/app/api/dev/user-skills/route.ts | 138 +- src/app/api/dev/users/magic-link/route.ts | 88 + src/app/api/dev/users/password/route.ts | 87 + src/app/api/dev/users/route.ts | 276 + src/app/api/events/[id]/archive/route.ts | 120 + src/app/api/events/[id]/download/route.ts | 122 + .../[folderId]/photos/[photoId]/edit/route.ts | 130 + .../photos/[photoId]/export/route.ts | 99 + .../photos/[photoId]/preview/route.ts | 102 + .../[folderId]/photos/[photoId]/route.ts | 125 + .../[id]/folders/[folderId]/photos/route.ts | 156 + src/app/api/events/[id]/folders/route.ts | 53 + .../api/events/[id]/photographers/route.ts | 67 + src/app/api/events/[id]/route.ts | 77 + .../[id]/videos/[videoId]/edit/route.ts | 152 + .../[id]/videos/[videoId]/original/route.ts | 77 + .../[id]/videos/[videoId]/process/route.ts | 47 + .../api/events/[id]/videos/[videoId]/route.ts | 104 + src/app/api/events/[id]/videos/chunk/route.ts | 257 + src/app/api/events/[id]/videos/route.ts | 213 + src/app/api/events/route.ts | 72 + src/app/api/export/history/route.ts | 18 + src/app/api/export/schedule/route.ts | 34 + src/app/api/media/[id]/poster/route.ts | 57 + src/app/api/media/[id]/stream/route.ts | 110 + src/app/api/oembed/route.ts | 55 + src/app/api/respond/route.ts | 117 + src/app/api/run-sheet/route.ts | 165 + src/app/api/training/files/[id]/route.ts | 49 + src/app/embed/[id]/page.tsx | 42 + src/app/globals.css | 135 +- src/app/layout.tsx | 6 +- src/app/login/page.tsx | 198 +- src/app/page.tsx | 108 +- src/app/request-coverage/page.tsx | 42 + src/app/reset-password/page.tsx | 62 + src/app/respond/page.tsx | 73 + src/app/watch/[id]/page.tsx | 209 + src/app/welcome/page.tsx | 59 + src/auth/api.ts | 158 + src/auth/config.ts | 39 +- src/auth/invites.ts | 11 +- src/auth/magic-link.test.ts | 87 + src/auth/magic-link.ts | 299 +- src/auth/password.test.ts | 53 + src/auth/password.ts | 123 + src/auth/roles.ts | 4 +- src/components/app/admin/backup-panel.tsx | 165 + src/components/app/admin/email-panel.tsx | 223 + .../app/admin/notifications-panel.tsx | 189 + src/components/app/admin/people-panel.tsx | 1041 ++++ src/components/app/admin/positions-panel.tsx | 344 ++ src/components/app/admin/reminders-panel.tsx | 313 ++ src/components/app/admin/services-panel.tsx | 285 + .../app/admin/skills-matrix-panel.tsx | 293 + src/components/app/announcements-panel.tsx | 218 + src/components/app/app-layout.tsx | 40 +- src/components/app/assign-picker.tsx | 312 ++ src/components/app/assignment-actions.tsx | 86 + .../app/availability/availability-manager.tsx | 379 ++ src/components/app/calendar-nav.tsx | 96 + .../app/coverage/coverage-board.tsx | 359 ++ .../app/coverage/coverage-request-button.tsx | 108 + .../app/events/archive-event-button.tsx | 79 + .../app/events/delete-event-button.tsx | 70 + .../app/events/event-create-form.tsx | 136 + .../app/events/folder-create-form.tsx | 84 + src/components/app/events/photo-gallery.tsx | 401 ++ src/components/app/events/photo-viewer.tsx | 1249 +++++ .../app/events/photographer-panel.tsx | 179 + src/components/app/media/video-editor.tsx | 605 +++ .../app/media/video-upload-form.tsx | 414 ++ src/components/app/month-calendar.tsx | 90 + src/components/app/nav.tsx | 91 +- src/components/app/password-form.tsx | 133 + src/components/app/print-button.tsx | 13 + src/components/app/profile-panel.tsx | 510 ++ .../app/requests/coverage-intake-form.tsx | 163 + src/components/app/reset-password-form.tsx | 105 + src/components/app/respond-form.tsx | 77 + .../app/run-sheet/run-sheet-editor.tsx | 554 ++ src/components/app/schedule-admin-bar.tsx | 200 + src/components/app/schedule-grid-editor.tsx | 109 +- src/components/app/schedule-grid.tsx | 112 +- src/components/app/set-password-form.tsx | 103 + src/components/app/settings-form.tsx | 98 + src/components/app/storage-panel.tsx | 143 + src/components/app/training-panel.tsx | 382 ++ src/components/app/training/guide.tsx | 194 + src/components/app/year-calendar.tsx | 45 + src/components/public/adaptive-video.tsx | 241 + src/db/admin.ts | 46 + src/db/announcements.ts | 93 + src/db/assignments.ts | 275 +- src/db/autoFill.ts | 371 ++ src/db/calendar.ts | 78 + src/db/cleanup.ts | 60 + src/db/complete.ts | 127 + src/db/coverage.ts | 376 ++ src/db/dashboard.ts | 158 + src/db/dispatcher.ts | 256 + src/db/eventReminders.ts | 181 + src/db/events.ts | 706 +++ src/db/exports.ts | 144 + src/db/grid.ts | 204 +- src/db/intake.ts | 189 + src/db/media.ts | 59 + src/db/outbox.ts | 331 ++ src/db/profile.ts | 18 + src/db/prune.ts | 33 + src/db/publish.ts | 253 + src/db/rankedCandidates.ts | 308 ++ src/db/reminders.ts | 263 + src/db/respond.ts | 303 ++ src/db/runSheet.ts | 399 ++ src/db/schema.ts | 700 ++- src/db/seed.ts | 180 +- src/db/services.ts | 59 +- src/db/settings.ts | 142 + src/db/storage-settings.ts | 131 + src/db/training.ts | 199 + src/db/userSkills.ts | 74 +- src/db/users.ts | 327 ++ src/db/videos.ts | 279 + src/db/volunteer.ts | 376 ++ src/domain/autoFill.test.ts | 237 + src/domain/autoFill.ts | 231 + src/domain/calendar.test.ts | 47 + src/domain/calendar.ts | 84 + src/domain/dispatch.test.ts | 136 + src/domain/dispatch.ts | 162 + src/domain/notifications.test.ts | 79 + src/domain/notifications.ts | 87 + src/domain/publish.test.ts | 84 + src/domain/publish.ts | 86 + src/domain/reminders.test.ts | 135 + src/domain/reminders.ts | 91 + src/domain/templates.test.ts | 63 + src/domain/templates.ts | 189 + src/domain/users.test.ts | 114 + src/domain/users.ts | 99 + src/lib/backup.test.ts | 89 + src/lib/backup.ts | 417 ++ src/lib/csv.test.ts | 20 + src/lib/csv.ts | 24 + src/lib/email.ts | 178 + src/lib/event-access.test.ts | 42 + src/lib/event-access.ts | 49 + src/lib/event-archive.test.ts | 51 + src/lib/event-archive.ts | 70 + src/lib/event-nfs-archive.ts | 260 + src/lib/event-photos.test.ts | 82 + src/lib/event-photos.ts | 217 + src/lib/event-video-finalize.ts | 174 + src/lib/event-videos.test.ts | 60 + src/lib/event-videos.ts | 237 + src/lib/http.ts | 15 + src/lib/ics.test.ts | 53 + src/lib/ics.ts | 111 + src/lib/media-url.ts | 13 + src/lib/photo-adjustments.test.ts | 138 + src/lib/photo-adjustments.ts | 710 +++ src/lib/photo-exports.test.ts | 45 + src/lib/photo-exports.ts | 36 + src/lib/photo-geometry.test.ts | 97 + src/lib/photo-geometry.ts | 204 + src/lib/photo-presets.ts | 119 + src/lib/photo-render.test.ts | 101 + src/lib/photo-render.ts | 247 + src/lib/range.test.ts | 26 + src/lib/range.ts | 44 + src/lib/rate-limit.test.ts | 34 + src/lib/rate-limit.ts | 61 + src/lib/respond.test.ts | 45 + src/lib/respond.ts | 87 + src/lib/secret.test.ts | 41 + src/lib/secret.ts | 59 + src/lib/tz.ts | 6 + src/lib/uploads.test.ts | 79 + src/lib/uploads.ts | 88 + src/lib/video-format.ts | 11 + src/lib/video-limits.ts | 10 + src/lib/video-processing.ts | 111 + src/lib/video-quality.test.ts | 43 + src/lib/video-quality.ts | 49 + src/lib/video-render.test.ts | 55 + src/lib/video-render.ts | 360 ++ src/lib/video-renditions.ts | 46 + src/lib/video-view.ts | 109 + src/lib/welcome-email.ts | 96 + src/middleware.ts | 23 + 345 files changed, 86105 insertions(+), 1079 deletions(-) delete mode 100644 .agent/HANDOFF-C2.md create mode 100644 .pi/DEAD_ENDS.md delete mode 100644 A4_HANDOFF.md create mode 100644 docs/PROJECT-STATE.md create mode 100644 docs/superpowers/D9-HANDOFF.md create mode 100644 drizzle/0010_friendly_oracle.sql create mode 100644 drizzle/0011_pretty_lilith.sql create mode 100644 drizzle/0012_admin_content.sql create mode 100644 drizzle/0013_fearless_gravity.sql create mode 100644 drizzle/0014_nifty_calypso.sql create mode 100644 drizzle/0015_vengeful_sabra.sql create mode 100644 drizzle/0016_orange_synch.sql create mode 100644 drizzle/0017_dear_mandarin.sql create mode 100644 drizzle/0018_brave_rick_jones.sql create mode 100644 drizzle/0019_raise_event_video_limit.sql create mode 100644 drizzle/0020_square_wolfpack.sql create mode 100644 drizzle/0021_sparkling_exiles.sql create mode 100644 drizzle/meta/0010_snapshot.json create mode 100644 drizzle/meta/0011_snapshot.json create mode 100644 drizzle/meta/0012_snapshot.json create mode 100644 drizzle/meta/0013_snapshot.json create mode 100644 drizzle/meta/0014_snapshot.json create mode 100644 drizzle/meta/0015_snapshot.json create mode 100644 drizzle/meta/0016_snapshot.json create mode 100644 drizzle/meta/0017_snapshot.json create mode 100644 drizzle/meta/0018_snapshot.json create mode 100644 drizzle/meta/0019_snapshot.json create mode 100644 drizzle/meta/0020_snapshot.json create mode 100644 drizzle/meta/0021_snapshot.json create mode 100644 e2e/admin.spec.ts create mode 100644 e2e/announcements.spec.ts create mode 100644 e2e/auto-fill.spec.ts create mode 100644 e2e/backup.spec.ts create mode 100644 e2e/calendar.spec.ts create mode 100644 e2e/events.spec.ts create mode 100644 e2e/media.spec.ts create mode 100644 e2e/notifications.spec.ts create mode 100644 e2e/passwords.spec.ts create mode 100644 e2e/photo-archive.spec.ts create mode 100644 e2e/publish.spec.ts create mode 100644 e2e/services.spec.ts create mode 100644 e2e/settings.spec.ts create mode 100644 e2e/training.spec.ts create mode 100644 public/training/media-team-admin-guide.pdf create mode 100644 public/training/media-team-user-guide.pdf create mode 100644 public/training/screens/admin-backup.png create mode 100644 public/training/screens/admin-coverage.png create mode 100644 public/training/screens/admin-dashboard.png create mode 100644 public/training/screens/admin-email.png create mode 100644 public/training/screens/admin-notifications.png create mode 100644 public/training/screens/admin-overview.png create mode 100644 public/training/screens/admin-people.png create mode 100644 public/training/screens/admin-positions.png create mode 100644 public/training/screens/admin-print.png create mode 100644 public/training/screens/admin-reminders.png create mode 100644 public/training/screens/admin-run-sheet.png create mode 100644 public/training/screens/admin-schedule.png create mode 100644 public/training/screens/admin-services.png create mode 100644 public/training/screens/admin-settings.png create mode 100644 public/training/screens/admin-skills.png create mode 100644 public/training/screens/user-announcements.png create mode 100644 public/training/screens/user-availability.png create mode 100644 public/training/screens/user-event.png create mode 100644 public/training/screens/user-events.png create mode 100644 public/training/screens/user-home-mobile.png create mode 100644 public/training/screens/user-home.png create mode 100644 public/training/screens/user-login.png create mode 100644 public/training/screens/user-media.png create mode 100644 public/training/screens/user-profile.png create mode 100644 public/training/screens/user-request-coverage.png create mode 100644 public/training/screens/user-roster.png create mode 100644 public/training/screens/user-run-sheet.png create mode 100644 public/training/screens/user-schedule-month.png create mode 100644 public/training/screens/user-schedule.png create mode 100644 public/training/screens/user-settings.png create mode 100644 public/training/screens/user-training.png create mode 100644 src/app/(app)/admin/page.tsx create mode 100644 src/app/(app)/availability/page.tsx create mode 100644 src/app/(app)/coverage/page.tsx create mode 100644 src/app/(app)/dashboard/page.tsx create mode 100644 src/app/(app)/events/[id]/folders/[folderId]/page.tsx create mode 100644 src/app/(app)/events/[id]/page.tsx create mode 100644 src/app/(app)/events/page.tsx create mode 100644 src/app/(app)/home/page.tsx create mode 100644 src/app/(app)/media/[id]/page.tsx create mode 100644 src/app/(app)/media/page.tsx create mode 100644 src/app/(app)/profile/page.tsx create mode 100644 src/app/(app)/run-sheet/[instanceId]/page.tsx create mode 100644 src/app/(app)/schedule/print/page.tsx create mode 100644 src/app/(app)/training/guides/admin/page.tsx create mode 100644 src/app/(app)/training/guides/user/page.tsx create mode 100644 src/app/api/account/calendar-feed/route.ts create mode 100644 src/app/api/account/password/route.ts create mode 100644 src/app/api/announcements/route.ts create mode 100644 src/app/api/assignments/[id]/respond/route.ts create mode 100644 src/app/api/assignments/candidates/route.ts create mode 100644 src/app/api/auth/reset-password/route.ts create mode 100644 src/app/api/calendar/[token]/route.ts create mode 100644 src/app/api/coverage-intake/route.ts create mode 100644 src/app/api/coverage/route.ts create mode 100644 src/app/api/dev/backup/restore/route.ts create mode 100644 src/app/api/dev/backup/route.ts create mode 100644 src/app/api/dev/cron/complete/route.ts create mode 100644 src/app/api/dev/cron/notifications/route.ts create mode 100644 src/app/api/dev/notification-rules/route.ts create mode 100644 src/app/api/dev/notifications/route.ts create mode 100644 src/app/api/dev/schedule/[instanceId]/auto-fill/route.ts create mode 100644 src/app/api/dev/schedule/[instanceId]/publish/route.ts create mode 100644 src/app/api/dev/schedule/instances/route.ts create mode 100644 src/app/api/dev/settings/route.ts create mode 100644 src/app/api/dev/storage/route.ts create mode 100644 src/app/api/dev/training/lessons/route.ts create mode 100644 src/app/api/dev/training/resources/route.ts create mode 100644 src/app/api/dev/users/magic-link/route.ts create mode 100644 src/app/api/dev/users/password/route.ts create mode 100644 src/app/api/dev/users/route.ts create mode 100644 src/app/api/events/[id]/archive/route.ts create mode 100644 src/app/api/events/[id]/download/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/edit/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/export/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/preview/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/route.ts create mode 100644 src/app/api/events/[id]/folders/route.ts create mode 100644 src/app/api/events/[id]/photographers/route.ts create mode 100644 src/app/api/events/[id]/route.ts create mode 100644 src/app/api/events/[id]/videos/[videoId]/edit/route.ts create mode 100644 src/app/api/events/[id]/videos/[videoId]/original/route.ts create mode 100644 src/app/api/events/[id]/videos/[videoId]/process/route.ts create mode 100644 src/app/api/events/[id]/videos/[videoId]/route.ts create mode 100644 src/app/api/events/[id]/videos/chunk/route.ts create mode 100644 src/app/api/events/[id]/videos/route.ts create mode 100644 src/app/api/events/route.ts create mode 100644 src/app/api/export/history/route.ts create mode 100644 src/app/api/export/schedule/route.ts create mode 100644 src/app/api/media/[id]/poster/route.ts create mode 100644 src/app/api/media/[id]/stream/route.ts create mode 100644 src/app/api/oembed/route.ts create mode 100644 src/app/api/respond/route.ts create mode 100644 src/app/api/run-sheet/route.ts create mode 100644 src/app/api/training/files/[id]/route.ts create mode 100644 src/app/embed/[id]/page.tsx create mode 100644 src/app/request-coverage/page.tsx create mode 100644 src/app/reset-password/page.tsx create mode 100644 src/app/respond/page.tsx create mode 100644 src/app/watch/[id]/page.tsx create mode 100644 src/app/welcome/page.tsx create mode 100644 src/auth/api.ts create mode 100644 src/auth/magic-link.test.ts create mode 100644 src/auth/password.test.ts create mode 100644 src/auth/password.ts create mode 100644 src/components/app/admin/backup-panel.tsx create mode 100644 src/components/app/admin/email-panel.tsx create mode 100644 src/components/app/admin/notifications-panel.tsx create mode 100644 src/components/app/admin/people-panel.tsx create mode 100644 src/components/app/admin/positions-panel.tsx create mode 100644 src/components/app/admin/reminders-panel.tsx create mode 100644 src/components/app/admin/services-panel.tsx create mode 100644 src/components/app/admin/skills-matrix-panel.tsx create mode 100644 src/components/app/announcements-panel.tsx create mode 100644 src/components/app/assign-picker.tsx create mode 100644 src/components/app/assignment-actions.tsx create mode 100644 src/components/app/availability/availability-manager.tsx create mode 100644 src/components/app/calendar-nav.tsx create mode 100644 src/components/app/coverage/coverage-board.tsx create mode 100644 src/components/app/coverage/coverage-request-button.tsx create mode 100644 src/components/app/events/archive-event-button.tsx create mode 100644 src/components/app/events/delete-event-button.tsx create mode 100644 src/components/app/events/event-create-form.tsx create mode 100644 src/components/app/events/folder-create-form.tsx create mode 100644 src/components/app/events/photo-gallery.tsx create mode 100644 src/components/app/events/photo-viewer.tsx create mode 100644 src/components/app/events/photographer-panel.tsx create mode 100644 src/components/app/media/video-editor.tsx create mode 100644 src/components/app/media/video-upload-form.tsx create mode 100644 src/components/app/month-calendar.tsx create mode 100644 src/components/app/password-form.tsx create mode 100644 src/components/app/print-button.tsx create mode 100644 src/components/app/profile-panel.tsx create mode 100644 src/components/app/requests/coverage-intake-form.tsx create mode 100644 src/components/app/reset-password-form.tsx create mode 100644 src/components/app/respond-form.tsx create mode 100644 src/components/app/run-sheet/run-sheet-editor.tsx create mode 100644 src/components/app/schedule-admin-bar.tsx create mode 100644 src/components/app/set-password-form.tsx create mode 100644 src/components/app/settings-form.tsx create mode 100644 src/components/app/storage-panel.tsx create mode 100644 src/components/app/training-panel.tsx create mode 100644 src/components/app/training/guide.tsx create mode 100644 src/components/app/year-calendar.tsx create mode 100644 src/components/public/adaptive-video.tsx create mode 100644 src/db/admin.ts create mode 100644 src/db/announcements.ts create mode 100644 src/db/autoFill.ts create mode 100644 src/db/calendar.ts create mode 100644 src/db/cleanup.ts create mode 100644 src/db/complete.ts create mode 100644 src/db/coverage.ts create mode 100644 src/db/dashboard.ts create mode 100644 src/db/dispatcher.ts create mode 100644 src/db/eventReminders.ts create mode 100644 src/db/events.ts create mode 100644 src/db/exports.ts create mode 100644 src/db/intake.ts create mode 100644 src/db/media.ts create mode 100644 src/db/outbox.ts create mode 100644 src/db/prune.ts create mode 100644 src/db/publish.ts create mode 100644 src/db/rankedCandidates.ts create mode 100644 src/db/reminders.ts create mode 100644 src/db/respond.ts create mode 100644 src/db/runSheet.ts create mode 100644 src/db/settings.ts create mode 100644 src/db/storage-settings.ts create mode 100644 src/db/training.ts create mode 100644 src/db/users.ts create mode 100644 src/db/videos.ts create mode 100644 src/db/volunteer.ts create mode 100644 src/domain/autoFill.test.ts create mode 100644 src/domain/autoFill.ts create mode 100644 src/domain/calendar.test.ts create mode 100644 src/domain/calendar.ts create mode 100644 src/domain/dispatch.test.ts create mode 100644 src/domain/dispatch.ts create mode 100644 src/domain/notifications.test.ts create mode 100644 src/domain/notifications.ts create mode 100644 src/domain/publish.test.ts create mode 100644 src/domain/publish.ts create mode 100644 src/domain/reminders.test.ts create mode 100644 src/domain/reminders.ts create mode 100644 src/domain/templates.test.ts create mode 100644 src/domain/templates.ts create mode 100644 src/domain/users.test.ts create mode 100644 src/domain/users.ts create mode 100644 src/lib/backup.test.ts create mode 100644 src/lib/backup.ts create mode 100644 src/lib/csv.test.ts create mode 100644 src/lib/csv.ts create mode 100644 src/lib/email.ts create mode 100644 src/lib/event-access.test.ts create mode 100644 src/lib/event-access.ts create mode 100644 src/lib/event-archive.test.ts create mode 100644 src/lib/event-archive.ts create mode 100644 src/lib/event-nfs-archive.ts create mode 100644 src/lib/event-photos.test.ts create mode 100644 src/lib/event-photos.ts create mode 100644 src/lib/event-video-finalize.ts create mode 100644 src/lib/event-videos.test.ts create mode 100644 src/lib/event-videos.ts create mode 100644 src/lib/http.ts create mode 100644 src/lib/ics.test.ts create mode 100644 src/lib/ics.ts create mode 100644 src/lib/media-url.ts create mode 100644 src/lib/photo-adjustments.test.ts create mode 100644 src/lib/photo-adjustments.ts create mode 100644 src/lib/photo-exports.test.ts create mode 100644 src/lib/photo-exports.ts create mode 100644 src/lib/photo-geometry.test.ts create mode 100644 src/lib/photo-geometry.ts create mode 100644 src/lib/photo-presets.ts create mode 100644 src/lib/photo-render.test.ts create mode 100644 src/lib/photo-render.ts create mode 100644 src/lib/range.test.ts create mode 100644 src/lib/range.ts create mode 100644 src/lib/rate-limit.test.ts create mode 100644 src/lib/rate-limit.ts create mode 100644 src/lib/respond.test.ts create mode 100644 src/lib/respond.ts create mode 100644 src/lib/secret.test.ts create mode 100644 src/lib/secret.ts create mode 100644 src/lib/uploads.test.ts create mode 100644 src/lib/uploads.ts create mode 100644 src/lib/video-format.ts create mode 100644 src/lib/video-limits.ts create mode 100644 src/lib/video-processing.ts create mode 100644 src/lib/video-quality.test.ts create mode 100644 src/lib/video-quality.ts create mode 100644 src/lib/video-render.test.ts create mode 100644 src/lib/video-render.ts create mode 100644 src/lib/video-renditions.ts create mode 100644 src/lib/video-view.ts create mode 100644 src/lib/welcome-email.ts create mode 100644 src/middleware.ts 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//9^|wtMEU%C7h=}-k66is1WER|HehS;5yg54pU=QSBlOXizBXq=E+JKSzs9J)$gQ z;CH!Mxq1$dcqJbu`X-PQk$~vFWuc__M~6o)dUcGK-?vWPDS*p}`*c4n_|1AID%x!5 z3*hqh-fk*44z8ST zXg+th{d+L1O-OG2bsEaUH59SP=zY7H2)gDpkjoeT)V0J#Q9?<(WzTRua{VKf%gxdB zjgsoUoQCRk-V*}7Ovbx$$d8nW3+3i$NlciT>?NCb1~_Uu+f4qF)BWAFsvZq80`&hU zHuI-4TtYF{M2jLpF07;Ru22`;77-OTU$wiBWUS<+18%)H2TPoYa$X>_e++FeudDR^ zlS;d=ToH+sSbCSuXWpu}fF^!)wfIE3=Tn*mjW5*rM(pV;OYcvvO}%$mSqAv^^%zyQ z-n@BUG-!Ms_NFO9jr%eW@^6e|VO)%;I`=O+YSS-Bfkqg)ScJWu5J2Yo@#9?oc_O zJ3&s&lg?(Z>!VZww@J%Os9(GrTlK$p_=NYrbB18Rm*lnqrkLN4=BEx^Sj+F054U&6 zM}`l^E&fgVH?wk0A_J6yKXkc22jKE0dk2!6@gLEgjN1PndCo27MOD*Z+@G0j6cxX} zhi~)I(TCH>OT;r>sn|nDqWoih0rKbv_wA`qRh_{^OHVvZcNmAB*&yhYs$=$kU|<9V z&CS8=%<4AuR$otpfEOh^Ii@3Q!20{)`2KwsZ|AkbruOjkdBqFfy=0tYTWlSAtKPO2 z$guyX{pG$ePF)O_?1$*+7FU)KSTJ%bI)Ll1P|WdnhLwL)u@VUDSaULZZoI$e7a1TK z&v>LSaLPpQs>K`{A2+Yv9IAc9QQk&$t}A@FNnSmuBxdekS|@J3`E+A0g99N+L+Q7j z_}qlwBD;NFql25yOJ7Z}av^DF*R&)-m5_S?rk7PhqP}0Z)A;V>*S_5+ej*_4i}o~~ zL)~GkMO;Ts@4U3&bha-U;uFZ=1_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^~q=fq5Pd_4=Ohf`*ck}Ebmee_k`gs!*4A0PhKS6HxAH_A9$f76;P zLq(p~V(%^Y0EB8}Mt^cb8A5wr9Q&(hOzy$ng;!dB*m`^VH0tB8^^!EJ>M$Y=y@+fH zBAhF#>Y)){KVDt_xZ0Yo&GnA7jItxX%X4$gu8c;4TW(l3ftqq!;nIVywVomdrGNpv zZsL75@7Itw8DVngIFh7E|KzqSK9foBnofAn2eokeM$!eRtEU?$ zXZat(IQSOMZhCl|5AGZ`uvkhAeZ*Sj|2~%?d!e#+TE(YN&t^PKIi-MZM)&Bv)g&I1 z(x^wc2F}NsqWF4CRcz-CDsy^h&V?24*xy8ArASVck9=>Q(Vl1LxC%L`?EK~Gu5rQ% zZYZ9G<&;+%18Qch68gvNFq?c}_50?!R0x#Ygkd(#-ums`-?DI~X-?57cW?(7(tj4k z#1^v(U@v-mq6Bp*&15tyoz=*Un9vs#mE6ddamjt&UCHL3$St(ztf6W+&hWjEZ%IK;L%#`=dNd{QQaD@k`3}vsrg>>ek9&JX(F0) zU2bcF0(PWqq* getPositionSkills(position.id)), + ); + const requirementsByPosition: Record = {}; + positions.forEach((position, index) => { + requirementsByPosition[position.id] = requirementSets[index].map((row) => ({ + skillId: row.skillId, + weight: row.weight, + requiredLevel: row.requiredLevel, + isCore: row.isCore, + })); + }); + + const matrixRows: MatrixRow[] = matrix.map((row) => ({ + userId: row.userId, + userName: row.userName, + email: row.email, + skillId: row.skillId, + skillName: row.skillName, + categoryName: row.categoryName ?? "Uncategorized", + selfComfort: row.selfComfort, + verifiedLevel: row.verifiedLevel, + lastServedOn: row.lastServedOn ?? null, + })); + + const managedUsers: ManagedUser[] = users.map((user) => ({ + id: user.id, + email: user.email, + username: user.username, + firstName: user.firstName, + lastName: user.lastName, + displayName: user.displayName, + systemRole: user.systemRole, + status: user.status, + phoneE164: user.phoneE164, + timezone: user.timezone, + emergencyContact: user.emergencyContact, + notes: user.notes, + deactivatedAt: user.deactivatedAt ? user.deactivatedAt.toISOString() : null, + passwordSet: user.passwordSet, + })); + + const positionRows: PositionSummary[] = positions.map((position) => ({ + id: position.id, + name: position.name, + defaultHeadcount: position.defaultHeadcount, + callTimeOffsetMinutes: position.callTimeOffsetMinutes, + active: position.active, + })); + + const rows: NotificationRow[] = log.map((n) => ({ + id: n.id, + templateKey: n.templateKey, + subject: typeof n.payload.subject === "string" ? n.payload.subject : null, + toAddress: n.toAddress, + status: n.status, + attempts: n.attempts, + scheduledFor: stamp(n.scheduledFor), + sentAt: n.sentAt ? stamp(n.sentAt) : null, + error: n.error, + })); + + return ( +

+
+

Admin

+

+ People, competency, positions, and outbound messages for the media + team. +

+
+ + + + People + + Add people, approve pending sign-ups, and edit every profile and + access field. Deactivate to keep a person's history; delete only + removes accounts with no scheduling history. + + + + ({ id: skill.id, name: skill.name }))} + /> + + + + + + Skill levels + + Who is signed off on what. Verifying records who moved the level and + why; the volunteer's own comfort rating is never changed here. + + + + + + + + + + Positions & requirements + + The seats each service needs and the skills they require. A position + saved as publishable needs at least one core skill. + + + + ({ id: skill.id, name: skill.name }))} + requirementsByPosition={requirementsByPosition} + /> + + + + + + Services & schedule + + Recurring service templates, and instance generation for the weeks + volunteers will be scheduled into. + + + + ({ + id: service.id, + name: service.name, + startTimeLocal: service.startTimeLocal, + durationMinutes: service.durationMinutes, + location: service.location ?? null, + active: service.active, + }))} + /> + + + + + + Reminder rules + + Offsets are relative to each service or event start; negative days + are before. Service reminders are queued when a week is published, + event reminders by the notification cron. Every offset and time is + editable. + + + + + + + + + + Email delivery + + Send through the team's Gmail account with an app password. + Nothing is stored in plain text, and the password is never shown + again after saving. + + + + + + + + + + Backup & restore + + Download every database record and uploaded file in one portable + ZIP, or restore a backup after a redeploy. Restores are admin-only + and require an explicit confirmation. + + + + + + + + + + Notifications + + The outbox log, newest first, with retry for anything that failed. + + + + + + +
+ ); +} diff --git a/src/app/(app)/announcements/page.tsx b/src/app/(app)/announcements/page.tsx index c2edd97..245c6e0 100644 --- a/src/app/(app)/announcements/page.tsx +++ b/src/app/(app)/announcements/page.tsx @@ -1,16 +1,53 @@ -import { StateMessage } from "@/components/app/state-message"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listAnnouncements } from "@/db/announcements"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { + AnnouncementsPanel, + type AnnouncementItem, +} from "@/components/app/announcements-panel"; export const metadata = { title: "Announcements" }; -export default function AnnouncementsPage() { +/** + * Team feed. Published posts are visible to every signed-in volunteer; authors + * (`content.author` = admin/coordinator) see drafts and can create, publish and + * delete. Admin access to the authoring controls lives here rather than a + * duplicate panel in the admin hub. + */ +export default async function AnnouncementsPage() { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined) + ?.systemRole; + const canEdit = hasPermission(role, "content.author"); + const rows = await listAnnouncements({ includeUnpublished: canEdit }); + + const announcements: AnnouncementItem[] = rows.map((row) => ({ + id: row.id, + title: row.title, + body: row.body, + published: row.published, + authorName: row.authorName, + createdLabel: formatInTimezone(row.createdAt, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + month: "short", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "2-digit", + }), + })); + return ( - <> -

Announcements

-

News and notes from the media team.

- - +
+
+

Announcements

+

+ News and notes from the media team. +

+
+ +
); } diff --git a/src/app/(app)/availability/page.tsx b/src/app/(app)/availability/page.tsx new file mode 100644 index 0000000..18e94fe --- /dev/null +++ b/src/app/(app)/availability/page.tsx @@ -0,0 +1,126 @@ +import Link from "next/link"; +import { AlertTriangle } from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listUnavailability } from "@/db/unavailability"; +import { + activeTeamBlackouts, + upcomingServesForUser, +} from "@/db/volunteer"; +import { isUnavailable, type UnavailabilityRecord } from "@/domain/availability"; +import { formatInTimezone, CHURCH_TIMEZONE } from "@/lib/tz"; +import { Badge } from "@/components/ui/badge"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { + AvailabilityManager, + type BlackoutRow, +} from "@/components/app/availability/availability-manager"; + +export const metadata = { title: "Availability" }; + +export default async function AvailabilityPage() { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) return null; + + const [rows, upcoming] = await Promise.all([ + listUnavailability({ userId: user.id }), + upcomingServesForUser(user.id, 20), + ]); + const active = rows.filter((row) => row.status === "active"); + const records = active as unknown as UnavailabilityRecord[]; + const conflicts = upcoming.filter((serve) => isUnavailable(records, serve.occursOn)); + const canManage = hasPermission(user.systemRole, "schedule.publish"); + const team = canManage ? await activeTeamBlackouts() : []; + + const initialRows: BlackoutRow[] = active.map((row) => ({ + id: row.id, + kind: row.kind, + startsOn: row.startsOn, + endsOn: row.endsOn, + reason: row.reason, + rrule: row.rrule, + })); + + return ( +
+
+

Availability

+

+ Add vacations, work trips, and recurring commitments. Coordinators see + these dates when building the schedule. +

+
+ + {conflicts.length > 0 && ( +
+

+

+
    + {conflicts.map((serve) => ( +
  • + {serve.roleName} · {serve.serviceName} —{" "} + {formatInTimezone(serve.startsAt, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + weekday: "short", + month: "short", + day: "numeric", + })}{" "} + ·{" "} + + review the schedule + +
  • + ))} +
+
+ )} + + + + {canManage && ( + + + Team availability +

+ Active blackouts across the roster, soonest first. +

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

+ No active blackout dates on the team. +

+ ) : ( +
    + {team.map((row) => ( +
  • +
    +

    {row.displayName}

    +

    + {row.startsOn === row.endsOn + ? row.startsOn + : `${row.startsOn} → ${row.endsOn}`} + {row.reason ? ` · ${row.reason}` : ""} +

    +
    + {row.kind} +
  • + ))} +
+ )} +
+
+ )} +
+ ); +} diff --git a/src/app/(app)/coverage/page.tsx b/src/app/(app)/coverage/page.tsx new file mode 100644 index 0000000..f66fa75 --- /dev/null +++ b/src/app/(app)/coverage/page.tsx @@ -0,0 +1,108 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { Download, Printer } from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listPendingCoverageRequests } from "@/db/coverage"; +import { listCoverageIntakes } from "@/db/intake"; +import { rankedCandidatesForSlot } from "@/db/rankedCandidates"; +import { Button } from "@/components/ui/button"; +import { + CoverageBoard, + type CoverageRequestView, + type IntakeView, +} from "@/components/app/coverage/coverage-board"; + +export const metadata = { title: "Coverage" }; + +export default async function CoveragePage() { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) return null; + if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home"); + + const [requests, intakes] = await Promise.all([ + listPendingCoverageRequests(), + listCoverageIntakes("new"), + ]); + + const views: CoverageRequestView[] = await Promise.all( + requests.map(async (request) => { + const ranked = await rankedCandidatesForSlot(request.slotId); + return { + id: request.id, + assignmentId: request.assignmentId, + slotId: request.slotId, + roleName: request.roleName, + serviceName: request.serviceName, + startsAt: request.startsAt, + callTime: request.callTime, + location: request.location, + reason: request.reason, + requesterName: request.requesterName, + requesterEmail: request.requesterEmail, + eligible: (ranked?.eligible ?? []).map((candidate) => ({ + userId: candidate.userId, + displayName: candidate.displayName, + score: candidate.score, + warnings: candidate.warnings, + })), + excludedCount: ranked?.excluded.length ?? 0, + }; + }), + ); + + const intakeViews: IntakeView[] = intakes.map((intake) => ({ + id: intake.id, + title: intake.title, + requesterName: intake.requesterName, + requesterEmail: intake.requesterEmail, + ministry: intake.ministry, + startsAt: intake.startsAt, + location: intake.location, + description: intake.description, + })); + + return ( +
+
+
+

Coverage

+

+ Approve swaps, release seats, and turn church requests into events. +

+
+
+ + + +
+
+ + + +

+ Share the public request form at{" "} + + /request-coverage + + . It does not require an account. +

+
+ ); +} diff --git a/src/app/(app)/dashboard/page.tsx b/src/app/(app)/dashboard/page.tsx new file mode 100644 index 0000000..e6dc67c --- /dev/null +++ b/src/app/(app)/dashboard/page.tsx @@ -0,0 +1,301 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { + AlertTriangle, + ArrowRight, + CalendarCheck, + CalendarX, + CircleHelp, + MailWarning, + UserCheck, + Users, +} from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { coverageGaps, dashboardSnapshot } from "@/db/dashboard"; +import { CHURCH_TIMEZONE, formatInTimezone, weekStartOn } from "@/lib/tz"; +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; + +export const metadata = { title: "Coverage dashboard" }; + +function dateLabel(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + weekday: "short", + month: "short", + day: "numeric", + }); +} + +function Stat({ + label, + value, + detail, + tone = "normal", +}: { + label: string; + value: number; + detail: string; + tone?: "normal" | "warning"; +}) { + return ( + + +

+ {label} +

+

+ {value} +

+

{detail}

+
+
+ ); +} + +export default async function DashboardPage() { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined) + ?.systemRole; + if (!hasPermission(role, "schedule.publish")) redirect("/home"); + + const [snapshot, gaps] = await Promise.all([ + dashboardSnapshot(), + coverageGaps(6), + ]); + const next = snapshot.nextService; + + return ( +
+
+
+

+ Coverage dashboard +

+

+ The next five weeks at a glance, plus the queues that need a + coordinator. +

+
+ +
+ +
+ + 0 ? "Needs a volunteer" : "All seats covered"} + tone={snapshot.open > 0 ? "warning" : "normal"} + /> + 0 ? "warning" : "normal"} + /> + 0 ? "warning" : "normal"} + /> +
+ +
+ + + + + + + {next ? ( + <> +
+
+

{next.serviceName}

+

+ {dateLabel(next.startsAt)} ·{" "} + {formatInTimezone(next.startsAt, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + hour: "numeric", + minute: "2-digit", + })} +

+
+ + {next.status} + +
+
+ + {next.filled} / {next.seats} filled + + + {Math.max(0, next.seats - next.filled)} open + + {snapshot.unconfirmedNext > 0 && ( + + {snapshot.unconfirmedNext} unconfirmed + + )} +
+ + + ) : ( +

+ No service instances in the next five weeks. Generate instances + from Admin → Services. +

+ )} +
+
+ +
+ + +

+

+

+ {snapshot.upcomingEvents} upcoming event + {snapshot.upcomingEvents === 1 ? "" : "s"} ·{" "} + {snapshot.eventsNeedingPhotographer} without a lead photographer +

+ + Review events + +
+
+ + + +

+

+

+ {snapshot.failedNotifications === 0 + ? "No failed messages." + : `${snapshot.failedNotifications} failed message${ + snapshot.failedNotifications === 1 ? "" : "s" + } need attention.`} +

+ + Open notification log + +
+
+
+
+ + + + + + + + {gaps.length === 0 ? ( +

+ Every seat in the next five weeks is filled. Nice work. +

+ ) : ( +
    + {gaps.map((gap) => ( +
  • +
    +

    {gap.serviceName}

    +

    + {dateLabel(gap.startsAt)} +

    +
    +
    + + {gap.seats - gap.filled} open + + + Fill + +
    +
  • + ))} +
+ )} +
+
+ +
+ + + + + + + +
+
+ ); +} diff --git a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx new file mode 100644 index 0000000..a2cf45b --- /dev/null +++ b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx @@ -0,0 +1,102 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { ArrowLeft } from "lucide-react"; +import { auth } from "@/auth/config"; +import type { SystemRole } from "@/auth/roles"; +import { getFolderDetail } from "@/db/events"; +import { + isBrowserRenderablePhoto, + isEditableEventPhoto, +} from "@/lib/event-photos"; +import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; +import { Badge } from "@/components/ui/badge"; +import { + PhotoGallery, + type GalleryPhoto, +} from "@/components/app/events/photo-gallery"; + +const KIND_LABELS: Record = { + originals: "RAW / originals", + edited: "Edited exports", + mixed: "Mixed", +}; + +function sizeLabel(bytes: number): string { + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + if (bytes < 1024 * 1024 * 1024) { + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + } + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +/** + * A folder's gallery. Every assigned photographer can see and download every + * file; only the uploader or an event manager can delete one. + */ +export default async function EventFolderPage({ + params, +}: { + params: Promise<{ id: string; folderId: string }>; +}) { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) redirect("/login"); + + const { id, folderId } = await params; + const detail = await getFolderDetail(folderId, user.id, user.systemRole); + if (!detail || detail.event.id !== id) notFound(); + + const photos: GalleryPhoto[] = detail.photos.map((photo) => ({ + id: photo.id, + filename: photo.filename, + sizeBytes: photo.sizeBytes, + kind: photo.kind, + uploaderId: photo.uploaderId, + uploaderName: photo.uploaderName, + previewable: isBrowserRenderablePhoto(photo.filename), + editable: isEditableEventPhoto(photo.filename), + adjustments: parseStoredPhotoAdjustments(photo.editJson), + editedAt: photo.editedAt ? photo.editedAt.toISOString() : null, + editedSizeBytes: photo.editedSizeBytes, + })); + + return ( +
+
+ +
+ +
+
+

+ {detail.folder.name} +

+

+ {detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "} + · {sizeLabel(detail.folder.totalBytes)} +

+
+ + {KIND_LABELS[detail.folder.kind] ?? detail.folder.kind} + +
+ + +
+ ); +} diff --git a/src/app/(app)/events/[id]/page.tsx b/src/app/(app)/events/[id]/page.tsx new file mode 100644 index 0000000..8b1218d --- /dev/null +++ b/src/app/(app)/events/[id]/page.tsx @@ -0,0 +1,325 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { ArrowLeft, Camera, Download, Film, FolderOpen, MapPin, Play } from "lucide-react"; +import { auth } from "@/auth/config"; +import type { SystemRole } from "@/auth/roles"; +import { getEventDetail, listAssignableUsers } from "@/db/events"; +import { listEventVideos } from "@/db/videos"; +import { formatVideoDuration } from "@/lib/event-videos"; +import { + checkArchiveDestination, + getStorageSettings, +} from "@/db/storage-settings"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { Badge } from "@/components/ui/badge"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { + PhotographerPanel, + type EventPhotographer, +} from "@/components/app/events/photographer-panel"; +import { FolderCreateForm } from "@/components/app/events/folder-create-form"; +import { DeleteEventButton } from "@/components/app/events/delete-event-button"; +import { ArchiveEventButton } from "@/components/app/events/archive-event-button"; +import { VideoUploadForm } from "@/components/app/media/video-upload-form"; +import { Button } from "@/components/ui/button"; + +const KIND_LABELS: Record = { + originals: "RAW / originals", + edited: "Edited exports", + mixed: "Mixed", +}; + +function when(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + weekday: "long", + month: "long", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "2-digit", + }); +} + +function sizeLabel(bytes: number): string { + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + if (bytes < 1024 * 1024 * 1024) { + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + } + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +/** + * One event: brief, assigned photographers, and the shared folders. Managers + * assign people; any assignee can create folders. Folder pages own uploads; + * the event header downloads every photo as one ZIP. + */ +export default async function EventDetailPage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) redirect("/login"); + + const { id } = await params; + const event = await getEventDetail(id, user.id, user.systemRole); + if (!event) notFound(); + + const users = event.canManage ? await listAssignableUsers() : []; + const archiveSettings = await getStorageSettings(); + const archiveStatus = await checkArchiveDestination(archiveSettings); + const videos = await listEventVideos(event.event.id); + const photographers: EventPhotographer[] = event.event.photographers.map( + (person) => ({ + userId: person.userId, + name: person.name, + email: person.email, + role: person.role, + }), + ); + + return ( +
+
+ +
+ +
+
+

+ {event.event.title} +

+ {event.event.eventType} +
+ {event.event.photoCount > 0 && ( + + )} + {event.canManage && archiveStatus.ready && ( + + )} + {event.canManage && ( + + )} +
+
+

+ {when(event.event.startsAt)} +

+ {event.event.location && ( +

+

+ )} + {event.event.description && ( +

+ {event.event.description} +

+ )} + {event.canManage && !archiveStatus.ready && ( +

+ NFS archive is not ready. {archiveStatus.message}{" "} + + Configure archive + {" "} + before deleting finished events. +

+ )} +
+ + + + + + + + ({ + id: person.id, + name: person.name, + email: person.email, + }))} + canManage={event.canManage} + /> + + + + + + + + + + {event.folders.length === 0 ? ( +

+ No folders yet. Create one for originals, dumps, or edited selects. +

+ ) : ( +
    + {event.folders.map((folder) => ( +
  • + +
    +

    + {folder.name} +

    + + {KIND_LABELS[folder.kind] ?? folder.kind} + +
    +

    + {folder.photoCount} photo + {folder.photoCount === 1 ? "" : "s"} ·{" "} + {sizeLabel(folder.totalBytes)} +

    + +
  • + ))} +
+ )} + + {event.canContribute ? ( + + ) : ( +

+ Only assigned photographers, coordinators and admins can add + folders or upload. +

+ )} +
+
+ + + + + + + + {videos.length === 0 ? ( +

+ No videos yet. The camera original is archived on NFS and a web + MP4 is generated for playback. +

+ ) : ( +
    + {videos.map((video) => { + const version = ( + video.processedAt ?? video.updatedAt + ).getTime(); + return ( +
  • + +
    + {video.posterStoredName ? ( + // Frames are private; the serving route applies the + // event access check. + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
    +
    + )} + + {formatVideoDuration(video.durationMs)} + + {video.status === "processing" && ( + + Processing + + )} + {video.status === "failed" && ( + + Failed + + )} + {video.status === "ready" && ( + + + + + )} +
    +
    +

    + {video.title} +

    +

    + {video.visibility === "team" + ? "Media team only" + : video.visibility === "unlisted" + ? "Unlisted link" + : "Public"}{" "} + · {sizeLabel(video.sizeBytes)} original +

    +
    + +
  • + ); + })} +
+ )} + + {event.canContribute && ( + + )} + {!event.canContribute && ( +

+ Only assigned photographers, coordinators and admins can upload + videos. +

+ )} +
+
+
+ ); +} diff --git a/src/app/(app)/events/page.tsx b/src/app/(app)/events/page.tsx new file mode 100644 index 0000000..2fe3e5a --- /dev/null +++ b/src/app/(app)/events/page.tsx @@ -0,0 +1,148 @@ +import Link from "next/link"; +import { CalendarDays, MapPin, Users } from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listEventsForUser } from "@/db/events"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { Badge } from "@/components/ui/badge"; +import { StateMessage } from "@/components/app/state-message"; +import { EventCreateForm } from "@/components/app/events/event-create-form"; + +export const metadata = { title: "Events" }; + +function when(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + weekday: "short", + month: "short", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "2-digit", + }); +} + +function EventCard({ + event, +}: { + event: Awaited>[number]; +}) { + return ( + +
+
+

{event.title}

+

+

+ {event.location && ( +

+

+ )} +
+ {event.eventType} +
+
+ + + + {event.folderCount} folder{event.folderCount === 1 ? "" : "s"} + + + {event.photoCount} photo{event.photoCount === 1 ? "" : "s"} + +
+ + ); +} + +/** + * Event photography hub. Managers (coordinators/admins) see every event and + * can create one; photographers see only events they are assigned to. Opening + * an event shows its shared folders, where any assignee can upload originals and + * download someone else's files to edit. + */ +export default async function EventsPage() { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + const role = user?.systemRole; + const events = await listEventsForUser(user?.id ?? "", role); + const canManage = hasPermission(role, "schedule.publish"); + const now = Date.now(); + const upcoming = events + .filter((event) => event.startsAt.getTime() >= now) + .sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime()); + const past = events.filter((event) => event.startsAt.getTime() < now); + + return ( +
+
+

Events

+

+ Photographers assigned to an event share originals and edited files in + its folders. Anyone assigned can download from the folder to edit. +

+
+ + {canManage && ( +
+ + Create an event + +
+ +
+
+ )} + + {events.length === 0 ? ( + + ) : ( +
+ {upcoming.length > 0 && ( +
+

+ Upcoming +

+
+ {upcoming.map((event) => ( + + ))} +
+
+ )} + {past.length > 0 && ( +
+

+ Past +

+
+ {past.map((event) => ( + + ))} +
+
+ )} +
+ )} +
+ ); +} diff --git a/src/app/(app)/home/page.tsx b/src/app/(app)/home/page.tsx new file mode 100644 index 0000000..e412fa2 --- /dev/null +++ b/src/app/(app)/home/page.tsx @@ -0,0 +1,310 @@ +import Link from "next/link"; +import { + ArrowRight, + CalendarDays, + CalendarPlus, + ClipboardCheck, + MapPin, + UserRound, +} from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { getUserById } from "@/db/users"; +import { + pastServesForUser, + upcomingEventAssignmentsForUser, + upcomingServesForUser, +} from "@/db/volunteer"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { AssignmentActions } from "@/components/app/assignment-actions"; +import { CoverageRequestButton } from "@/components/app/coverage/coverage-request-button"; +import { coverageRequestsForUser } from "@/db/coverage"; + +export const metadata = { title: "Home" }; + +function when(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + weekday: "long", + month: "long", + day: "numeric", + }); +} + +function time(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + hour: "numeric", + minute: "2-digit", + }); +} + +function roleLabel(role: string): string { + return role.replaceAll("_", " "); +} + +export default async function HomePage() { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) return null; + + const profile = await getUserById(user.id); + const [upcoming, past, events, coverage] = await Promise.all([ + upcomingServesForUser(user.id, 6), + pastServesForUser(user.id, 3), + upcomingEventAssignmentsForUser(user.id), + coverageRequestsForUser(user.id), + ]); + const pendingCoverage = new Set( + coverage.filter((row) => row.status === "pending").map((row) => row.assignmentId), + ); + const next = upcoming[0] ?? null; + const canManage = hasPermission(user.systemRole, "schedule.publish"); + const firstName = profile?.firstName || "there"; + + return ( +
+
+
+

+ Hi, {firstName} +

+

+ Your next serving date, assignments, and the things that need a + response. +

+
+
+ + +
+
+ + {next ? ( + + +
+
+ + +
+

+ Your next serve +

+ + {next.roleName} · {next.serviceName} + +
+
+ + {next.status} + +
+
+ +
+

{when(next.startsAt)}

+

+ Service {time(next.startsAt)} + {next.callTime ? ` · call time ${time(next.callTime)}` : ""} +

+ {next.location && ( +

+

+ )} +
+ +
+ + +
+ {next.status === "proposed" && ( +

+

+ )} +
+
+ ) : ( + + +

No upcoming serving dates

+

+ When a coordinator puts you on the schedule, it will appear here. +

+ +
+
+ )} + +
+ + + Coming up + + + {upcoming.length <= 1 ? ( +

+ Nothing else scheduled yet. +

+ ) : ( +
    + {upcoming.slice(1).map((serve) => ( +
  • +
    +

    + {serve.roleName} · {serve.serviceName} +

    +

    + {when(serve.startsAt)} + {serve.callTime ? ` · call ${time(serve.callTime)}` : ""} +

    +
    + + {serve.status} + +
  • + ))} +
+ )} + + Full schedule + +
+
+ + + + Event coverage + + + {events.length === 0 ? ( +

+ No upcoming photography or editing assignments. +

+ ) : ( +
    + {events.map((event) => ( +
  • + + {event.title} + +

    + {roleLabel(event.role)} · {when(event.startsAt)} + {event.location ? ` · ${event.location}` : ""} +

    +
  • + ))} +
+ )} + + All events + +
+
+
+ + {past.length > 0 && ( + + + Recently served + + +
    + {past.map((serve) => ( +
  • + + {serve.roleName} · {serve.serviceName} + + + {when(serve.startsAt)} + +
  • + ))} +
+
+
+ )} + + {canManage && ( + + +
+

Coordinator tools

+

+ Coverage, open seats, approvals, and notification health. +

+
+ +
+
+ )} +
+ ); +} diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index 7ad0542..658b107 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -1,11 +1,14 @@ -import { auth } from "@/auth/config"; import { redirect } from "next/navigation"; +import { auth } from "@/auth/config"; +import { getUserSecurity } from "@/db/users"; import { AppLayout } from "@/components/app/app-layout"; +import type { SystemRole } from "@/auth/roles"; /** * Authenticated shell wrapper. Any route under the `(app)` group requires a * session; unauthenticated visitors are sent to /login. The visible shell - * (header, nav, main, footer) is provided by AppLayout. + * (header, nav, main, footer) is provided by AppLayout, which receives the + * role so the admin-only tab is only rendered for admins. */ export default async function AppGroupLayout({ children, @@ -14,5 +17,13 @@ export default async function AppGroupLayout({ }) { const session = await auth(); if (!session?.user) redirect("/login"); - return {children}; + const userId = (session.user as { id?: string }).id; + if (!userId) redirect("/login"); + // A magic-link session is enough to reach the setup page, but not the rest + // of the app until the person has chosen credentials. + const security = await getUserSecurity(userId); + if (!security) redirect("/login"); + if (!security.passwordHash) redirect("/welcome"); + const role = (session.user as { systemRole?: SystemRole }).systemRole; + return {children}; } diff --git a/src/app/(app)/media/[id]/page.tsx b/src/app/(app)/media/[id]/page.tsx new file mode 100644 index 0000000..64985a3 --- /dev/null +++ b/src/app/(app)/media/[id]/page.tsx @@ -0,0 +1,78 @@ +import Link from "next/link"; +import { notFound, redirect } from "next/navigation"; +import { ArrowLeft, CalendarDays } from "lucide-react"; +import { auth } from "@/auth/config"; +import type { SystemRole } from "@/auth/roles"; +import { getEventVideoAccess } from "@/db/videos"; +import { mediaOrigin } from "@/lib/media-url"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { videoView } from "@/lib/video-view"; +import { VideoEditor } from "@/components/app/media/video-editor"; + +export const metadata = { title: "Video" }; +export const dynamic = "force-dynamic"; + +export default async function MediaVideoPage({ + params, +}: { + params: Promise<{ id: string }>; +}) { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + if (!user?.id) redirect("/login"); + + const { id } = await params; + const access = await getEventVideoAccess(id, user.id, user.systemRole); + if (!access) notFound(); + + const origin = await mediaOrigin(); + const video = videoView( + { + ...access.video, + eventTitle: access.event.title, + eventStartsAt: access.event.startsAt, + }, + origin, + ); + + return ( +
+ +
+ ); +} diff --git a/src/app/(app)/media/page.tsx b/src/app/(app)/media/page.tsx new file mode 100644 index 0000000..47d1806 --- /dev/null +++ b/src/app/(app)/media/page.tsx @@ -0,0 +1,263 @@ +import Link from "next/link"; +import { + Clock3, + FileImage, + Film, + Image as ImageIcon, + Play, +} from "lucide-react"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listEventsForUser } from "@/db/events"; +import { listMediaPhotosForEvents } from "@/db/media"; +import { listEventVideosForEvents } from "@/db/videos"; +import { + checkArchiveDestination, + getStorageSettings, +} from "@/db/storage-settings"; +import { formatVideoDuration } from "@/lib/event-videos"; +import { isBrowserRenderablePhoto } from "@/lib/event-photos"; +import { mediaOrigin } from "@/lib/media-url"; +import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; +import { videoView } from "@/lib/video-view"; +import { Badge } from "@/components/ui/badge"; +import { StateMessage } from "@/components/app/state-message"; +import { VideoUploadForm } from "@/components/app/media/video-upload-form"; + +export const metadata = { title: "Media" }; +export const dynamic = "force-dynamic"; + +function day(date: Date): string { + return formatInTimezone(date, CHURCH_TIMEZONE, { + timeZone: CHURCH_TIMEZONE, + month: "short", + day: "numeric", + year: "numeric", + }); +} + +function bytesLabel(bytes: number): string { + if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; + if (bytes < 1024 * 1024 * 1024) { + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + } + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +/** + * The media library: every event photo and video the signed-in user can open. + * Photos remain protected by event access; video cards link to the watch/editor + * page where managers can publish an unlisted/public version. + */ +export default async function MediaPage() { + const session = await auth(); + const user = session?.user as + | { id?: string; systemRole?: SystemRole } + | undefined; + const role = user?.systemRole; + const events = await listEventsForUser(user?.id ?? "", role); + const eventIds = events.map((event) => event.id); + const origin = await mediaOrigin(); + const [videos, photos, storage] = await Promise.all([ + listEventVideosForEvents(eventIds), + listMediaPhotosForEvents(eventIds), + getStorageSettings(), + ]); + const archiveStatus = await checkArchiveDestination(storage); + const canManage = hasPermission(role, "schedule.publish"); + const videoCards = videos.map((video) => videoView(video, origin)); + + return ( +
+
+

Media

+

+ An ad-free library of every event photo and video you can access. + Videos stay private to the team until a manager publishes an unlisted + or public version. +

+
+ +
+
+
+

+

+

+ Camera originals live on the NFS archive; playback uses a generated + MP4. +

+
+ + {videoCards.length} video{videoCards.length === 1 ? "" : "s"} + +
+ + ({ + id: event.id, + title: event.title, + }))} + canManage={canManage} + archiveReady={archiveStatus.ready} + /> + + {videoCards.length === 0 ? ( + + ) : ( +
+ {videoCards.map((video) => ( + +
+ {video.posterUrl && video.status !== "failed" ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
+
+ )} + + {formatVideoDuration(video.durationMs)} + + {(video.status !== "ready" || video.isShareable) && ( +
+ {video.status !== "ready" && ( + + {video.status === "failed" ? "Failed" : "Processing"} + + )} + {video.isShareable && ( + + {video.visibility} + + )} +
+ )} + + + + +
+
+

+ {video.title} +

+

+ {video.eventTitle} · {day(new Date(video.eventStartsAt))} +

+

+ {bytesLabel(video.sizeBytes)} original +

+
+ + ))} +
+ )} +
+ +
+
+
+

+

+

+ Every photo in the event folders you can open. Download originals + from the event folder. +

+
+ + {photos.length} photo{photos.length === 1 ? "" : "s"} + +
+ + {photos.length === 0 ? ( + + ) : ( +
+ {photos.map((photo) => { + const previewable = + Boolean(photo.editedAt) || + isBrowserRenderablePhoto(photo.filename); + const version = photo.editedAt + ? Date.parse(photo.editedAt.toISOString()) + : 0; + const src = `/api/events/${photo.eventId}/folders/${photo.folderId}/photos/${photo.id}${ + photo.editedAt ? `?variant=edited&v=${version}` : "" + }`; + return ( + +
+ {previewable ? ( + // eslint-disable-next-line @next/next/no-img-element + {photo.filename} + ) : ( + + + )} +
+
+

+ {photo.filename} +

+

+ {photo.eventTitle} · {photo.folderName} +

+

+ {bytesLabel(photo.sizeBytes)} +

+
+ + ); + })} +
+ )} +
+ +

+

+
+ ); +} diff --git a/src/app/(app)/profile/page.tsx b/src/app/(app)/profile/page.tsx new file mode 100644 index 0000000..d5e81b0 --- /dev/null +++ b/src/app/(app)/profile/page.tsx @@ -0,0 +1,73 @@ +import Link from "next/link"; +import { redirect } from "next/navigation"; +import { ArrowLeft } from "lucide-react"; +import { auth } from "@/auth/config"; +import { getProfile } from "@/db/profile"; +import { getUserSkills } from "@/db/userSkills"; +import { listSkills } from "@/db/positions"; +import { getOrCreateCalendarFeedToken } from "@/db/volunteer"; +import { mediaOrigin } from "@/lib/media-url"; +import { ProfilePanel } from "@/components/app/profile-panel"; + +export const metadata = { title: "My profile" }; +export const dynamic = "force-dynamic"; + +export default async function ProfilePage() { + const session = await auth(); + const user = session?.user as { id?: string } | undefined; + if (!user?.id) redirect("/login"); + + const [profile, skillRows, allSkills, token, origin] = await Promise.all([ + getProfile(user.id), + getUserSkills(user.id), + listSkills({ active: true }), + getOrCreateCalendarFeedToken(user.id), + mediaOrigin(), + ]); + const bySkill = new Map(skillRows.map((row) => [row.skillId, row])); + + return ( +
+
+ +
+ + ({ + id: skill.id, + name: skill.name, + verifiedLevel: bySkill.get(skill.id)?.verifiedLevel ?? "none", + selfComfort: bySkill.get(skill.id)?.selfComfort ?? null, + }))} + feedUrl={`${origin}/api/calendar/${token}`} + /> +
+ ); +} diff --git a/src/app/(app)/roster/page.tsx b/src/app/(app)/roster/page.tsx index 8e6d08a..9dc1828 100644 --- a/src/app/(app)/roster/page.tsx +++ b/src/app/(app)/roster/page.tsx @@ -1,16 +1,78 @@ +import Link from "next/link"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { listUsers } from "@/db/admin"; +import { Badge } from "@/components/ui/badge"; import { StateMessage } from "@/components/app/state-message"; export const metadata = { title: "Roster" }; -export default function RosterPage() { +/** + * The team list. Everyone signed in can see who serves on the team and their + * role; admins additionally get a link to the people controls in /admin. + */ +export default async function RosterPage() { + const session = await auth(); + const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole; + const isAdmin = hasPermission(role, "admin.settings"); + const team = (await listUsers()).filter((u) => u.status === "active"); + return ( - <> -

Roster

-

The team, their roles, and how to reach them.

- - +
+
+
+

Roster

+

+ The team, their roles, and how to reach them. +

+
+ {isAdmin && ( + + Manage people + + )} +
+ + {team.length === 0 ? ( + + ) : ( +
+ + + + + + + + + + {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. +

+