Files
glenloch-media/README.md
T
bhursey e8759cdee8
CI / build (push) Has been cancelled
docs: rebuild the migrate image before running it
docker compose run reuses the previously built tools image, so an upgrade could execute stale seed code against a newer schema. Include the explicit build step in quick start, production deployment, and update commands.
2026-11-20 05:39:46 +00:00

615 lines
30 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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)
- [Production deployment on Ubuntu](#production-deployment-on-ubuntu)
- [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 build migrate
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 published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it).
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 for host-side CLI commands. Compose builds the app/migrate URL from `POSTGRES_*` and uses `db:5432`; local dev uses `localhost:5433`. |
| `POSTGRES_USER`, `POSTGRES_PASSWORD`, `POSTGRES_DB` | Compose database credentials. Applied only when the `pgdata` volume is first initialized; use a URL-safe password (hex is simplest). |
| `POSTGRES_PORT`, `POSTGRES_BIND` | Host publishing for Postgres. Defaults: `5433` on `127.0.0.1`. |
| `APP_PORT`, `APP_BIND` | Host publishing for the app. Default: `3000` on all interfaces; set `APP_BIND=127.0.0.1` behind a reverse proxy. |
| `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_FOLDER` | Archive mount path inside the container, the reported NFS share, and the default archive subfolder. |
| `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.
## Production deployment on Ubuntu
This is the full path for a fresh Ubuntu 22.04/24.04 host using Docker. The result is the app on `127.0.0.1:3000`, Postgres on `127.0.0.1:5433`, Caddy terminating TLS on ports 80/443, and cron driving the background jobs.
**Host requirements**
- Ubuntu 22.04 LTS or 24.04 LTS with sudo access.
- 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.
### 1. Install Docker Engine and Compose
```bash
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
| sudo gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
| sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
sudo usermod -aG docker "$USER"
newgrp docker
docker compose version
```
### 2. Put the code on the server
```bash
sudo mkdir -p /opt/glenloch-media
sudo chown "$USER":"$USER" /opt/glenloch-media
git clone https://git.maple-street.net/bhursey/glenloch-media.git /opt/glenloch-media
cd /opt/glenloch-media
```
For a private repository, configure a read-only deploy key or access token in your Git host instead of embedding a password in the clone URL. Keep the checkout on `main`.
### 3. Create the environment file
```bash
cp .env.example .env
chmod 600 .env
openssl rand -base64 32 # NEXTAUTH_SECRET
openssl rand -hex 32 # CRON_SECRET
openssl rand -hex 24 # POSTGRES_PASSWORD (hex avoids URL encoding)
```
Edit `.env`. Minimum production values:
```dotenv
NEXTAUTH_URL=https://media.example.org
NEXTAUTH_SECRET=<base64 value>
PUBLIC_ORIGIN=https://media.example.org
APP_ORIGIN=https://media.example.org
APP_BIND=127.0.0.1
POSTGRES_BIND=127.0.0.1
POSTGRES_USER=media
POSTGRES_PASSWORD=<hex value>
POSTGRES_DB=media
DATABASE_URL=postgres://media:<hex value>@localhost:5433/media
CHURCH_TIMEZONE=America/New_York
AUTO_ACTIVATE_NEW_USERS=false
ALLOW_DEV_RESET=false
# Bootstrap only. Set to false before exposing the app (step 5).
MAGIC_LINK_DEV_TRANSPORT=true
CRON_SECRET=<hex value>
POSTMARK_FROM=media@example.org
# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead
```
Notes:
- `NEXTAUTH_URL` and `PUBLIC_ORIGIN` must be the public HTTPS origin. An HTTPS `NEXTAUTH_URL` makes the session cookie `Secure`, so do not sign in over plain HTTP once it is set.
- `POSTGRES_*` is applied when the `pgdata` volume is first initialized. Changing it later does **not** change the existing role; rotate with SQL (`ALTER ROLE`) or recreate the volume.
- `DATABASE_URL` is for host-side CLI commands. Compose builds the app's internal URL from `POSTGRES_*`.
- Back up `NEXTAUTH_SECRET` with the database: it encrypts the stored Gmail app password.
Validate the rendered Compose configuration before starting:
```bash
docker compose config --quiet
```
### 4. Build, migrate, and start
```bash
docker compose up -d db
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate
docker compose up -d --build app
docker compose ps
curl -fsS http://127.0.0.1:3000/api/health
```
Rebuild `migrate` as shown; `docker compose run` reuses the last built tools image, so without the build step an update can run stale seed code against a newer schema.
`migrate` runs migrations **and the demo seed** (seeded services, sample volunteers, and `admin@glenloch.local`). The seed is idempotent. For a clean production dataset, sign in with the seeded admin, then edit the services and people in Admin; do not re-run the seed after customizing.
### 5. First sign-in and admin bootstrap
Keep the app on loopback and use an SSH tunnel for this step:
```bash
ssh -L 3000:127.0.0.1:3000 you@media.example.org
```
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from the page or from `docker compose logs app`. Then:
1. Admin → People: change the admin name and email to the real person, and create real accounts.
2. Admin → Services: set real service times, roles, and headcounts.
3. Remove or deactivate the seeded demo people.
4. Configure the real sender in Admin → Email delivery (Gmail app password) or set `POSTMARK_SERVER_TOKEN`.
Only after that, set `MAGIC_LINK_DEV_TRANSPORT=false` in `.env` and restart:
```bash
docker compose up -d app
```
**Do not expose the app publicly while the dev transport is on:** it displays sign-in links in the browser. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
### 6. Reverse proxy and TLS with Caddy
Install Caddy from its official repository:
```bash
sudo apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
| sudo gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
| sudo tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null
sudo apt-get update
sudo apt-get install -y caddy
```
Write `/etc/caddy/Caddyfile` (replace the hostname):
```caddyfile
media.example.org {
encode zstd gzip
reverse_proxy 127.0.0.1:3000
}
```
```bash
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
sudo systemctl status caddy --no-pager
```
Caddy obtains and renews the certificate automatically once DNS and ports 80/443 are correct. Nginx also works: proxy to `http://127.0.0.1:3000` and set a body limit large enough for video uploads.
### 7. Firewall
```bash
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status
```
`APP_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app and database off the public interface.
### 8. Background jobs (cron)
Create `/usr/local/bin/media-hub-cron`:
```bash
sudo tee /usr/local/bin/media-hub-cron >/dev/null <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
cd /opt/glenloch-media
secret="$(sed -n 's/^CRON_SECRET=//p' .env | head -1)"
base="http://127.0.0.1:3000"
case "${1:-}" in
notifications) endpoints=(notifications) ;;
daily) endpoints=(instances slots complete) ;;
*) echo "usage: $0 notifications|daily" >&2; exit 2 ;;
esac
for endpoint in "${endpoints[@]}"; do
curl -fsS -H "Authorization: Bearer $secret" "$base/api/dev/cron/$endpoint" >/dev/null
done
EOF
sudo chmod 700 /usr/local/bin/media-hub-cron
```
Schedule it in root's crontab (`sudo crontab -e`):
```cron
*/5 * * * * /usr/local/bin/media-hub-cron notifications
15 3 * * * /usr/local/bin/media-hub-cron daily
```
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)
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:
```bash
sudo apt-get install -y nfs-common
sudo mkdir -p /mnt/glenloch-media
sudo mount -t nfs nas.example.org:/export /mnt/glenloch-media
```
Persist it in `/etc/fstab`:
```fstab
nas.example.org:/export /mnt/glenloch-media nfs defaults,_netdev,nofail 0 0
```
Set the host path in `.env`, recreate the app, and verify write access as the container user (UID 100):
```dotenv
MEDIA_ARCHIVE_DIR=/mnt/glenloch-media
```
```bash
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).
### 10. Email delivery
Configure one transport in Admin → Email delivery:
- **Gmail SMTP** — the sending Gmail address plus a Google app password (requires 2FA on that account). The password is stored encrypted with `NEXTAUTH_SECRET`.
- **Postmark** — set `POSTMARK_SERVER_TOKEN` and `POSTMARK_FROM` in `.env`, then `docker compose up -d app`.
Without either, mail goes to the console transport under `OUTBOX_DIR` and is visible with `docker compose logs app`. Use Admin → Notifications → **Send test** to confirm delivery.
### 11. Backups
Use Admin → Backup & restore to download a ZIP of the database dump, uploads, archive, and manifest. Keep copies off the server, and store `.env` (especially `NEXTAUTH_SECRET`) separately with the backup. Restore on a fresh stack through the same admin panel; the database load is one transaction.
At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup.
### 12. Updating the deployment
Take a backup, then:
```bash
cd /opt/glenloch-media
git pull --ff-only
docker compose --profile tools build migrate
docker compose --profile tools run --rm migrate
docker compose up -d --build app
docker compose ps
curl -fsS http://127.0.0.1:3000/api/health
```
`migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit:
```bash
git log --oneline -5
git checkout <previous-commit>
docker compose up -d --build app
# after fixing:
git switch main
```
### 13. Health and troubleshooting
| Symptom | Check |
| --- | --- |
| 502 from Caddy | `docker compose ps` (app should be `healthy`), then `docker compose logs --tail=100 app`. |
| Login link not delivered | `MAGIC_LINK_DEV_TRANSPORT`, Gmail/Postmark configuration, `docker compose logs app`, and the console outbox. |
| `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`. |
| 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. |
### 14. Production checklist
- [ ] `NEXTAUTH_SECRET` generated, backed up, and not reused from development.
- [ ] `PUBLIC_ORIGIN` and `NEXTAUTH_URL` set to the public HTTPS URL.
- [ ] `APP_BIND=127.0.0.1`, `POSTGRES_BIND=127.0.0.1`, and Postgres is not reachable from the internet.
- [ ] `AUTO_ACTIVATE_NEW_USERS=false`, `ALLOW_DEV_RESET=false`, `MAGIC_LINK_DEV_TRANSPORT=false`.
- [ ] Strong, URL-safe `POSTGRES_PASSWORD`; `.env` is mode `600`.
- [ ] TLS certificate issued; HTTP redirects to HTTPS.
- [ ] 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).
- [ ] The `/api/dev/*` prefix is historical: 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.