From 872d1cb29e5bf33d75d9148401451295e9a65d25 Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Fri, 20 Nov 2026 05:14:57 +0000 Subject: [PATCH] docs: rewrite README for the shipped application 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. --- README.md | 373 +++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 286 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 7ac06be..56c10a5 100644 --- a/README.md +++ b/README.md @@ -1,120 +1,319 @@ # Media Team Hub -Scheduling and training platform for a church media team. +Scheduling, availability, training, and media operations for a church media team. -> **Current state:** the app is built and running (Next.js 15 + Postgres, containerised). For the live code map, phase status, the security/correctness repair pass, remaining gaps and next steps, read **[docs/PROJECT-STATE.md](docs/PROJECT-STATE.md)**. The sections below are the original planning docs and describe intended behaviour; the stack notes are historical (the build targets a portable Node container, not Cloudflare Workers). +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. -## Read in this order +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. -| Doc | What it answers | Length | +> **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/`, a minimal `/embed/` 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 . 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 | | --- | --- | --- | -| **[docs/FEATURE-SUMMARY.md](docs/FEATURE-SUMMARY.md)** | Plain-language feature list with a tick-box sign-off — send this to the ministry leader. | ~5 min | -| **[docs/BUILD-SPEC.md](docs/BUILD-SPEC.md)** | What are we building, screen by screen, and in what order? The build team's source of truth. | ~15 min | -| **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** | How is it built — stack, data model, scheduling and reminder logic, security. | ~25 min | -| **[docs/BUILD-PLAN.md](docs/BUILD-PLAN.md)** | The order to build it in: 56 units across 10 phases (plus 5 deferred media-library units), 7 checkpoints, and the rules that stop an AI agent looping. Give this to the agent. | ~15 min | +| `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 | -## Media library & video +Set `CRON_SECRET` before enabling the timer; without it the routes only accept an authenticated session. -**Media** is an ad-free library of the event photos and videos the signed-in -person can access. Event photos remain private to assigned photographers and -managers; the library does not publish them. +## Backup and restore -Videos are uploaded from an event page or the Media page: +Admin → Backup & restore downloads one ZIP containing: -- The untouched camera original is written to - `//videos//