872d1cb29e
The old README still described the planning phase and a Cloudflare/Postmark/Twilio stack. Replace it with current setup, features, configuration, cron, backup, roles, testing, and known gaps so the repository is usable as-is.
320 lines
18 KiB
Markdown
320 lines
18 KiB
Markdown
# Media Team Hub
|
|
|
|
Scheduling, availability, training, and media operations for a church media team.
|
|
|
|
The app runs the full weekly loop: recurring services are generated, seats are assigned (manually or by ranked auto-fill), conflicts and blackout dates are checked, the week is published, and volunteers receive email with one-click confirm/decline links. It also handles one-off event photography, a photo/video library, skill verification and mentoring, training material, announcements, coverage requests, calendar feeds, and backups.
|
|
|
|
Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It deploys as a portable Node container behind your own reverse proxy.
|
|
|
|
> **Notification scope:** email is the only delivery channel currently implemented. SMS was deliberately removed; queued SMS rows are suppressed by the dispatcher. See [Known gaps](#known-gaps).
|
|
|
|
## Contents
|
|
|
|
- [Features](#features)
|
|
- [Stack](#stack)
|
|
- [Quick start (Docker)](#quick-start-docker)
|
|
- [Local development](#local-development)
|
|
- [Configuration](#configuration)
|
|
- [Email delivery](#email-delivery)
|
|
- [Scheduled jobs](#scheduled-jobs)
|
|
- [Backup and restore](#backup-and-restore)
|
|
- [Roles and permissions](#roles-and-permissions)
|
|
- [Testing](#testing)
|
|
- [Deployment notes](#deployment-notes)
|
|
- [Project structure](#project-structure)
|
|
- [Documentation](#documentation)
|
|
- [Known gaps](#known-gaps)
|
|
|
|
## Features
|
|
|
|
### Scheduling
|
|
|
|
- Recurring service templates (RFC 5545 subset, local start time, duration, call-time offsets) materialized into dated instances and per-role seats.
|
|
- Week, month, and year calendar lenses, plus a printable run sheet/booth sheet.
|
|
- One active assignment per seat, enforced by the database; one assignment per person per service, enforced by the conflict engine.
|
|
- Manual assignments from a ranked candidate list (availability → roster → one-per-service → core competency → readiness).
|
|
- Hard-conflict blocking (blackout, double-booking, missing core skill, shadow pairing, etc.) with soft conflicts returned as warnings.
|
|
- Deterministic auto-fill under a monthly service cap, with preview and apply.
|
|
- Draft vs. published weeks: publishing validates coverage, writes an audit row, and queues notifications atomically. Unpublishing is refused while anyone is confirmed.
|
|
- Post-service completion job records `last_served_on` / `last_served_at`.
|
|
|
|
### Availability and coverage
|
|
|
|
- Volunteers publish one-off or recurring blackout ranges; coordinators see the whole team's availability.
|
|
- Warnings when a new blackout overlaps an existing assignment.
|
|
- Coverage board for swap/release requests, with ranked replacements.
|
|
- Public, no-account coverage request form at `/request-coverage`.
|
|
|
|
### Notifications
|
|
|
|
- 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.
|
|
- 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.
|
|
|
|
### People, skills, and training
|
|
|
|
- Magic-link sign-in, optional account password, approval queue, deactivation, and admin account management.
|
|
- Skill taxonomy composed from category / technology / function, with per-position requirements (core flag, weight, required level).
|
|
- 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.
|
|
- Training lessons with attachments (images, PDF, text, Markdown, Word; 5 MB max), draft/publish, and separate admin/volunteer guides.
|
|
|
|
### 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.
|
|
- 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/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint.
|
|
- Announcements feed with draft/publish/delete for coordinators and admins.
|
|
|
|
### 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.
|
|
- Runtime settings stored in Postgres, including encrypted Gmail credentials, so mail identity and storage paths change without a deploy.
|
|
|
|
## Stack
|
|
|
|
| Layer | Choice |
|
|
| --- | --- |
|
|
| Framework | Next.js 15 App Router, React 19, TypeScript (strict) |
|
|
| Styling | Tailwind CSS 4, local shadcn-style primitives, lucide-react |
|
|
| Database | PostgreSQL 16 via Drizzle ORM (`postgres` driver) |
|
|
| Auth | Auth.js / NextAuth v5, JWT sessions, magic links, optional passwords |
|
|
| Email | Nodemailer: Gmail SMTP (admin-configured) → Postmark → console/file transport |
|
|
| Media | FFmpeg, sharp, ImageMagick + LibRaw |
|
|
| Testing | Vitest (unit), Playwright (browser) |
|
|
| Runtime | Multi-stage Docker image, Node 22, non-root user |
|
|
|
|
Business rules live in pure modules under `src/domain/` with no database imports. `src/db/` resolves facts and applies those rules in transactions; route handlers and server components stay thin.
|
|
|
|
## Quick start (Docker)
|
|
|
|
Requirements: Docker with Compose, and a generated auth secret.
|
|
|
|
```bash
|
|
cp .env.example .env
|
|
# Set NEXTAUTH_SECRET in .env:
|
|
# openssl rand -base64 32
|
|
|
|
docker compose up -d db
|
|
docker compose --profile tools run --rm migrate # migrations + seed
|
|
docker compose up -d --build app
|
|
```
|
|
|
|
Open <http://localhost:3000>. The app publishes on host port `3000`; Postgres is exposed on `5433` to avoid clashing with a local `5432`.
|
|
|
|
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log:
|
|
|
|
```bash
|
|
docker compose logs -f app
|
|
```
|
|
|
|
Sign in with the seeded admin, `admin@glenloch.local`. Other seeded accounts: `coordinator@glenloch.local`, volunteers `jordan@`, `avery@`, `sam@`, and a pending trainee `riley@` (all `@glenloch.local`). Seeded data includes two Sunday services, the next two weeks of seats, skills, assignments, reminder rules, and two training lessons.
|
|
|
|
Migrations are **not** run automatically by `docker compose up`. Re-run the `migrate` command after pulling schema changes. The seed is idempotent.
|
|
|
|
## Local development
|
|
|
|
```bash
|
|
pnpm install
|
|
cp .env.example .env
|
|
docker compose up -d db
|
|
|
|
pnpm db:migrate
|
|
pnpm db:seed
|
|
pnpm dev
|
|
```
|
|
|
|
`pnpm dev` uses Turbopack. If a production `.next/` directory is present, remove it first (`rm -rf .next`); the two modes can conflict.
|
|
|
|
### Scripts
|
|
|
|
| Command | Purpose |
|
|
| --- | --- |
|
|
| `pnpm dev` | Development server (Turbopack) |
|
|
| `pnpm build` / `pnpm start` | Production build / start |
|
|
| `pnpm typecheck` | `tsc --noEmit` |
|
|
| `pnpm lint` | ESLint |
|
|
| `pnpm test` / `pnpm test:watch` | Vitest unit tests |
|
|
| `pnpm test:e2e` | Playwright (builds and starts its own server) |
|
|
| `pnpm db:generate` | Generate a Drizzle migration from schema changes |
|
|
| `pnpm db:migrate` | Apply migrations |
|
|
| `pnpm db:seed` | Idempotent seed |
|
|
| `pnpm db:prune` | Remove orphaned user-owned rows |
|
|
|
|
## Configuration
|
|
|
|
Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.env.example` is not).
|
|
|
|
| Variable | Purpose |
|
|
| --- | --- |
|
|
| `DATABASE_URL` | Postgres connection string. Compose uses `db:5432`; local dev uses `localhost:5433`. |
|
|
| `NEXTAUTH_SECRET` | Auth.js signing secret **and** the at-rest encryption key for the stored Gmail app password. Rotating it invalidates sessions and makes the stored SMTP password undecryptable. |
|
|
| `NEXTAUTH_URL` | Base URL for Auth.js. Keep it HTTP locally; an HTTPS value marks the session cookie `Secure`, which breaks plain-HTTP LAN access. |
|
|
| `PUBLIC_ORIGIN` | Canonical origin used in emailed links. **Set this in any off-LAN deployment**; if empty, links use the request origin/Host header. |
|
|
| `APP_ORIGIN` | Fallback application origin. |
|
|
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
|
|
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
|
|
| `MAGIC_LINK_DEV_TRANSPORT` | Shows/prints the sign-in link instead of emailing it. Defaults on outside production; compose sets `true` for first login. |
|
|
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
|
|
| `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 mount path inside the container and the reported NFS share. |
|
|
| `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.
|
|
|
|
## Email delivery
|
|
|
|
Delivery is resolved at send time, in order:
|
|
|
|
1. **Gmail SMTP** configured in Admin → Email delivery (address + app password). The password is encrypted with AES-256-GCM using `NEXTAUTH_SECRET`.
|
|
2. **Postmark**, when `POSTMARK_SERVER_TOKEN` is set.
|
|
3. **Console transport**, which writes JSON messages under `OUTBOX_DIR` (development fallback).
|
|
|
|
The sender address and admin notification inbox are runtime settings. Admin → Notifications shows the outbox, allows retrying failed/suppressed rows, and sends a test message.
|
|
|
|
## Scheduled jobs
|
|
|
|
There is no in-app scheduler. Call these routes on a timer with `Authorization: Bearer $CRON_SECRET` (an authorized admin session also works):
|
|
|
|
| Route | Suggested cadence | Purpose |
|
|
| --- | --- | --- |
|
|
| `GET /api/dev/cron/instances` | Daily | Materialize upcoming service instances |
|
|
| `GET /api/dev/cron/slots` | Daily, after instances | Materialize seats (skips published weeks) |
|
|
| `GET /api/dev/cron/notifications` | Every 5 minutes | Claim and dispatch due outbox rows |
|
|
| `GET /api/dev/cron/complete` | Daily, after the last service | Complete past assignments and update serving history |
|
|
|
|
Set `CRON_SECRET` before enabling the timer; without it the routes only accept an authenticated session.
|
|
|
|
## Backup and restore
|
|
|
|
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;
|
|
- `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.
|
|
|
|
To restore: bring up a fresh stack, run migrations and seed, sign in as an admin, open Admin → Backup & restore, upload the ZIP, type `RESTORE`, and confirm. The database load is one transaction, so an incompatible dump rolls back. Restore replaces the current database and the file areas named in the manifest.
|
|
|
|
## Roles and permissions
|
|
|
|
| Permission | Admin | Coordinator | Volunteer | Trainee |
|
|
| --- | :---: | :---: | :---: | :---: |
|
|
| `admin.settings`, `users.manage`, `training.author`, `design.theme` | ✅ | — | — | — |
|
|
| `content.author`, `schedule.publish` | ✅ | ✅ | — | — |
|
|
| `schedule.view`, `volunteer.serve`, `volunteer.blackout`, `roster.view` | ✅ | ✅ | ✅ | partial (no roster) |
|
|
|
|
- **Admin** — everything, including system settings, people administration, and design/theme.
|
|
- **Coordinator** — scheduling, coverage, events, people operations, training, and announcements; no system/theme settings.
|
|
- **Volunteer** — set availability, view the schedule/roster, confirm or decline assignments, edit their profile.
|
|
- **Trainee** — shadow seat access without full roster visibility.
|
|
|
|
Route handlers enforce permissions server-side (`src/auth/api.ts`); the UI only hides controls. `/admin` redirects non-admins.
|
|
|
|
## Testing
|
|
|
|
```bash
|
|
pnpm typecheck
|
|
pnpm lint
|
|
pnpm test
|
|
pnpm test:e2e
|
|
pnpm build
|
|
```
|
|
|
|
Playwright builds and starts the app on port 3000 and resets the database between suites. **Never point it at a database you care about.** Use a disposable database:
|
|
|
|
```bash
|
|
TEST_DATABASE_URL=postgres://media:media@localhost:5433/media_e2e pnpm test:e2e
|
|
```
|
|
|
|
If a server is already listening on port 3000, Playwright reuses it; stop the dev server first so the test build and database are the ones under test.
|
|
|
|
The unit suite covers pure domain rules, auth/permissions/tokens, uploads, rate limiting, event access, photo/video helpers, and backup/export logic. `.github/workflows/ci.yml` defines the full check sequence: migration drift, typecheck, lint, unit tests, migrations, E2E, and build.
|
|
|
|
## Deployment notes
|
|
|
|
- Run the app behind a TLS-terminating reverse proxy. Application responses already set `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, and `X-Frame-Options` on API routes; `/embed/*` is intentionally frameable.
|
|
- Set `PUBLIC_ORIGIN` to the public HTTPS origin, `AUTO_ACTIVATE_NEW_USERS=false`, `ALLOW_DEV_RESET=false`, and `MAGIC_LINK_DEV_TRANSPORT=false` once real mail is configured.
|
|
- Schedule the four cron routes externally (host cron/systemd timer/scheduler container) with `CRON_SECRET`.
|
|
- Mount the NFS export on the Docker host and start Compose with `MEDIA_ARCHIVE_DIR=/path/to/export`; configure the archive subfolder in Settings → Media archive (NFS).
|
|
- Persist the Postgres, outbox, uploads, and archive volumes. Keep `NEXTAUTH_SECRET` stable and backed up.
|
|
- The `/api/dev/*` prefix is historical: these are the production admin/cron APIs. The guards, not the URL, are the security boundary.
|
|
|
|
## Project structure
|
|
|
|
```text
|
|
.
|
|
├── .github/workflows/ci.yml Typecheck, lint, tests, migrations, E2E, build
|
|
├── docs/ Product spec, architecture, build plan, current state
|
|
├── drizzle/ Migrations, snapshots, journal
|
|
├── e2e/ Playwright specs and shared helpers
|
|
├── public/ Static assets
|
|
├── src/
|
|
│ ├── app/ Pages, layouts, API route handlers
|
|
│ ├── auth/ Auth.js config, magic links, permissions, gates
|
|
│ ├── components/ App UI and local UI primitives
|
|
│ ├── db/ Schema, queries, transactions, seed/prune/complete jobs
|
|
│ ├── domain/ Pure, unit-tested business rules
|
|
│ └── lib/ Timezone, tokens, email, storage, media, backup helpers
|
|
├── Dockerfile Multi-stage build; tools stage for migrations
|
|
├── docker-compose.yml App + Postgres + one-shot migrate/seed
|
|
├── drizzle.config.ts
|
|
├── next.config.ts
|
|
├── playwright.config.ts
|
|
└── package.json
|
|
```
|
|
|
|
### Main routes
|
|
|
|
| Route | Purpose |
|
|
| --- | --- |
|
|
| `/home` | Personal next-serve, upcoming assignments, coverage status |
|
|
| `/dashboard` | Coordinator coverage snapshot and queues |
|
|
| `/schedule` | Week/month/year schedule; inline editing for coordinators |
|
|
| `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet |
|
|
| `/availability` | Personal and team blackout management |
|
|
| `/coverage` | Swap/release requests and public intake |
|
|
| `/events`, `/events/[id]` | One-off events, briefs, photographers, folders |
|
|
| `/media`, `/media/[id]` | Photo/video library and public video page |
|
|
| `/training`, `/training/guides/*` | Lessons, attachments, role guides |
|
|
| `/announcements` | Team feed |
|
|
| `/roster` | Active team directory |
|
|
| `/profile`, `/settings` | Personal details, skills, calendar feed, account security |
|
|
| `/admin` | Admin console |
|
|
| `/login`, `/respond`, `/request-coverage`, `/watch/[id]`, `/embed/[id]` | Public or token-based entry points |
|
|
|
|
## Documentation
|
|
|
|
- [docs/PROJECT-STATE.md](docs/PROJECT-STATE.md) — detailed code map, data model, route inventory, risks.
|
|
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — architecture and design rationale.
|
|
- [docs/BUILD-SPEC.md](docs/BUILD-SPEC.md) — screen-by-screen product specification.
|
|
- [docs/BUILD-PLAN.md](docs/BUILD-PLAN.md) — phased build plan.
|
|
- [docs/FEATURE-SUMMARY.md](docs/FEATURE-SUMMARY.md) — plain-language feature list.
|
|
|
|
The planning documents describe the original long-range product and still mention deferred phases. This README reflects what is actually implemented today.
|
|
|
|
## 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.
|
|
- 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.
|
|
- `PUBLIC_ORIGIN` must be set in production, otherwise emailed links are derived from the request host.
|