From f7a0c8618fab9c8eba8aa09addd8278cadf85161 Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Fri, 20 Nov 2026 23:21:34 +0000 Subject: [PATCH] feat(media): primary media storage, growth goals, retention and delivery tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Event photos and videos are now stored only on the NFS/local share named in Settings -> Media storage. Uploads, photo editing, video processing and the per-event filing step refuse to run until that share is configured and writable, so nothing is silently written inside the container. Video originals, renditions, posters and sidecars share one folder on the share. Also adds volunteer growth goals with a mentor queue, an admin retention and storage sweep with a cron entry point, cached gallery thumbnails with per-folder ZIP downloads, a server-rendered booth-sheet PDF, and in-app confirm/release for every upcoming assignment. Service reminders now ignore the one-off event reminder rule, which had been queueing an extra bogus reminder for each published service. Generated with Codebuff πŸ€– Co-Authored-By: Codebuff --- .env.example | 19 +- README.md | 45 ++- docker-compose.yml | 15 +- docs/PROJECT-STATE.md | 7 +- e2e/admin.spec.ts | 6 +- e2e/events.spec.ts | 5 +- e2e/growth-and-maintenance.spec.ts | 187 +++++++++ e2e/media.spec.ts | 10 +- e2e/photo-archive.spec.ts | 5 +- package.json | 1 + pnpm-lock.yaml | 37 ++ src/app/(app)/admin/page.tsx | 93 ++++- .../events/[id]/folders/[folderId]/page.tsx | 32 +- src/app/(app)/events/[id]/page.tsx | 31 +- src/app/(app)/home/page.tsx | 26 +- src/app/(app)/media/page.tsx | 65 +++- src/app/(app)/profile/page.tsx | 44 ++- src/app/(app)/run-sheet/[instanceId]/page.tsx | 19 +- src/app/(app)/settings/page.tsx | 21 +- src/app/(app)/training/guides/admin/page.tsx | 2 +- src/app/api/dev/cron/retention/route.ts | 32 ++ src/app/api/dev/retention/route.ts | 50 +++ src/app/api/dev/storage/route.ts | 2 +- src/app/api/events/[id]/archive/route.ts | 24 +- src/app/api/events/[id]/download/route.ts | 26 +- .../[folderId]/photos/[photoId]/edit/route.ts | 10 +- .../photos/[photoId]/export/route.ts | 11 +- .../photos/[photoId]/preview/route.ts | 7 +- .../[folderId]/photos/[photoId]/route.ts | 16 +- .../photos/[photoId]/thumb/route.ts | 118 ++++++ .../[id]/folders/[folderId]/photos/route.ts | 8 +- src/app/api/events/[id]/route.ts | 41 +- .../[id]/videos/[videoId]/original/route.ts | 6 +- .../api/events/[id]/videos/[videoId]/route.ts | 20 +- src/app/api/events/[id]/videos/chunk/route.ts | 17 +- src/app/api/events/[id]/videos/route.ts | 17 +- src/app/api/growth-goals/route.ts | 107 +++++ src/app/api/media/[id]/poster/route.ts | 10 +- src/app/api/media/[id]/stream/route.ts | 14 +- .../api/run-sheet/[instanceId]/pdf/route.ts | 41 ++ src/components/app/admin/retention-panel.tsx | 199 ++++++++++ .../app/events/archive-event-button.tsx | 11 +- src/components/app/events/photo-gallery.tsx | 37 +- .../app/growth/growth-goals-panel.tsx | 207 ++++++++++ .../app/growth/mentor-queue-panel.tsx | 242 ++++++++++++ .../app/media/video-upload-form.tsx | 16 +- src/components/app/storage-panel.tsx | 25 +- src/db/events.ts | 4 +- src/db/growthGoals.ts | 368 ++++++++++++++++++ src/db/reminders.ts | 6 +- src/db/retention.ts | 300 ++++++++++++++ src/db/schema.ts | 8 +- src/db/storage-settings.ts | 4 +- src/db/videos.ts | 8 +- src/lib/booth-sheet-pdf.test.ts | 75 ++++ src/lib/booth-sheet-pdf.ts | 360 +++++++++++++++++ src/lib/event-nfs-archive.ts | 7 +- src/lib/event-photos.test.ts | 17 +- src/lib/event-photos.ts | 38 +- src/lib/event-videos.ts | 40 +- src/lib/media-storage.test.ts | 40 ++ src/lib/media-storage.ts | 138 +++++++ src/lib/retention.test.ts | 46 +++ src/lib/retention.ts | 54 +++ src/lib/uploads.ts | 7 +- src/lib/video-processing.ts | 19 +- src/lib/video-render.ts | 2 +- src/lib/video-renditions.ts | 9 +- 68 files changed, 3237 insertions(+), 297 deletions(-) create mode 100644 e2e/growth-and-maintenance.spec.ts create mode 100644 src/app/api/dev/cron/retention/route.ts create mode 100644 src/app/api/dev/retention/route.ts create mode 100644 src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/thumb/route.ts create mode 100644 src/app/api/growth-goals/route.ts create mode 100644 src/app/api/run-sheet/[instanceId]/pdf/route.ts create mode 100644 src/components/app/admin/retention-panel.tsx create mode 100644 src/components/app/growth/growth-goals-panel.tsx create mode 100644 src/components/app/growth/mentor-queue-panel.tsx create mode 100644 src/db/growthGoals.ts create mode 100644 src/db/retention.ts create mode 100644 src/lib/booth-sheet-pdf.test.ts create mode 100644 src/lib/booth-sheet-pdf.ts create mode 100644 src/lib/media-storage.test.ts create mode 100644 src/lib/media-storage.ts create mode 100644 src/lib/retention.test.ts create mode 100644 src/lib/retention.ts diff --git a/.env.example b/.env.example index 2ba68e0..be27c9a 100644 --- a/.env.example +++ b/.env.example @@ -65,18 +65,25 @@ 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 25 MB each). +# Training attachments only (metadata in Postgres, bytes on disk; max 25 MB +# each). Event photos and videos are NOT stored here; they live on the media +# storage share below. 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: +# Primary storage for original event photos and videos. Mount the NFS export +# (or any local directory) 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). +# Then set the share name and folder in Settings β†’ Media storage. Photo/video +# uploads and photo editing stay disabled until that check passes; the app never +# writes event media inside the container. ARCHIVE_DIR=/archive ARCHIVE_FOLDER=Glenloch Media +# Human-readable share, e.g. nas.local:/volume1/church-media or /mnt/media. +# Required in app settings (Settings β†’ Media storage); this seeds the default. NFS_SHARE= -# Host path bind-mounted at /archive. Leave empty to use the archive-data volume. +# Host path bind-mounted at /archive. Point this at real storage; the app blocks +# media writes on a Docker-managed named volume. MEDIA_ARCHIVE_DIR= # Observability (declared; no Sentry integration is wired yet) diff --git a/README.md b/README.md index 36d3516..83b556a 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It - Database outbox with atomic claiming, a `queued β†’ sending β†’ sent` state machine, retry backoff (5/30/120 minutes, three attempts), and stale-send recovery. - Per-user email preference, lead time, digest flag, and quiet hours (quiet hours only gate SMS; there is no SMS transport). - Admin-editable reminder rules: default 7 days out, Friday before at 18:00, and a day-of rule. Timing and channel set are runtime data, not code. -- Publish-time assignment email and reminders, with signed single-use confirm/decline links that work without signing in. +- Publish-time assignment email and reminders, with signed single-use confirm/decline links that work without signing in; every upcoming assignment can also be confirmed or released in-app from the home page. - Declines cancel that assignment's queued mail; late assignments enqueue their own mail; unpublishing cancels the week's queued mail. - Admin outbox log with retry and test-send. @@ -61,13 +61,15 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It - Volunteers record self-comfort; mentors/admins verify the real level. Every level change appends an assessment-history row. - Per-skill mentor opt-in and persisted admin approval; trainee shadow seats require a paired, mentor-ready volunteer. - Skills matrix, readiness scoring, and growth-goal domain rules. -- Rich-text training lessons with headings, lists, links, inline images (align, resize, drag to reorder), and PDF/Word/text manuals up to 25 MB, plus draft/publish controls and separate admin/volunteer guides. +- Rich-text training lessons with headings, lists, links, inline images (align, resize, caption, drag to reorder), and PDF/Word/text manuals up to 25 MB, plus draft/publish controls and separate admin/volunteer guides. +- Growth goals: volunteers ask to level up a skill, coordinators assign a mentor who is actually mentor-ready, and shadows are logged until the goal is achieved (verification itself stays in the matrix). +- Retention and storage report in the admin console: what the outbox, token tables and upload volume hold, and an explicit sweep for finished mail, used tokens and orphan files. ### Events and media - One-off events with a shot brief, location, times, photographer/editor assignments, and per-event shared folders. - RAW and JPEG uploads streamed to disk, SHA-256 dedupe per folder, authenticated downloads, and manager-only event deletion with file cleanup. -- Photo gallery with preview, non-destructive adjustments/presets, export, and NFS archive of originals + edits + manifest. +- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, per-folder or whole-event ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share β€” never in container-local storage. - Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode. - Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/`, a minimal `/embed/` iframe, and an oEmbed endpoint. - Announcements feed with draft/publish/delete for coordinators and admins. @@ -75,8 +77,8 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It ### Calendars, exports, and admin - Personal ICS calendar feed with a rotatable token. -- Schedule and service-history CSV exports; browser print-to-PDF for rosters and run sheets. -- Admin console: people, skill matrix, positions and requirements, service templates, reminder rules, email delivery, notification log, archive storage, and backup/restore. +- Schedule and service-history CSV exports; a server-rendered PDF booth sheet for any service; browser print-to-PDF for rosters. +- Admin console: people, skill matrix, positions and requirements, service templates, reminder rules, email delivery, notification log, media storage, and backup/restore. - Runtime settings stored in Postgres, including encrypted Gmail credentials, so mail identity and storage paths change without a deploy. ## Stack @@ -171,12 +173,12 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `. | `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. | | `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. | | `OUTBOX_DIR` | Console email transport directory (`/tmp/outbox` in compose). | -| `UPLOAD_DIR` | Training attachments and event photo/video bytes (`/tmp/uploads` in compose). | -| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Archive mount path inside the container, the reported NFS share, and the default archive subfolder. | +| `UPLOAD_DIR` | Training attachments only (`/tmp/uploads` in compose). Event photos and videos never live here. | +| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Mount path inside the container, the reported share, and the default folder. This is the primary storage for original event photos and videos; a named share plus a writable path is required or uploads and photo editing stay disabled. | | `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. | | `SENTRY_DSN` | Declared but not wired to any integration. | -Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount. Back these up together. +Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount (the latter is what holds original photos and videos). Back these up together. ## Email delivery @@ -206,8 +208,8 @@ Set `CRON_SECRET` before enabling the timer; without it the routes only accept a Admin β†’ Backup & restore downloads one ZIP containing: - `dump.sql` β€” schema, data, constraints, indexes, and the migration ledger; -- `uploads/` β€” training attachments, event photos, and video derivatives; -- `archive/` β€” the NFS/archive mount, including untouched camera originals and finished photo archives; +- `uploads/` β€” training attachments; +- `archive/` β€” the media storage mount: original event photos, video originals/derivatives, and dated delivery folders; - `manifest.json` β€” timestamp, app version, SHA-256 checksum, and included areas. The manifest excludes `.env` and the console outbox. **Store `NEXTAUTH_SECRET` with the backup** β€” it decrypts the stored Gmail app password. @@ -259,7 +261,7 @@ This is the full path for a fresh Ubuntu 22.04/24.04 host using Docker. The resu - 2 vCPU and 2 GB RAM minimum (4 GB for heavy video processing), 20 GB free disk plus space for media. - A DNS `A` record (and `AAAA` if using IPv6) for the hostname, pointing at the server. - Inbound TCP 22, 80, and 443 allowed. Do **not** expose 3000 or 5433. -- Optional: an NFS export for the media archive. +- An NFS export or host directory for original photo/video storage (required for event media). ### 1. Install Docker Engine and Compose @@ -453,9 +455,11 @@ Schedule it in root's crontab (`sudo crontab -e`): The daily job runs instances β†’ slots β†’ complete in that order. Run the script manually once and check its exit status after changing `.env`. -### 9. Media archive on NFS (optional) +### 9. Media storage on NFS or a local path (required for event media) -Without NFS the app uses the `archive-data` Docker volume, which is included in the admin backup. To store originals and photo archives on a NAS: +Original event photos and videos are stored **only** on the configured media storage share β€” it is their primary home, not a backup. Without a named share and a writable mounted path, the uploader and the photo editor are disabled with a warning; the app never falls back to storing media inside the container or on the `archive-data` volume. Photos live in `//events//`, and each video keeps its original, renditions, poster and sidecar together in `//videos///`. + +A bind-mounted host directory works too β€” set `MEDIA_ARCHIVE_DIR` to any local path and name it in Settings. To store media on a NAS: ```bash sudo apt-get install -y nfs-common @@ -480,7 +484,7 @@ docker compose up -d app docker compose exec app sh -c 'test -w /archive && echo "archive writable"' ``` -Adjust NFS export ownership or ID mapping so UID 100 can write. Set the archive subfolder in Settings β†’ Media archive (NFS). +Adjust NFS export ownership or ID mapping so UID 100 can write. Then, in Settings β†’ Media storage, enter the share name (for example `nas.example.org:/export`) and the storage subfolder, and save. Uploads unlock only after that check succeeds. ### 10. Email delivery @@ -530,8 +534,8 @@ git switch main | `password authentication failed` | `POSTGRES_PASSWORD` changed after the volume was initialized. Use the original role password or rotate it with SQL. Changing the env alone does not update Postgres. | | Secure-cookie/login loop | `NEXTAUTH_URL` and `PUBLIC_ORIGIN` must exactly match the HTTPS origin in the browser. | | Wrong links in email | Set `PUBLIC_ORIGIN`; otherwise links derive from the request Host header. | -| Video upload/encode fails | Free disk space, `UPLOAD_DIR` writability, and `docker compose logs app` for FFmpeg errors. | -| Archive unavailable | NFS mount exists on the host, `MEDIA_ARCHIVE_DIR` is set, and UID 100 can write to `/archive`. | +| Video upload/encode fails | Free disk space on the media storage share and `docker compose logs app` for FFmpeg errors. | +| Uploads/editing are disabled | Settings β†’ Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. | | Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. | | Disk filling up | Docker log rotation is capped at 10 MB Γ— 3 per service; remove old backups, exports, and unused media. | @@ -546,7 +550,7 @@ git switch main - [ ] Gmail/Postmark configured and a test email received. - [ ] Cron jobs installed and returning success. - [ ] Backup downloaded, stored off-host, and restore tested once. -- [ ] NFS archive writable (if used). +- [ ] Media storage share configured in Settings β†’ Media storage and writable (required for event photos and videos). - [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary. ## Project structure @@ -605,10 +609,9 @@ The planning documents describe the original long-range product and still mentio ## Known gaps - **SMS is not implemented.** SMS delivery was removed; queued SMS rows are suppressed. Default reminder rules may include an SMS channel, but only email is sent. -- Rich-text editing (TipTap) is not built; lesson and announcement bodies are plain text. -- Exports are CSV plus browser print-to-PDF. There is no server-generated PDF/XLSX export or volunteer swap-request workflow beyond the coverage board. -- Growth goals have a data model and rules but no UI. +- Announcement bodies are still plain text; training lessons use the rich-text editor. +- Run sheets have a server-generated PDF booth sheet; rosters and history export as CSV, and the schedule/run-sheet pages still print from the browser. There is no XLSX export. - Event seats/reminders are separate from the recurring-service slot pipeline. - Reminder templates live in code; timing, channel set, sender identity, and storage paths are runtime settings. -- No built-in cron runner, delivery webhooks/bounce handling, observability integration, or retention job for notification/token rows. +- No built-in cron runner, delivery webhooks/bounce handling, or observability integration. Retention is implemented (`/api/dev/cron/retention`) but still needs a scheduler entry. - `PUBLIC_ORIGIN` must be set in production, otherwise emailed links are derived from the request host. diff --git a/docker-compose.yml b/docker-compose.yml index 584e6c8..d96ec2e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -46,13 +46,18 @@ services: # Dev deployments write messages here; a named volume makes them # inspectable (`docker compose exec app ls /tmp/outbox`). OUTBOX_DIR: /tmp/outbox - # Training attachments. Metadata is in Postgres; bytes live here. + # Training attachments only. Metadata is in Postgres; bytes live here. + # Original event photos and videos require the media storage share below + # and are blocked + # (with an in-app warning) until it is configured and writable. UPLOAD_DIR: /tmp/uploads - # Archive destination inside the container for finished event photos and - # every video's untouched camera original. For NFS, mount the export on the - # Docker host, set MEDIA_ARCHIVE_DIR to that host path, and restart: + # Primary storage inside the container for original event photos and videos. + # For NFS, mount the export on the Docker host, set MEDIA_ARCHIVE_DIR to + # that host path, and restart: # MEDIA_ARCHIVE_DIR=/mnt/nfs/glenloch docker compose up -d - # The default is a local named volume for development. + # Then set the share name and folder in Settings β†’ Media storage. The + # default named volume exists only so the stack boots; it is not accepted + # as media storage once the app checks the configured share. ARCHIVE_DIR: /archive NFS_SHARE: ${NFS_SHARE:-} volumes: diff --git a/docs/PROJECT-STATE.md b/docs/PROJECT-STATE.md index dc06f2f..b70ee58 100644 --- a/docs/PROJECT-STATE.md +++ b/docs/PROJECT-STATE.md @@ -68,7 +68,8 @@ Media Team Hub is a **working, container-deployed church media-team scheduling a | **Repair** | Security, assignment correctness, notification reconciliation, completion job, CI/env/docs | DONE, uncommitted | | **Event photography (MVP)** | Events + photographer/editor assignments, shared folders, streamed RAW/JPEG uploads, downloads, manager event deletion + file cleanup, E2E | DONE, uncommitted | | **Announcements** | Admin/coordinator authoring, publish/unpublish, delete, published-only volunteer feed, E2E | DONE, uncommitted | -| **Not started** | F1 rich text (TipTap) + sanitize, G exports/swaps, full J event seats/reminders/publish pipeline, I launch pass | β€” | +| **Growth & maintenance** | Growth goals + mentor queue UI, retention/storage sweep (+ cron), cached photo thumbnails, per-folder ZIP, server PDF booth sheet, in-app responses for every upcoming assignment | DONE | +| **Not started** | Full J event seats/reminders/publish pipeline, XLSX exports, I launch pass | β€” | --- @@ -517,7 +518,7 @@ GET /api/dev/cron/complete [session | CRON_SECRET] **Session validation:** every `gateOrUser` request re-reads the account row. A JWT whose user was deleted, deactivated or re-seeded (for example after a test reset) now gets a `401 STALE_SESSION` instead of writing rows with a phantom `user_id`; the photo uploader redirects to `/login`. -**Event photography access model:** managers (`schedule.publish`) see every event and assign people; only assigned photographers/editors (plus managers) can open an event, create folders, upload, and download each other's files. Unassigned users get a 404. Files are stored under `UPLOAD_DIR/events//`, never in Postgres; the filename/type is validated by extension (RAW or image), the SHA-256 dedupes re-uploads per folder, and non-previewable files are forced to download. Managers can delete an event; the DB cascade removes folders/photos and the route recursively removes that event's directory, with an audit row. +**Event photography access model:** managers (`schedule.publish`) see every event and assign people; only assigned photographers/editors (plus managers) can open an event, create folders, upload, and download each other's files. Unassigned users get a 404. Files are stored under `/events//` on the configured NFS/local share (never in Postgres and never in container-local storage; uploads and editing are blocked until that share is configured and writable); the filename/type is validated by extension (RAW or image), the SHA-256 dedupes re-uploads per folder, and non-previewable files are forced to download. Managers can delete an event; the DB cascade removes folders/photos and the route recursively removes that event's directory, with an audit row. **Announcements access model:** every signed-in user reads published posts. `content.author` (admin/coordinator) also sees drafts and can create, publish/unpublish or delete. Bodies are plain text and rendered as text, never HTML. @@ -553,7 +554,7 @@ Still missing screens (APIs exist): volunteer profile + prefs, blackout calendar ## 13. Training, uploads, settings -- Lessons: sanitized rich-text HTML body (headings, lists, links, inline images with alignment/size/move controls), published flag, ordering. Volunteers see published; admins author/publish/delete. Two plain-text starter lessons seeded only when the table is empty and normalized to HTML on read. +- Lessons: sanitized rich-text HTML body (headings, lists, links, inline images with alignment/size/caption/move controls), published flag, ordering. Volunteers see published; admins author/publish/delete. Two plain-text starter lessons seeded only when the table is empty and normalized to HTML on read. - Attachments: images/PDF/plain text/Markdown/Word, ≀25 MB, random stored name, metadata in Postgres, bytes under `UPLOAD_DIR`. - Uploads verify **magic bytes** against the declared MIME; SVG is rejected because it can execute as a document. - Serving requires a session; images and PDFs render inline, everything else is a download, with `nosniff`. diff --git a/e2e/admin.spec.ts b/e2e/admin.spec.ts index 969f708..987a8ad 100644 --- a/e2e/admin.spec.ts +++ b/e2e/admin.spec.ts @@ -157,7 +157,11 @@ test.describe("admin", () => { await signInAs(page, "admin@glenloch.local"); await page.goto(`${BASE}/admin`); - await page.getByRole("button", { name: "Send test email" }).click(); + // The email panel also offers a test send; this one belongs to the log. + await page + .locator("#notifications") + .getByRole("button", { name: "Send test email" }) + .click(); await expect(page.getByText(/Test message sent via/)).toBeVisible(); const disable = page.getByRole("button", { name: "Disable" }).first(); diff --git a/e2e/events.spec.ts b/e2e/events.spec.ts index 6478e8a..930c57d 100644 --- a/e2e/events.spec.ts +++ b/e2e/events.spec.ts @@ -88,7 +88,8 @@ test.describe("event photo sharing", () => { const [download] = await Promise.all([ page.waitForEvent("download"), - page.getByRole("link", { name: "Download" }).first().click(), + // Exact: the folder header also offers "Download folder (n)". + page.getByRole("link", { name: "Download", exact: true }).first().click(), ]); const downloadPath = await download.path(); expect(downloadPath).toBeTruthy(); @@ -179,7 +180,7 @@ test.describe("event photo sharing", () => { await page.goto(eventUrl); await page.getByRole("link", { name: /Originals/ }).click(); const photoHref = await page - .getByRole("link", { name: "Download" }) + .getByRole("link", { name: "Download", exact: true }) .first() .getAttribute("href"); expect(photoHref).toBeTruthy(); diff --git a/e2e/growth-and-maintenance.spec.ts b/e2e/growth-and-maintenance.spec.ts new file mode 100644 index 0000000..cf3b44b --- /dev/null +++ b/e2e/growth-and-maintenance.spec.ts @@ -0,0 +1,187 @@ +import { test, expect } from "@playwright/test"; +import { signInAs, resetDb, BASE } from "./dev"; + +/** + * Growth goals, the mentor queue, retention, and the server-rendered booth + * sheet. These surfaces turn existing rules/data into screens, so the point of + * this suite is that a volunteer can ask, a coordinator can resolve, and the + * derived artifacts (sweep report, PDF) are really produced. + */ +test.describe("growth goals and maintenance", () => { + test.beforeAll(async ({ browser }) => { + const context = await browser.newContext(); + const page = await context.newPage(); + await resetDb(page); + await context.close(); + }); + + test("volunteer requests a goal and admin resolves it in the mentor queue", async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 1000 }); + await signInAs(page, "jordan@glenloch.local"); + await page.goto(`${BASE}/profile`); + + await expect(page.getByText("Growth goals", { exact: true })).toBeVisible(); + + const skillSelect = page.getByLabel("Skill", { exact: true }); + const audio = skillSelect + .locator("option") + .filter({ hasText: /^Audio/ }) + .first(); + const audioValue = await audio.getAttribute("value"); + expect(audioValue, "the seed should include an Audio skill").toBeTruthy(); + await skillSelect.selectOption(audioValue!); + await page.getByLabel("Target level").selectOption("expert"); + await page.getByRole("button", { name: "Request goal" }).click(); + + await expect( + page.getByText("Goal requested. A coordinator will pair you with a mentor."), + ).toBeVisible(); + await expect(page.getByText("Waiting for a mentor")).toBeVisible(); + + // The coordinator sees the same goal and can act on it. + await signInAs(page, "admin@glenloch.local"); + await page.goto(`${BASE}/admin`); + await expect(page.getByText("Mentor queue", { exact: true })).toBeVisible(); + await expect( + page.getByText(/Jordan.*Audio/).first(), + ).toBeVisible(); + + await page.getByRole("button", { name: "Decline" }).first().click(); + // The confirmation toast is transient (the page refreshes immediately), so + // assert the durable outcome instead. + await expect(page.getByText("No open growth goals.")).toBeVisible(); + + // Persisted: the volunteer now sees the declined state, not a pending goal. + await signInAs(page, "jordan@glenloch.local"); + await page.goto(`${BASE}/profile`); + await expect(page.getByText("Declined", { exact: true })).toBeVisible(); + }); + + test("admin sees retention counts and can run the sweep", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 1000 }); + await signInAs(page, "admin@glenloch.local"); + await page.goto(`${BASE}/admin`); + + await expect(page.getByText("Retention & storage", { exact: true })).toBeVisible(); + await expect(page.getByText("Upload volume", { exact: true })).toBeVisible(); + + const before = await page.request.get(`${BASE}/api/dev/retention`); + expect(before.ok(), "retention summary should require and accept an admin").toBe(true); + const summary = (await before.json()) as { + summary: { notifications: { total: number }; thresholds: { notificationDays: number } }; + }; + expect(summary.summary.thresholds.notificationDays).toBeGreaterThan(0); + + await page.getByRole("button", { name: "Prune now" }).click(); + await expect( + page.getByText(/Removed \d+ notification rows|Sweep complete/), + ).toBeVisible(); + }); + + test("booth sheet downloads as a real PDF", async ({ page }) => { + await signInAs(page, "admin@glenloch.local"); + + const res = await page.request.get(`${BASE}/api/dev/schedule/instances`); + expect(res.ok()).toBe(true); + const body = (await res.json()) as { instances: { id: string }[] }; + const instance = body.instances[0]; + expect(instance, "the seed should include a service instance").toBeTruthy(); + + const pdf = await page.request.get( + `${BASE}/api/run-sheet/${instance.id}/pdf`, + ); + expect(pdf.status()).toBe(200); + expect(pdf.headers()["content-type"]).toContain("application/pdf"); + expect(pdf.headers()["content-disposition"]).toContain("booth-sheet"); + const bytes = await pdf.body(); + expect(bytes.subarray(0, 5).toString()).toBe("%PDF-"); + expect(bytes.length).toBeGreaterThan(1000); + }); + + test("media uploads and editing stay blocked until media storage is set", async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 1000 }); + await signInAs(page, "admin@glenloch.local"); + + const archiveRoot = process.env.ARCHIVE_DIR ?? "/tmp/glenloch-e2e-archive"; + // A writable path with no named share is not enough: the app must never + // fall back to storing event media inside the container. + const cleared = await page.request.put(`${BASE}/api/dev/storage`, { + data: { nfsShare: "", archivePath: archiveRoot, archiveFolder: "E2E Gate" }, + }); + expect(cleared.ok()).toBe(true); + + const eventResponse = await page.request.post(`${BASE}/api/events`, { + data: { + title: "E2E storage gate", + eventType: "photoshoot", + startsAtLocal: "2026-11-22T10:00", + location: "Main campus", + }, + }); + expect(eventResponse.ok()).toBe(true); + const eventId = ((await eventResponse.json()) as { event: { id: string } }) + .event.id; + const folderResponse = await page.request.post( + `${BASE}/api/events/${eventId}/folders`, + { data: { name: "Originals", kind: "originals" } }, + ); + expect(folderResponse.ok()).toBe(true); + const folderId = ( + (await folderResponse.json()) as { folder: { id: string } } + ).folder.id; + + const photo = await page.request.post( + `${BASE}/api/events/${eventId}/folders/${folderId}/photos?name=blocked.jpg`, + { + headers: { "content-type": "image/jpeg" }, + data: Buffer.from([0xff, 0xd8, 0xff, 0xd9]), + }, + ); + expect(photo.status()).toBe(503); + expect(((await photo.json()) as { error: string }).error).toContain( + "No media storage share", + ); + + const video = await page.request.post( + `${BASE}/api/events/${eventId}/videos?name=blocked.mp4`, + { + headers: { "content-type": "video/mp4" }, + data: Buffer.from("not-a-video"), + }, + ); + expect(video.status()).toBe(409); + expect(((await video.json()) as { error: string }).error).toContain( + "No media storage share", + ); + + await page.goto(`${BASE}/events/${eventId}/folders/${folderId}`); + await expect(page.getByRole("alert").first()).toContainText( + "Photo uploads and editing are disabled", + ); + await page.goto(`${BASE}/events/${eventId}`); + await expect(page.getByRole("alert").first()).toContainText( + "Photo and video uploads are disabled", + ); + + // Leave a working destination behind for the specs that upload media. + const restored = await page.request.put(`${BASE}/api/dev/storage`, { + data: { + nfsShare: "e2e-nas:/export/church", + archivePath: archiveRoot, + archiveFolder: "E2E Archive", + }, + }); + expect(restored.ok()).toBe(true); + + // With a usable share the Media page reports the archive's usage. + await page.goto(`${BASE}/media`); + await expect( + page.getByText("Original media storage", { exact: true }), + ).toBeVisible(); + await expect(page.getByText(/\bused of\b.*\bfree$/)).toBeVisible(); + }); +}); diff --git a/e2e/media.spec.ts b/e2e/media.spec.ts index 775122d..6556ae5 100644 --- a/e2e/media.spec.ts +++ b/e2e/media.spec.ts @@ -15,7 +15,9 @@ import { signInAs, resetDb, BASE } from "./dev"; const execFileAsync = promisify(execFile); const ARCHIVE_ROOT = process.env.ARCHIVE_DIR ?? "/tmp/glenloch-e2e-archive"; const ARCHIVE_FOLDER = "E2E Video Archive"; -const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/tmp/glenloch-e2e-uploads"; +// Originals and every derivative live on the configured share, never in the +// app container's upload volume. +const MEDIA_ROOT = path.join(ARCHIVE_ROOT, ARCHIVE_FOLDER); const SAMPLE = "/tmp/glenloch-e2e-media-sample.mp4"; // A real 32Γ—24 JPEG, so the media page renders a normal browser image. @@ -211,7 +213,7 @@ test.describe("media library and video sharing", () => { expect(trimmed.video.embedCode).toContain(`/embed/${videoId}`); const webPath = path.join( - UPLOAD_DIR, + MEDIA_ROOT, "videos", eventId, videoId, @@ -236,7 +238,7 @@ test.describe("media library and video sharing", () => { // A 720p upload gets a smaller 480p sibling for slow connections. const lowPath = path.join( - UPLOAD_DIR, + MEDIA_ROOT, "videos", eventId, videoId, @@ -322,7 +324,7 @@ test.describe("media library and video sharing", () => { await expect(access(nfsOriginal)).rejects.toThrow(); await expect( - access(path.join(UPLOAD_DIR, "videos", eventId)), + access(path.join(MEDIA_ROOT, "videos", eventId)), ).rejects.toThrow(); const gone = await fetch(`${BASE}/watch/${videoId}`); expect(gone.status).toBe(404); diff --git a/e2e/photo-archive.spec.ts b/e2e/photo-archive.spec.ts index 6f2dacf..928f682 100644 --- a/e2e/photo-archive.spec.ts +++ b/e2e/photo-archive.spec.ts @@ -12,7 +12,8 @@ import { signInAs, resetDb, BASE } from "./dev"; const ARCHIVE_ROOT = process.env.ARCHIVE_DIR ?? "/tmp/glenloch-e2e-archive"; const ARCHIVE_FOLDER = "E2E Archive"; -const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/tmp/glenloch-e2e-uploads"; +// Live photos sit on the configured share too, under `//events`. +const MEDIA_ROOT = path.join(ARCHIVE_ROOT, ARCHIVE_FOLDER); let photoBytes: Buffer; @@ -144,6 +145,6 @@ test("exports a delivery size, then archives and removes the event", async ({ const gone = await page.goto(`${BASE}/events/${event.event.id}`); expect(gone?.status()).toBe(404); await expect( - access(path.join(UPLOAD_DIR, "events", event.event.id)), + access(path.join(MEDIA_ROOT, "events", event.event.id)), ).rejects.toThrow(); }); diff --git a/package.json b/package.json index 1aaf864..c92b82f 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,7 @@ "next": "15.5.29", "next-auth": "5.0.0-beta.32", "nodemailer": "^10.6.0", + "pdf-lib": "^1.17.1", "postgres": "^4.1.1", "react": "19.1.0", "react-dom": "19.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eb68d42..e0b7f57 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -53,6 +53,9 @@ importers: nodemailer: specifier: ^10.6.0 version: 10.6.0 + pdf-lib: + specifier: ^1.17.1 + version: 1.17.1 postgres: specifier: ^4.1.1 version: 4.1.1 @@ -1098,6 +1101,12 @@ packages: '@panva/hkdf@1.2.1': resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==} + '@pdf-lib/standard-fonts@1.0.0': + resolution: {integrity: sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==} + + '@pdf-lib/upng@1.0.1': + resolution: {integrity: sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==} + '@playwright/test@1.65.1': resolution: {integrity: sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==} engines: {node: '>=20'} @@ -3448,6 +3457,9 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} + pako@1.0.11: + resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -3487,6 +3499,9 @@ packages: path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + pdf-lib@1.17.1: + resolution: {integrity: sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -3992,6 +4007,9 @@ packages: resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} engines: {node: '>=6'} + tslib@1.14.1: + resolution: {integrity: sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==} + tslib@2.9.1: resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} @@ -4987,6 +5005,14 @@ snapshots: '@panva/hkdf@1.2.1': {} + '@pdf-lib/standard-fonts@1.0.0': + dependencies: + pako: 1.0.11 + + '@pdf-lib/upng@1.0.1': + dependencies: + pako: 1.0.11 + '@playwright/test@1.65.1': dependencies: playwright: 1.65.1 @@ -7362,6 +7388,8 @@ snapshots: p-try@2.2.0: {} + pako@1.0.11: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -7390,6 +7418,13 @@ snapshots: path-parse@1.0.7: {} + pdf-lib@1.17.1: + dependencies: + '@pdf-lib/standard-fonts': 1.0.0 + '@pdf-lib/upng': 1.0.1 + pako: 1.0.11 + tslib: 1.14.1 + picocolors@1.1.1: {} picomatch@2.3.2: {} @@ -8057,6 +8092,8 @@ snapshots: minimist: 1.2.8 strip-bom: 3.0.0 + tslib@1.14.1: {} + tslib@2.9.1: {} tsx@4.23.15: diff --git a/src/app/(app)/admin/page.tsx b/src/app/(app)/admin/page.tsx index 76f97a6..f48197d 100644 --- a/src/app/(app)/admin/page.tsx +++ b/src/app/(app)/admin/page.tsx @@ -40,6 +40,16 @@ import { type PositionSummary, type RequirementDraft, } from "@/components/app/admin/positions-panel"; +import { listGrowthQueue } from "@/db/growthGoals"; +import { retentionSummary } from "@/db/retention"; +import { + RetentionPanel, + type RetentionSummaryView, +} from "@/components/app/admin/retention-panel"; +import { + MentorQueuePanel, + type QueueGoalView, +} from "@/components/app/growth/mentor-queue-panel"; export const metadata = { title: "Admin" }; @@ -70,17 +80,29 @@ export default async function AdminPage() { const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole; if (!hasPermission(role, "admin.settings")) redirect("/schedule"); - const [users, rules, log, services, matrix, positions, skillRows, emailSettings] = - await Promise.all([ - listUsersForAdmin(), - listRules(), - listNotifications({ limit: 25 }), - listServices({ active: false }), - listSkillsMatrix(), - listPositions({ active: false }), - listSkills({ active: true }), - getEmailSettings(), - ]); + const [ + users, + rules, + log, + services, + matrix, + positions, + skillRows, + emailSettings, + growthQueue, + retention, + ] = await Promise.all([ + listUsersForAdmin(), + listRules(), + listNotifications({ limit: 25 }), + listServices({ active: false }), + listSkillsMatrix(), + listPositions({ active: false }), + listSkills({ active: true }), + getEmailSettings(), + listGrowthQueue(), + retentionSummary(), + ]); const requirementSets = await Promise.all( positions.map((position) => getPositionSkills(position.id)), @@ -107,6 +129,27 @@ export default async function AdminPage() { lastServedOn: row.lastServedOn ?? null, })); + const retentionView: RetentionSummaryView = retention; + + const queueGoals: QueueGoalView[] = growthQueue.map((goal) => ({ + id: goal.id, + userName: goal.userName, + email: goal.email, + skillName: goal.skillName, + targetLevel: goal.targetLevel, + targetDate: goal.targetDate, + status: goal.status, + mentorUserId: goal.mentorUserId, + mentorName: goal.mentorName, + shadowCount: goal.shadowCount, + verifiedLevel: goal.verifiedLevel, + mentorCandidates: goal.mentorCandidates.map((candidate) => ({ + userId: candidate.userId, + displayName: candidate.displayName, + verifiedLevel: candidate.verifiedLevel, + })), + })); + const managedUsers: ManagedUser[] = users.map((user) => ({ id: user.id, email: user.email, @@ -186,6 +229,20 @@ export default async function AdminPage() { + + + Mentor queue + + Volunteers asking to grow. Assign a mentor who is already + mentor-ready for that skill, then log shadows and sign the goal off. + Levels themselves are verified in the matrix above. + + + + + + + Positions & requirements @@ -259,6 +316,20 @@ export default async function AdminPage() { + + + Retention & storage + + What the database and the upload volume are holding, and what the + next sweep would remove. Sent mail and used tokens past their window + are deleted; queued mail never is. + + + + + + + Backup & restore diff --git a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx index a2cf45b..028cbdd 100644 --- a/src/app/(app)/events/[id]/folders/[folderId]/page.tsx +++ b/src/app/(app)/events/[id]/folders/[folderId]/page.tsx @@ -1,6 +1,6 @@ import Link from "next/link"; import { notFound, redirect } from "next/navigation"; -import { ArrowLeft } from "lucide-react"; +import { ArrowLeft, Download } from "lucide-react"; import { auth } from "@/auth/config"; import type { SystemRole } from "@/auth/roles"; import { getFolderDetail } from "@/db/events"; @@ -8,8 +8,10 @@ import { isBrowserRenderablePhoto, isEditableEventPhoto, } from "@/lib/event-photos"; +import { mediaStorage } from "@/lib/media-storage"; import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; import { PhotoGallery, type GalleryPhoto, @@ -48,6 +50,10 @@ export default async function EventFolderPage({ const detail = await getFolderDetail(folderId, user.id, user.systemRole); if (!detail || detail.event.id !== id) notFound(); + // Photos live only on the configured media storage share, so the uploader and + // editor stay disabled (with the reason) until that destination is ready. + const storage = await mediaStorage(); + const photos: GalleryPhoto[] = detail.photos.map((photo) => ({ id: photo.id, filename: photo.filename, @@ -84,9 +90,21 @@ export default async function EventFolderPage({ Β· {sizeLabel(detail.folder.totalBytes)}

- - {KIND_LABELS[detail.folder.kind] ?? detail.folder.kind} - +
+ + {KIND_LABELS[detail.folder.kind] ?? detail.folder.kind} + + {detail.photos.length > 0 && ( + + )} +
); diff --git a/src/app/(app)/events/[id]/page.tsx b/src/app/(app)/events/[id]/page.tsx index 8b1218d..fb38c90 100644 --- a/src/app/(app)/events/[id]/page.tsx +++ b/src/app/(app)/events/[id]/page.tsx @@ -6,10 +6,8 @@ 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 { getStorageSettings } from "@/db/storage-settings"; +import { mediaStorage } from "@/lib/media-storage"; import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz"; import { Badge } from "@/components/ui/badge"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; @@ -71,7 +69,7 @@ export default async function EventDetailPage({ const users = event.canManage ? await listAssignableUsers() : []; const archiveSettings = await getStorageSettings(); - const archiveStatus = await checkArchiveDestination(archiveSettings); + const archiveStatus = await mediaStorage(); const videos = await listEventVideos(event.event.id); const photographers: EventPhotographer[] = event.event.photographers.map( (person) => ({ @@ -109,12 +107,12 @@ export default async function EventDetailPage({ )} - {event.canManage && archiveStatus.ready && ( + {event.canManage && archiveStatus.ok && ( )} {event.canManage && ( @@ -139,13 +137,16 @@ export default async function EventDetailPage({ {event.event.description}

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

- NFS archive is not ready. {archiveStatus.message}{" "} - - Configure archive - {" "} - before deleting finished events. + {!archiveStatus.ok && ( +

+ Photo and video uploads are disabled. {archiveStatus.message}{" "} + + Configure media storage + + .

)} @@ -307,7 +308,7 @@ export default async function EventDetailPage({ diff --git a/src/app/(app)/home/page.tsx b/src/app/(app)/home/page.tsx index e412fa2..6d34638 100644 --- a/src/app/(app)/home/page.tsx +++ b/src/app/(app)/home/page.tsx @@ -203,13 +203,25 @@ export default async function HomePage() { {serve.callTime ? ` Β· call ${time(serve.callTime)}` : ""}

- - {serve.status} - +
+ + {serve.status} + + {pendingCoverage.has(serve.assignmentId) && ( + + Coverage requested + + )} + +
))} diff --git a/src/app/(app)/media/page.tsx b/src/app/(app)/media/page.tsx index 47d1806..9bf3be3 100644 --- a/src/app/(app)/media/page.tsx +++ b/src/app/(app)/media/page.tsx @@ -3,6 +3,7 @@ import { Clock3, FileImage, Film, + HardDrive, Image as ImageIcon, Play, } from "lucide-react"; @@ -12,10 +13,8 @@ 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 { getStorageSettings } from "@/db/storage-settings"; +import { mediaStorage } from "@/lib/media-storage"; import { formatVideoDuration } from "@/lib/event-videos"; import { isBrowserRenderablePhoto } from "@/lib/event-photos"; import { mediaOrigin } from "@/lib/media-url"; @@ -64,7 +63,19 @@ export default async function MediaPage() { listMediaPhotosForEvents(eventIds), getStorageSettings(), ]); - const archiveStatus = await checkArchiveDestination(storage); + const archiveStatus = await mediaStorage(); + const archiveUsedBytes = + archiveStatus.ok && + archiveStatus.totalBytes !== null && + archiveStatus.freeBytes !== null + ? Math.max(0, archiveStatus.totalBytes - archiveStatus.freeBytes) + : null; + const archiveUsedPercent = + archiveUsedBytes !== null && + archiveStatus.ok && + archiveStatus.totalBytes + ? Math.min(100, Math.round((archiveUsedBytes / archiveStatus.totalBytes) * 100)) + : null; const canManage = hasPermission(role, "schedule.publish"); const videoCards = videos.map((video) => videoView(video, origin)); @@ -79,6 +90,44 @@ export default async function MediaPage() {

+ {archiveStatus.ok && ( +
+
+

+

+

+ {archiveStatus.settings.nfsShare} Β·{" "} + {archiveStatus.settings.archiveFolder} +

+
+ {archiveUsedBytes !== null && archiveStatus.totalBytes !== null ? ( + <> +
+
+
+

+ {bytesLabel(archiveUsedBytes)} used of{" "} + {bytesLabel(archiveStatus.totalBytes)} Β·{" "} + {bytesLabel(archiveStatus.freeBytes ?? 0)} free +

+ + ) : ( +

+ Free space could not be read from this filesystem. +

+ )} +
+ )} +
@@ -87,8 +136,8 @@ export default async function MediaPage() { Videos

- Camera originals live on the NFS archive; playback uses a generated - MP4. + Camera originals are stored on the media storage share; playback + uses a generated MP4.

@@ -102,7 +151,7 @@ export default async function MediaPage() { title: event.title, }))} canManage={canManage} - archiveReady={archiveStatus.ready} + archiveReady={archiveStatus.ok} /> {videoCards.length === 0 ? ( diff --git a/src/app/(app)/profile/page.tsx b/src/app/(app)/profile/page.tsx index d5e81b0..89df4fa 100644 --- a/src/app/(app)/profile/page.tsx +++ b/src/app/(app)/profile/page.tsx @@ -8,6 +8,16 @@ import { listSkills } from "@/db/positions"; import { getOrCreateCalendarFeedToken } from "@/db/volunteer"; import { mediaOrigin } from "@/lib/media-url"; import { ProfilePanel } from "@/components/app/profile-panel"; +import { listGoalsForUser } from "@/db/growthGoals"; +import { SKILL_LEVELS } from "@/db/schema"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { GrowthGoalsPanel } from "@/components/app/growth/growth-goals-panel"; export const metadata = { title: "My profile" }; export const dynamic = "force-dynamic"; @@ -17,12 +27,13 @@ export default async function ProfilePage() { const user = session?.user as { id?: string } | undefined; if (!user?.id) redirect("/login"); - const [profile, skillRows, allSkills, token, origin] = await Promise.all([ + const [profile, skillRows, allSkills, token, origin, goals] = await Promise.all([ getProfile(user.id), getUserSkills(user.id), listSkills({ active: true }), getOrCreateCalendarFeedToken(user.id), mediaOrigin(), + listGoalsForUser(user.id), ]); const bySkill = new Map(skillRows.map((row) => [row.skillId, row])); @@ -68,6 +79,37 @@ export default async function ProfilePage() { }))} feedUrl={`${origin}/api/calendar/${token}`} /> + + + + Growth goals + + Ask to grow toward a level on a skill. A coordinator pairs you with + a mentor who is signed off for that skill; the verified level itself + still changes in the skills matrix. + + + + ({ + id: goal.id, + skillName: goal.skillName, + targetLevel: goal.targetLevel, + targetDate: goal.targetDate, + status: goal.status, + mentorName: goal.mentorName, + shadowCount: goal.shadowCount, + verifiedLevel: goal.verifiedLevel, + }))} + skills={allSkills.map((skill) => ({ + id: skill.id, + name: skill.name, + verifiedLevel: bySkill.get(skill.id)?.verifiedLevel ?? "none", + }))} + levels={SKILL_LEVELS} + /> + +
); } diff --git a/src/app/(app)/run-sheet/[instanceId]/page.tsx b/src/app/(app)/run-sheet/[instanceId]/page.tsx index 275d33d..2201eaa 100644 --- a/src/app/(app)/run-sheet/[instanceId]/page.tsx +++ b/src/app/(app)/run-sheet/[instanceId]/page.tsx @@ -1,4 +1,6 @@ import { notFound } from "next/navigation"; +import { Download } from "lucide-react"; +import { Button } from "@/components/ui/button"; import { auth } from "@/auth/config"; import { hasPermission } from "@/auth/permissions"; import type { SystemRole } from "@/auth/roles"; @@ -24,5 +26,20 @@ export default async function RunSheetPage({ const canEdit = hasPermission(user.systemRole, "schedule.publish"); - return ; + return ( +
+
+

+ {data.instance.serviceName} Β· {data.instance.status} +

+ +
+ +
+ ); } diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx index 4441e75..5fe350e 100644 --- a/src/app/(app)/settings/page.tsx +++ b/src/app/(app)/settings/page.tsx @@ -4,10 +4,8 @@ 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 { getStorageSettings } from "@/db/storage-settings"; +import { mediaStorage } from "@/lib/media-storage"; import { CHURCH_TIMEZONE } from "@/lib/tz"; import { Card, @@ -34,9 +32,18 @@ export default async function SettingsPage() { const security = userId ? await getUserSecurity(userId) : null; const isAdmin = hasPermission(role, "admin.settings"); const emailSettings = isAdmin ? await getEmailSettings() : null; + // Keep the form populated even while the destination is unusable, so an + // admin can see and fix what is saved. const storageSettings = isAdmin ? await getStorageSettings() : null; - const storageStatus = storageSettings - ? await checkArchiveDestination(storageSettings) + const media = isAdmin ? await mediaStorage() : null; + const storageStatus = media + ? { + ready: media.ok, + message: media.ok + ? `Event photos and videos are stored in ${media.root}.` + : media.message, + freeBytes: media.ok ? media.freeBytes : null, + } : null; const emailTransport = emailSettings?.smtpConfigured ? "Gmail (SMTP)" @@ -142,7 +149,7 @@ export default async function SettingsPage() { {isAdmin && storageSettings && storageStatus && ( - Media archive (NFS) + Media storage (NFS / local path) Mount an NFS export into this container. Finished event photos are archived here, and every uploaded video keeps its camera original diff --git a/src/app/(app)/training/guides/admin/page.tsx b/src/app/(app)/training/guides/admin/page.tsx index 38819ee..3c01615 100644 --- a/src/app/(app)/training/guides/admin/page.tsx +++ b/src/app/(app)/training/guides/admin/page.tsx @@ -606,7 +606,7 @@ export default function AdminGuidePage() { diff --git a/src/app/api/dev/cron/retention/route.ts b/src/app/api/dev/cron/retention/route.ts new file mode 100644 index 0000000..5d5656b --- /dev/null +++ b/src/app/api/dev/cron/retention/route.ts @@ -0,0 +1,32 @@ +import type { NextRequest } from "next/server"; +import { gateCron } from "@/auth/api"; +import { pruneRetention } from "@/db/retention"; + +const JSON_HEADERS = { "content-type": "application/json" }; + +/** + * GET /api/dev/cron/retention β€” monthly housekeeping (cron `0 4 1 * *`). + * + * Deletes terminal notification rows and consumed tokens past their window and + * sweeps orphan training attachments. Auth: `Authorization: Bearer + * $CRON_SECRET` (or `?secret=`) for a scheduler, otherwise a coordinator + * session. Running it twice is harmless. + */ +export const GET = async (req: NextRequest) => { + const gate = await gateCron(req); + if (gate instanceof Response) return gate; + + try { + const removed = await pruneRetention(); + return new Response(JSON.stringify({ ok: true, removed }), { + status: 200, + headers: JSON_HEADERS, + }); + } catch (error) { + const message = error instanceof Error ? error.message : "retention failed"; + return new Response(JSON.stringify({ error: message }), { + status: 500, + headers: JSON_HEADERS, + }); + } +}; diff --git a/src/app/api/dev/retention/route.ts b/src/app/api/dev/retention/route.ts new file mode 100644 index 0000000..2cc3c71 --- /dev/null +++ b/src/app/api/dev/retention/route.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; +import { gateOrUser } from "@/auth/api"; +import { pruneRetention, retentionSummary } from "@/db/retention"; +import { errorResponse, jsonResponse } from "@/lib/http"; +import { RETENTION_LIMITS } from "@/lib/retention"; + +const sweepSchema = z.object({ + notificationDays: z + .number() + .int() + .min(RETENTION_LIMITS.minDays) + .max(RETENTION_LIMITS.maxDays) + .optional(), + tokenDays: z + .number() + .int() + .min(RETENTION_LIMITS.minDays) + .max(RETENTION_LIMITS.maxDays) + .optional(), +}); + +/** GET /api/dev/retention β€” counts, sizes, and what the next sweep would remove. */ +export async function GET() { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + try { + return jsonResponse({ summary: await retentionSummary() }); + } catch (error) { + console.error("[retention] summary failed", error); + return errorResponse(500, "could not read retention counts"); + } +} + +/** POST /api/dev/retention β€” sweep old mail, tokens and orphan training files. */ +export async function POST(req: Request) { + const gate = await gateOrUser("admin.settings"); + if (gate instanceof Response) return gate; + + const parsed = sweepSchema.safeParse(await req.json().catch(() => ({}))); + if (!parsed.success) return errorResponse(400, "invalid retention window"); + + try { + const result = await pruneRetention(parsed.data); + return jsonResponse({ ok: true, removed: result, summary: await retentionSummary() }); + } catch (error) { + console.error("[retention] sweep failed", error); + return errorResponse(500, "retention sweep failed"); + } +} diff --git a/src/app/api/dev/storage/route.ts b/src/app/api/dev/storage/route.ts index b8a84cd..300192f 100644 --- a/src/app/api/dev/storage/route.ts +++ b/src/app/api/dev/storage/route.ts @@ -42,7 +42,7 @@ function publicSettings(settings: StorageSettings) { }; } -/** GET /api/dev/storage β€” NFS/archive destination and mount readiness. */ +/** GET /api/dev/storage β€” media storage destination and mount readiness. */ export const GET = async () => { const gate = await gateOrUser("admin.settings"); if (gate instanceof Response) return gate; diff --git a/src/app/api/events/[id]/archive/route.ts b/src/app/api/events/[id]/archive/route.ts index ec9408f..080fc75 100644 --- a/src/app/api/events/[id]/archive/route.ts +++ b/src/app/api/events/[id]/archive/route.ts @@ -9,11 +9,8 @@ import { listEventPhotosForArchive, } from "@/db/events"; import { listEventVideos } from "@/db/videos"; -import { eventVideoUploadDir } from "@/lib/event-videos"; -import { - checkArchiveDestination, - getStorageSettings, -} from "@/db/storage-settings"; +import { getStorageSettings } from "@/db/storage-settings"; +import { mediaStorage } from "@/lib/media-storage"; import { archiveEventPhotos, EventArchiveError, @@ -42,14 +39,12 @@ export const POST = async ( return errorResponse(403, "only an event manager may archive this event"); } + // Archiving copies live photos into the dated folder on the same configured + // share; without a named share there is no archive to write to. + const media = await mediaStorage(); + if (!media.ok) return errorResponse(409, media.message); 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 uploadRoot = media.root; const photos = await listEventPhotosForArchive(id); const videos = await listEventVideos(id); @@ -84,10 +79,9 @@ export const POST = async ( } try { - await rm(eventPhotoDir(id), { recursive: true, force: true }); - await rm(eventVideoUploadDir(id), { recursive: true, force: true }); + await rm(eventPhotoDir(uploadRoot, id), { recursive: true, force: true }); } catch (error) { - console.error(`event ${id}: archived but live files remain`, error); + console.error(`event ${id}: archived but live photos remain`, error); } await writeAudit(db, { diff --git a/src/app/api/events/[id]/download/route.ts b/src/app/api/events/[id]/download/route.ts index 24fed56..a4359b5 100644 --- a/src/app/api/events/[id]/download/route.ts +++ b/src/app/api/events/[id]/download/route.ts @@ -11,6 +11,7 @@ import { photoContentDisposition, } from "@/lib/event-photos"; import { errorResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; /** * GET /api/events/:id/download @@ -22,7 +23,7 @@ import { errorResponse } from "@/lib/http"; * Anyone assigned to the event (or a manager) can download it. */ export const GET = async ( - _req: NextRequest, + req: NextRequest, { params }: { params: Promise<{ id: string }> }, ) => { const gate = await gateSession(); @@ -32,9 +33,17 @@ export const GET = async ( const access = await getEventAccess(id, gate.id, gate.systemRole); if (!access) return errorResponse(404, "unknown event"); - const photos = await listEventPhotosForArchive(id); + // `?folderId=` narrows the archive to one folder, so a photographer can pull + // just the shots they need without downloading the whole event. + const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null; + const photos = (await listEventPhotosForArchive(id)).filter( + (photo) => !folderId || photo.folderId === folderId, + ); if (photos.length === 0) { - return errorResponse(404, "this event has no photos"); + return errorResponse( + 404, + folderId ? "this folder has no photos" : "this event has no photos", + ); } // Originals claim their names first, then generated edits join the same @@ -71,9 +80,12 @@ export const GET = async ( filename: entry.filename, })), ); + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + const available: { path: string; name: string }[] = []; for (const entry of entries) { - const filePath = eventPhotoPath(entry.storedName); + const filePath = eventPhotoPath(storage.root, entry.storedName); try { const info = await stat(filePath); if (!info.isFile()) continue; @@ -111,7 +123,11 @@ export const GET = async ( headers: { "content-type": "application/zip", "content-disposition": photoContentDisposition( - eventArchiveFilename(access.event.title), + eventArchiveFilename( + folderId + ? `${access.event.title} - ${photos[0].folderName}` + : access.event.title, + ), false, ), "cache-control": "private, no-store", 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 index c79246e..e9ba55c 100644 --- 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 @@ -11,6 +11,7 @@ import { isEditableEventPhoto, } from "@/lib/event-photos"; import { errorResponse, jsonResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; import { normalizePhotoAdjustments } from "@/lib/photo-adjustments"; import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; @@ -52,6 +53,11 @@ export const POST = async ( return errorResponse(415, "this photo format cannot be edited"); } + // The rendered JPEG is written beside the original on the media share. + // Editing must never fall back to container storage. + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + const body = (await req.json().catch(() => null)) as | { adjustments?: unknown } | null; @@ -60,7 +66,7 @@ export const POST = async ( return errorResponse(400, "invalid photo adjustments"); } - const sourcePath = eventPhotoPath(access.photo.storedName); + const sourcePath = eventPhotoPath(storage.root, access.photo.storedName); try { const source = await stat(sourcePath); if (!source.isFile()) return errorResponse(404, "the file is missing from storage"); @@ -72,7 +78,7 @@ export const POST = async ( access.eventId, access.photo.id, ); - const editedPath = eventPhotoPath(editedStoredName); + const editedPath = eventPhotoPath(storage.root, editedStoredName); let rendered: Awaited>; try { 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 index e1a5b48..39f2bfc 100644 --- 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 @@ -14,6 +14,7 @@ import { import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments"; import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; import { errorResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; /** * GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048 @@ -45,10 +46,16 @@ export const GET = async ( return errorResponse(400, "unknown export size"); } + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + let data: Buffer; try { if (access.photo.editedStoredName) { - const editedPath = eventPhotoPath(access.photo.editedStoredName); + const editedPath = eventPhotoPath( + storage.root, + access.photo.editedStoredName, + ); const info = await stat(editedPath); if (!info.isFile()) throw new Error("missing edit"); data = await sharp(editedPath) @@ -62,7 +69,7 @@ export const GET = async ( .toBuffer(); } else if (access.photo.editJson) { const rendered = await renderPhotoJpeg({ - filePath: eventPhotoPath(access.photo.storedName), + filePath: eventPhotoPath(storage.root, access.photo.storedName), kind: access.photo.kind, adjustments: parseStoredPhotoAdjustments(access.photo.editJson), maxDimension: preset.maxDimension, 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 index 1f09c01..fae98a7 100644 --- 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 @@ -10,6 +10,7 @@ import { previewStoredNameForEventPhoto, } from "@/lib/event-photos"; import { errorResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; @@ -44,7 +45,10 @@ export const GET = async ( return errorResponse(415, "this photo format cannot be previewed in the editor"); } - const sourcePath = eventPhotoPath(access.photo.storedName); + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + + const sourcePath = eventPhotoPath(storage.root, access.photo.storedName); try { const source = await stat(sourcePath); if (!source.isFile()) return errorResponse(404, "the file is missing from storage"); @@ -53,6 +57,7 @@ export const GET = async ( } const previewPath = eventPhotoPath( + storage.root, previewStoredNameForEventPhoto(access.eventId, access.photo.id), ); 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 index 049331e..468bd66 100644 --- a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/route.ts @@ -12,6 +12,7 @@ import { photoContentDisposition, } from "@/lib/event-photos"; import { errorResponse, jsonResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; /** * GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited] @@ -47,7 +48,11 @@ export const GET = async ( return errorResponse(404, "this photo has no saved edit"); } + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + const filePath = eventPhotoPath( + storage.root, wantsEdited ? access.photo.editedStoredName! : access.photo.storedName, @@ -115,11 +120,16 @@ export const DELETE = async ( } await deleteEventPhoto(photoId); - await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined); - if (access.photo.editedStoredName) { - await unlink(eventPhotoPath(access.photo.editedStoredName)).catch( + const storage = await mediaStorage(); + if (storage.ok) { + await unlink(eventPhotoPath(storage.root, access.photo.storedName)).catch( () => undefined, ); + if (access.photo.editedStoredName) { + await unlink( + eventPhotoPath(storage.root, access.photo.editedStoredName), + ).catch(() => undefined); + } } return jsonResponse({ ok: true }); }; diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/thumb/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/thumb/route.ts new file mode 100644 index 0000000..71ab53d --- /dev/null +++ b/src/app/api/events/[id]/folders/[folderId]/photos/[photoId]/thumb/route.ts @@ -0,0 +1,118 @@ +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 sharp from "sharp"; +import { gateSession } from "@/auth/api"; +import { getEventPhotoAccess } from "@/db/events"; +import { + eventPhotoPath, + isBrowserRenderablePhoto, + thumbStoredNameForEventPhoto, +} from "@/lib/event-photos"; +import { errorResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; +import { defaultPhotoAdjustments } from "@/lib/photo-adjustments"; +import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render"; + +/** + * GET /api/events/:id/folders/:folderId/photos/:photoId/thumb + * + * A 640px square-croppable JPEG of the original for the gallery grid. Without + * it a 400-photo event ships hundreds of megabytes of camera originals to a + * phone. Cached on disk (the original never changes) and safe to cache in the + * browser, since the URL is keyed by photo id. + */ +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 storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + + const thumbPath = eventPhotoPath( + storage.root, + thumbStoredNameForEventPhoto(access.eventId, access.photo.id), + ); + + try { + const cached = await stat(thumbPath); + if (cached.isFile()) { + return imageResponse(await readFile(thumbPath)); + } + } catch { + // not cached yet + } + + const sourcePath = eventPhotoPath(storage.root, 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"); + } + + let data: Buffer; + try { + if (access.photo.kind === "raw") { + const rendered = await renderPhotoJpeg({ + filePath: sourcePath, + kind: "raw", + adjustments: defaultPhotoAdjustments(), + maxDimension: 640, + }); + data = rendered.data; + } else if (isBrowserRenderablePhoto(access.photo.filename)) { + data = await sharp(sourcePath, { failOn: "none", limitInputPixels: 500_000_000 }) + .autoOrient() + .resize(640, 640, { fit: "inside", withoutEnlargement: true }) + .jpeg({ quality: 72 }) + .toBuffer(); + } else { + return errorResponse(415, "this photo format has no thumbnail"); + } + } catch (error) { + if (error instanceof PhotoRenderError) { + return errorResponse(415, error.message); + } + console.warn(`event photo ${photoId}: thumbnail failed`, error); + return errorResponse(500, "could not build a thumbnail"); + } + + await mkdir(path.dirname(thumbPath), { recursive: true }); + const tempPath = `${thumbPath}.${randomUUID()}.tmp`; + try { + await writeFile(tempPath, data); + await rename(tempPath, thumbPath); + } catch (error) { + console.warn(`event photo ${photoId}: thumbnail cache write failed`, error); + } + + return imageResponse(data); +}; + +function imageResponse(data: Buffer): Response { + return new Response(new Uint8Array(data), { + status: 200, + headers: { + "content-type": "image/jpeg", + "cache-control": "private, max-age=31536000, immutable", + "x-content-type-options": "nosniff", + }, + }); +} diff --git a/src/app/api/events/[id]/folders/[folderId]/photos/route.ts b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts index 535c381..65d4cc2 100644 --- a/src/app/api/events/[id]/folders/[folderId]/photos/route.ts +++ b/src/app/api/events/[id]/folders/[folderId]/photos/route.ts @@ -21,6 +21,7 @@ import { storedNameForEventPhoto, } from "@/lib/event-photos"; import { errorResponse, jsonResponse } from "@/lib/http"; +import { mediaStorage } from "@/lib/media-storage"; import { uuidv7 } from "@/lib/uuid"; class PhotoTooLarge extends Error {} @@ -69,6 +70,11 @@ export const POST = async ( return errorResponse(403, "you are not assigned to this event"); } + // Photos are only ever written to the configured media storage share, so refuse + // before reading a single byte when that destination is not ready. + const storage = await mediaStorage(); + if (!storage.ok) return errorResponse(503, storage.message); + const suppliedName = req.nextUrl.searchParams.get("name"); if (!suppliedName) return errorResponse(400, "a filename is required"); const filename = sanitizePhotoFilename(suppliedName); @@ -88,7 +94,7 @@ export const POST = async ( const photoId = uuidv7(); const storedName = storedNameForEventPhoto(id, photoId, filename); - const destination = eventPhotoPath(storedName); + const destination = eventPhotoPath(storage.root, storedName); await mkdir(path.dirname(destination), { recursive: true }); const hash = createHash("sha256"); diff --git a/src/app/api/events/[id]/route.ts b/src/app/api/events/[id]/route.ts index 186a7ac..1013bab 100644 --- a/src/app/api/events/[id]/route.ts +++ b/src/app/api/events/[id]/route.ts @@ -6,11 +6,9 @@ import { writeAudit } from "@/db/audit"; import { deleteEvent, getEventAccess } from "@/db/events"; import { listEventVideos } from "@/db/videos"; import { getStorageSettings } from "@/db/storage-settings"; +import { mediaStorage } from "@/lib/media-storage"; import { eventPhotoDir } from "@/lib/event-photos"; -import { - eventVideoArchiveDir, - eventVideoUploadDir, -} from "@/lib/event-videos"; +import { eventVideoArchiveDir } from "@/lib/event-videos"; import { errorResponse, jsonResponse } from "@/lib/http"; /** @@ -34,30 +32,29 @@ export const DELETE = async ( 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); + const media = await mediaStorage(); + if (media.ok) { + try { + await rm(eventPhotoDir(media.root, id), { recursive: true, force: true }); + } catch (error) { + console.error(`event ${id}: database deleted but photos 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. + // Video originals are the largest files; remove the whole event video folder + // on the archive after the cascade has removed the rows, so a deletion cannot + // orphan GBs. Originals and derivatives share one folder per video. try { const storage = await getStorageSettings(); - for (const video of videos) { - await rm( - eventVideoArchiveDir( - storage.archivePath, - video.archiveFolder, - id, - video.id, - ), - { recursive: true, force: true }, - ); + const folders = new Set(videos.map((video) => video.archiveFolder)); + for (const folder of folders) { + await rm(eventVideoArchiveDir(storage.archivePath, folder, id), { + recursive: true, + force: true, + }); } } catch (error) { - console.error(`event ${id}: NFS video originals were not removed`, error); + console.error(`event ${id}: NFS video files were not removed`, error); } await writeAudit(db, { diff --git a/src/app/api/events/[id]/videos/[videoId]/original/route.ts b/src/app/api/events/[id]/videos/[videoId]/original/route.ts index 15f016e..e14c58f 100644 --- a/src/app/api/events/[id]/videos/[videoId]/original/route.ts +++ b/src/app/api/events/[id]/videos/[videoId]/original/route.ts @@ -12,7 +12,7 @@ import { import { errorResponse } from "@/lib/http"; import { parseByteRange } from "@/lib/range"; -/** Download the untouched camera original from the NFS archive. */ +/** Download the untouched camera original from media storage. */ export const GET = async ( req: NextRequest, { params }: { params: Promise<{ id: string; videoId: string }> }, @@ -35,12 +35,12 @@ export const GET = async ( access.video.originalStoredName, ); } catch { - return errorResponse(404, "the NFS archive is not configured"); + return errorResponse(404, "media storage 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"); + return errorResponse(404, "the original video is missing from media storage"); } const range = parseByteRange(req.headers.get("range"), info.size); diff --git a/src/app/api/events/[id]/videos/[videoId]/route.ts b/src/app/api/events/[id]/videos/[videoId]/route.ts index 87f31a0..f1a965b 100644 --- a/src/app/api/events/[id]/videos/[videoId]/route.ts +++ b/src/app/api/events/[id]/videos/[videoId]/route.ts @@ -1,6 +1,5 @@ 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"; @@ -9,11 +8,7 @@ import { getEventVideoAccess, } from "@/db/videos"; import { getStorageSettings } from "@/db/storage-settings"; -import { - eventVideoArchiveDir, - eventVideoUploadPath, - webStoredNameForEventVideo, -} from "@/lib/event-videos"; +import { eventVideoArchiveDir } from "@/lib/event-videos"; import { errorResponse, jsonResponse } from "@/lib/http"; import { videoView } from "@/lib/video-view"; @@ -62,16 +57,7 @@ export const DELETE = async ( 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); - }); - + // One folder on the share holds the original, renditions, poster and sidecar. try { const storage = await getStorageSettings(); await rm( @@ -84,7 +70,7 @@ export const DELETE = async ( { recursive: true, force: true }, ); } catch (error) { - console.error(`video ${videoId}: NFS original was not removed`, error); + console.error(`video ${videoId}: NFS files were not removed`, error); } await writeAudit(db, { diff --git a/src/app/api/events/[id]/videos/chunk/route.ts b/src/app/api/events/[id]/videos/chunk/route.ts index da1fd7a..b41f149 100644 --- a/src/app/api/events/[id]/videos/chunk/route.ts +++ b/src/app/api/events/[id]/videos/chunk/route.ts @@ -6,10 +6,7 @@ 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 { mediaStorage } from "@/lib/media-storage"; import { EVENT_VIDEO_VISIBILITIES, type EventVideoVisibility, @@ -142,14 +139,10 @@ export const POST = async ( (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.`, - ); - } + // Staging chunks also land on the media storage share, never in the container. + const media = await mediaStorage(); + if (!media.ok) return errorResponse(409, media.message); + const storage = media.settings; // 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 diff --git a/src/app/api/events/[id]/videos/route.ts b/src/app/api/events/[id]/videos/route.ts index 6f0b7cb..3c64ca6 100644 --- a/src/app/api/events/[id]/videos/route.ts +++ b/src/app/api/events/[id]/videos/route.ts @@ -8,7 +8,7 @@ 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 { mediaStorage } from "@/lib/media-storage"; import { MAX_EVENT_VIDEO_BYTES, eventVideoArchivePath, @@ -30,7 +30,7 @@ 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 + * Raw request body. The camera original streams straight to media storage 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. @@ -89,14 +89,11 @@ export const POST = async ( } 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.`, - ); - } + // Videos are written only to the configured media storage share. No share, no + // upload: the app must never fall back to container-local storage. + const media = await mediaStorage(); + if (!media.ok) return errorResponse(409, media.message); + const storage = media.settings; const videoId = uuidv7(); const storedName = originalStoredNameForEventVideo(id, videoId, filename); diff --git a/src/app/api/growth-goals/route.ts b/src/app/api/growth-goals/route.ts new file mode 100644 index 0000000..70023c1 --- /dev/null +++ b/src/app/api/growth-goals/route.ts @@ -0,0 +1,107 @@ +import { z } from "zod"; +import { gateSession } from "@/auth/api"; +import { hasPermission } from "@/auth/permissions"; +import { + advanceGrowthGoal, + createGrowthGoal, + GrowthGoalError, + listGoalsForUser, + listGrowthQueue, +} from "@/db/growthGoals"; +import { SKILL_LEVELS } from "@/db/schema"; +import { errorResponse, jsonResponse } from "@/lib/http"; + +const createSchema = z.object({ + skillId: z.string().min(1), + targetLevel: z.enum(SKILL_LEVELS), + targetDate: z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/) + .optional() + .nullable(), +}); + +const actionSchema = z.object({ + id: z.string().min(1), + action: z.enum([ + "assignMentor", + "decline", + "startShadow", + "progressShadow", + "achieve", + "pause", + "resume", + ]), + mentorUserId: z.string().min(1).optional().nullable(), +}); + +/** + * GET /api/growth-goals β€” the signed-in volunteer's goals + * GET /api/growth-goals?scope=queue β€” coordinator/mentor queue (+ candidates) + */ +export async function GET(req: Request) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const scope = new URL(req.url).searchParams.get("scope"); + if (scope === "queue") { + if (!hasPermission(gate.systemRole, "schedule.publish")) { + return errorResponse(403, "coordinators only"); + } + return jsonResponse({ goals: await listGrowthQueue() }); + } + return jsonResponse({ goals: await listGoalsForUser(gate.id) }); +} + +/** POST /api/growth-goals β€” ask to grow toward a level for one skill. */ +export async function POST(req: Request) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const parsed = createSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) return errorResponse(400, "invalid growth goal"); + + try { + const goal = await createGrowthGoal({ + userId: gate.id, + skillId: parsed.data.skillId, + targetLevel: parsed.data.targetLevel, + targetDate: parsed.data.targetDate ?? null, + }); + return jsonResponse({ ok: true, ...goal }, 201); + } catch (error) { + if (error instanceof GrowthGoalError) { + return errorResponse(error.status, error.message); + } + console.error("[growth-goals] create failed", error); + return errorResponse(500, "failed to create the goal"); + } +} + +/** PATCH /api/growth-goals β€” advance a goal (coordinator). */ +export async function PATCH(req: Request) { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + if (!hasPermission(gate.systemRole, "schedule.publish")) { + return errorResponse(403, "coordinators only"); + } + + const parsed = actionSchema.safeParse(await req.json().catch(() => null)); + if (!parsed.success) return errorResponse(400, "invalid action"); + + try { + const result = await advanceGrowthGoal({ + goalId: parsed.data.id, + action: parsed.data.action, + actorId: gate.id, + mentorUserId: parsed.data.mentorUserId ?? null, + }); + return jsonResponse({ ok: true, ...result }); + } catch (error) { + if (error instanceof GrowthGoalError) { + return errorResponse(error.status, error.message); + } + console.error("[growth-goals] action failed", error); + return errorResponse(500, "failed to update the goal"); + } +} diff --git a/src/app/api/media/[id]/poster/route.ts b/src/app/api/media/[id]/poster/route.ts index f282ca5..a0fb286 100644 --- a/src/app/api/media/[id]/poster/route.ts +++ b/src/app/api/media/[id]/poster/route.ts @@ -3,8 +3,9 @@ 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, getPublicEventVideo } from "@/db/videos"; -import { eventVideoUploadPath } from "@/lib/event-videos"; +import { eventVideoArchivePath } from "@/lib/event-videos"; import { errorResponse } from "@/lib/http"; export const GET = async ( @@ -33,7 +34,12 @@ export const GET = async ( } let filePath: string; try { - filePath = eventVideoUploadPath(video.posterStoredName); + const storage = await getStorageSettings(); + filePath = eventVideoArchivePath( + storage.archivePath, + video.archiveFolder, + video.posterStoredName, + ); } catch { return errorResponse(404, "unknown poster"); } diff --git a/src/app/api/media/[id]/stream/route.ts b/src/app/api/media/[id]/stream/route.ts index b33ef75..068ca75 100644 --- a/src/app/api/media/[id]/stream/route.ts +++ b/src/app/api/media/[id]/stream/route.ts @@ -3,9 +3,10 @@ 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, getPublicEventVideo } from "@/db/videos"; import { - eventVideoUploadPath, + eventVideoArchivePath, sanitizeVideoFilename, videoContentDisposition, webRenditionStoredNameForEventVideo, @@ -49,12 +50,19 @@ export const GET = async ( let filePath: string; let info: Awaited> | null = null; try { - filePath = eventVideoUploadPath(video.webStoredName); + const storage = await getStorageSettings(); + filePath = eventVideoArchivePath( + storage.archivePath, + video.archiveFolder, + 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( + const renditionPath = eventVideoArchivePath( + storage.archivePath, + video.archiveFolder, webRenditionStoredNameForEventVideo( video.eventId, video.id, diff --git a/src/app/api/run-sheet/[instanceId]/pdf/route.ts b/src/app/api/run-sheet/[instanceId]/pdf/route.ts new file mode 100644 index 0000000..96ffcf4 --- /dev/null +++ b/src/app/api/run-sheet/[instanceId]/pdf/route.ts @@ -0,0 +1,41 @@ +import type { NextRequest } from "next/server"; +import { gateSession } from "@/auth/api"; +import { getRunSheet } from "@/db/runSheet"; +import { boothSheetFilename, buildBoothSheetPdf } from "@/lib/booth-sheet-pdf"; +import { errorResponse } from "@/lib/http"; + +/** + * GET /api/run-sheet/:instanceId/pdf + * + * The printable booth sheet as a real PDF. Any signed-in team member can pull + * it (the run sheet itself is team-visible); it is generated from the current + * database state each time, so it can never show a stale team. + */ +export const GET = async ( + _req: NextRequest, + { params }: { params: Promise<{ instanceId: string }> }, +) => { + const gate = await gateSession(); + if (gate instanceof Response) return gate; + + const { instanceId } = await params; + const sheet = await getRunSheet(instanceId); + if (!sheet) return errorResponse(404, "unknown run sheet"); + + try { + const pdf = await buildBoothSheetPdf(sheet); + const filename = boothSheetFilename(sheet).replace(/[^A-Za-z0-9._-]/g, "_"); + return new Response(new Uint8Array(pdf), { + status: 200, + headers: { + "content-type": "application/pdf", + "content-disposition": `attachment; filename="${filename}"`, + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }, + }); + } catch (error) { + console.error("[run-sheet-pdf] build failed", error); + return errorResponse(500, "could not build the booth sheet"); + } +}; diff --git a/src/components/app/admin/retention-panel.tsx b/src/components/app/admin/retention-panel.tsx new file mode 100644 index 0000000..1c24793 --- /dev/null +++ b/src/components/app/admin/retention-panel.tsx @@ -0,0 +1,199 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { Database, HardDrive } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { formatBytes } from "@/lib/retention"; + +export interface RetentionSummaryView { + notifications: { total: number; live: number; terminal: number; prunable: number }; + tokens: { used: number; magic: number; prunable: number }; + auditLog: number; + training: { files: number; bytes: number }; + eventPhotos: { files: number; bytes: number }; + eventVideos: { files: number; bytes: number }; + orphanFiles: { files: number; bytes: number }; + thresholds: { notificationDays: number; tokenDays: number }; +} + +function Row({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
{value}
+
+ ); +} + +/** + * Retention + storage report. The numbers come from the database (rows) and + * the upload volume (orphan files). Running the sweep is explicit β€” nothing is + * deleted on a page view. + */ +export function RetentionPanel({ summary }: { summary: RetentionSummaryView }) { + const router = useRouter(); + const [notificationDays, setNotificationDays] = useState( + summary.thresholds.notificationDays, + ); + const [tokenDays, setTokenDays] = useState(summary.thresholds.tokenDays); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + const [error, setError] = useState(null); + + async function sweep() { + setBusy(true); + setMessage(null); + setError(null); + try { + const res = await fetch("/api/dev/retention", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ notificationDays, tokenDays }), + }); + const data = (await res.json().catch(() => ({}))) as { + error?: string; + removed?: { + notifications: number; + tokens: number; + magicTokens: number; + orphanFiles: number; + orphanBytes: number; + }; + }; + if (!res.ok) { + setError(data.error ?? "The sweep failed."); + return; + } + const removed = data.removed; + setMessage( + removed + ? `Removed ${removed.notifications} notification rows, ${removed.tokens + removed.magicTokens} tokens, and ${removed.orphanFiles} orphan files (${formatBytes(removed.orphanBytes)}).` + : "Sweep complete.", + ); + router.refresh(); + } catch { + setError("Network error."); + } finally { + setBusy(false); + } + } + + const totalBytes = + summary.training.bytes + + summary.eventPhotos.bytes + + summary.eventVideos.bytes; + + return ( +
+
+
+

+

+
+ + + + + +
+
+ +
+

+

+
+ + + + + +
+
+
+ +
+
+ + setNotificationDays(Number(event.target.value))} + className="h-9 w-28" + /> +
+
+ + setTokenDays(Number(event.target.value))} + className="h-9 w-28" + /> +
+ +
+ +

+ Only finished mail and already-used tokens are removed; queued mail is + never touched. Orphan files are uploads whose record is gone and that are + more than a day old. Event photos and videos are owned by their event and + are reported, not swept. The same sweep runs monthly from + /api/dev/cron/retention. +

+ + {message && ( +

+ {message} +

+ )} + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/src/components/app/events/archive-event-button.tsx b/src/components/app/events/archive-event-button.tsx index 87d9fcf..cf30429 100644 --- a/src/components/app/events/archive-event-button.tsx +++ b/src/components/app/events/archive-event-button.tsx @@ -6,9 +6,10 @@ import { Archive } from "lucide-react"; import { Button } from "@/components/ui/button"; /** - * Manager-only "copy then delete" action. The server writes a complete archive - * first, including a manifest, and only then removes the event. A failure leaves - * the live event untouched. + * Manager-only "file then delete" action for a finished event. Originals and + * edits already live on the media storage share; this copies them into a dated + * delivery folder with a manifest, then removes the event rows and the working + * copies. A failure leaves the live event untouched. */ export function ArchiveEventButton({ eventId, @@ -27,7 +28,7 @@ export function ArchiveEventButton({ async function archive() { const confirmed = window.confirm( - `Archive ${photoCount} photo${photoCount === 1 ? "" : "s"} from "${title}" to ${archivePath}, then delete the event?\n\nThe originals and saved edits are copied first. The event is removed only if the archive succeeds.`, + `File ${photoCount} photo${photoCount === 1 ? "" : "s"} from "${title}" into a dated folder under ${archivePath}, then delete the event?\n\nOriginals and saved edits are copied first; they stay on media storage either way. The event is removed only if the copy succeeds.`, ); if (!confirmed) return; @@ -67,7 +68,7 @@ export function ArchiveEventButton({ onClick={archive} >