Files
glenloch-media/docs/ARCHITECTURE.md
T
Tiel Coder c595865496 A1: foundation scaffold (Next.js 15, shadcn/Radix, Drizzle+Postgres, Vitest, Docker)
- Next.js 15 + TS strict + Tailwind 4 + ESLint 9
- shadcn/ui initialized (Radix, CSS variables); cn() util
- Drizzle + postgres driver + Zod; db client + schema placeholder (A2)
- Vitest with passing cn() test; GitHub Actions CI
- Portable container stack: multi-stage non-root Dockerfile, docker-compose (app + Postgres on host 5433)
- Verified: typecheck, lint, test (3), build, docker build, HTTP 200 on :3000
- Records the 5 pre-build decisions (email-only launch, SMS deferred)
2026-11-17 18:09:24 +00:00

76 KiB
Raw Permalink Blame History

Media Team Scheduling Platform — Architecture

Field Value
Product Media Team Hub (working name)
Owner Media Director
Status Draft v1.0 — for technical review
Last updated 2026-11-17
Companion docs BUILD-SPEC.md (what to build), ../README.md (index)

1. What this system is

A scheduling and enablement platform for a church media team. It replaces the spreadsheets, group texts and "who's on slides this Sunday?" messages with one source of truth:

  • Admin approves volunteers and builds the weekly schedule for three production roles — Audio, Livestream, Slides.
  • Volunteers publish blackout dates, confirm or decline assignments, and request swaps from their phone.
  • The system emails and text-messages each scheduled volunteer the Friday before they serve, and again on the day, with call times.
  • Training lives in the same product: written how-tos and video tutorials authored with a rich text editor, with completion tracking tied to role eligibility.

Everything a leader writes — announcements, run sheets, training lessons, notification copy, service notes — is authored in a rich text editor.

1.1 Goals

# Goal Success measure
G1 Cover every weekly production slot ≥ 98% of published slots filled 7 days out
G2 Eliminate manual reminder chasing 100% of assigned volunteers receive the Friday reminder automatically
G3 Make availability trustworthy ≥ 90% of volunteers maintain blackout dates; near-zero "I forgot I was serving" incidents
G4 Onboard and train without the director New volunteer reaches qualified status without a 1:1 walkthrough
G5 Be usable on a phone in under 60 seconds Volunteer confirms or declines in ≤ 3 taps

1.2 Non-goals (v1)

  • Choir/worship team, ushers, greeters or children's ministry scheduling (design leaves room; do not build).
  • Payroll/volunteer-hour compliance reporting.
  • Live service control (this is not ProPresenter/OBS). We may link to run sheets; we do not drive the gear.
  • Native iOS/Android apps. We ship a mobile-first PWA.
  • Multi-campus. Single church, multiple service times.

2. Users and permissions

2.1 Personas

Persona Description Primary need
Media Director (Admin) Runs the media ministry, owns the gear and the roster Assign people fast, see gaps before Sunday, never chase a no-show
Team Lead (Coordinator) Volunteer who also builds part of the schedule Schedule their roles without full admin rights
Volunteer Serves 1–2× per month Know when I serve, tell them when I can't
Trainee In training, shadowing slots Learn the role, see what's coming
Applicant Signed up, not yet approved Get approved and onboarded

2.2 Permission matrix

Capability Admin Coordinator Volunteer Trainee Applicant
View own schedule / confirm / decline ✅ ✅ ✅ ✅ —
Submit blackout dates ✅ ✅ ✅ ✅ ✅
Request swaps ✅ ✅ ✅ — —
View team roster + contact info ✅ ✅ name+role only name+role only —
View training library ✅ ✅ ✅ ✅ ✅ (public intro only)
Build / edit schedule ✅ assigned roles only — — —
Publish a week (sends notifications) ✅ ✅ — — —
Approve users / assign roles & certifications ✅ — — — —
Author training content ✅ — — — —
Author announcements / pages ✅ ✅ — — —
Edit notification templates & rules ✅ — — — —
Settings, audit log, exports ✅ read-only — — —
Run AI assistant tools ✅ ✅ own data only own data only —

Coordinator scope is bound by feature, not by role: a coordinator has full control over scheduling, people, events, training and notifications — everything except design/theme and admin/system settings (which are admin-only). This overrides the earlier role-scoped assumption (user_scopes(role_id)); see the recorded decisions in README.md §"Decisions recorded from your answers".

Enums:

type UserStatus = 'invited' | 'pending_approval' | 'active' | 'inactive' | 'denied';
type SystemRole = 'admin' | 'coordinator' | 'volunteer' | 'trainee';
type CertLevel = 'trainee' | 'qualified' | 'lead';
type SlotStatus = 'open' | 'proposed' | 'confirmed' | 'declined' | 'covered';
type AssignmentSource = 'manual' | 'auto' | 'swap' | 'import';

3. System architecture

3.1 Context

flowchart LR
  subgraph People
    A[Admin / Coordinator]
    V[Volunteer / Trainee]
  end
  subgraph Platform["Media Team Hub"]
    UI[Next.js app<br/>mobile-first PWA]
    WK[Worker API<br/>server actions + route handlers]
    CRON[Scheduled Worker<br/>cron triggers]
  end
  DB[(D1 / PostgreSQL)]
  R2[(Object storage<br/>R2: images, video, exports)]
  EM[Postmark<br/>transactional email]
  SMS[Twilio<br/>SMS + A2P 10DLC]
  AI[LLM API<br/>OpenAI-compatible]
  CAL[Google/Apple Calendar<br/>ICS feed]

  A --> UI
  V --> UI
  UI --> WK
  WK --> DB
  WK --> R2
  WK --> EM
  WK --> SMS
  WK -->|assistive only| AI
  CRON --> DB
  CRON --> EM
  CRON --> SMS
  CRON -->|daily instance generation| DB
  V -->|subscribed feed| CAL
  CAL -.->|reads| WK

3.2 Request path

  1. Reads — React Server Components query the database directly in the Worker (no API hop), then stream HTML.
  2. Mutations — Server Actions with Zod-validated input, one authorization check per action (requirePermission(user, 'schedule.publish', { roleId })), then revalidatePath.
  3. Long/async work — nothing user-facing depends on a third party. Publishing a week writes rows and enqueues notifications rows; a cron worker drains the queue. An email or SMS outage can never block scheduling.
  4. Webhooks — /api/webhooks/postmark and /api/webhooks/twilio verify signatures and update delivery status.

3.3 Stack

Layer Choice Why
Framework Next.js 15 (App Router), React 19, TypeScript strict SSR for fast first paint on phones, server actions for mutation ergonomics
UI Tailwind CSS + shadcn/ui (Radix primitives) Accessible components, no design system from scratch, dark mode for booth use
Rich text TipTap 2 (ProseMirror) Schema-based JSON output, custom nodes (video, mention, callout), mature
Data SQLite/D1 via Drizzle ORM in production; Postgres 16 + Drizzle if self-hosting Typed schema, migrations in-repo, both dialects supported by the same query layer for the 20 tables we need
Validation Zod Shared schemas client + server + form errors
Auth Managed OIDC (Auth.js) with email magic link fallback Volunteers will not remember passwords; magic link is the adoption lever
Email Postmark server API + React Email templates Best-in-class deliverability for transactional mail, fast support, simple API
SMS Twilio Programmable Messaging via Messaging Service Deferred to a later phase (launch is email-only). A2P 10DLC support, STOP/HELP handled by Twilio, delivery receipts
Media Cloudflare R2 (S3-compatible, presigned uploads) Cheap egress, same platform as compute
Exports ExcelJS (XLSX), @react-pdf/renderer (PDF), hand-written RFC 4180 writer (CSV) Real spreadsheet files with typed dates and autofilters; no headless Chrome needed on Workers; zero-dependency CSV keeps correctness auditable
Jobs Cloudflare Cron Triggers → Worker routes No extra infra; 1-minute granularity is plenty
Observability Sentry + structured JSON logs + cron_heartbeats table Know reminders failed before a volunteer tells you
Hosting Cloudflare Workers (OpenNext) or Vercel Edge-cached static, single-region DB is fine at this scale

Alternative considered: off-the-shelf (Planning Center Services, Supersaas). Rejected as primary because the training library, church-specific reminder cadence and rich-text run sheets are the actual differentiator — but the build spec includes a CSV import from Planning Center so a future migration is not a dead end.

Alternative considered: Firebase. Rejected: relational integrity matters here (unique active assignment per slot, cascade rules, reporting joins), and SQL reporting for fairness/coverage would be painful.

3.4 Environment topology

Env Purpose Data Messaging
local Development Seeded SQLite + 1 mock admin Console transport (writes to /tmp/outbox)
preview Stakeholder review Isolated DB, copy of schema only Twilio test credentials, Postmark sandbox
production Live Real Live

Secrets are server-only env vars, never NEXT_PUBLIC_. Required keys:

DATABASE_URL or D1 binding DB
AUTH_SECRET / OIDC client id + issuer
POSTMARK_SERVER_TOKEN
POSTMARK_FROM=media@yourchurch.org
TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN
TWILIO_MESSAGING_SERVICE_SID
LLM_API_KEY            # assists only; app degrades gracefully without it
SENTRY_DSN
APP_ORIGIN=https://media.yourchurch.org

4. Data model

4.1 Entity relationships (core)

erDiagram
  USERS ||--o{ USER_SKILLS : rates
  SKILLS ||--o{ USER_SKILLS : measured_by
  ROLES ||--o{ POSITION_SKILLS : requires
  SKILLS ||--o{ POSITION_SKILLS : required_for
  USERS ||--o{ SKILL_ASSESSMENTS : assessed
  USERS ||--o{ GROWTH_GOALS : pursues
  SKILLS ||--o{ GROWTH_GOALS : target
  SKILL_CATEGORIES ||--o{ SKILLS : groups
  SKILL_CATEGORIES ||--o{ FUNCTIONS : groups
  VENDORS ||--o{ TECHNOLOGIES : makes
  TECHNOLOGIES ||--o{ SKILLS : specializes
  FUNCTIONS ||--o{ SKILLS : describes
  SKILLS ||--o{ SKILL_EQUIVALENCIES : relates_to
  EVENT_TYPES ||--o{ EVENTS : classifies
  EVENTS ||--o{ EVENT_POSITIONS : needs
  EVENTS ||--o{ SLOTS : staffed_by
  EVENTS ||--o{ EVENT_MEDIA : produces
  UPLOAD_BATCHES ||--o{ EVENT_MEDIA : contains
  SERVICES ||--o{ SERVICE_ROLE_REQUIREMENTS : needs
  ROLES ||--o{ SERVICE_ROLE_REQUIREMENTS : requires
  SERVICES ||--o{ SERVICE_INSTANCES : occurs_as
  SERVICE_INSTANCES ||--o{ SLOTS : contains
  ROLES ||--o{ SLOTS : staffed_by
  SLOTS ||--o{ ASSIGNMENTS : filled_by
  USERS ||--o{ ASSIGNMENTS : serves
  USERS ||--o{ UNAVAILABILITY : blocks
  USERS ||--o{ NOTIFICATION_PREFERENCES : configures
  USERS ||--o{ NOTIFICATIONS : receives
  NOTIFICATION_TEMPLATES ||--o{ NOTIFICATIONS : renders
  COURSES ||--o{ LESSONS : contains
  LESSONS ||--o{ LESSON_PROGRESS : tracked_by
  USERS ||--o{ LESSON_PROGRESS : completes
  SERVICE_INSTANCES ||--o| RUN_SHEETS : has
  ASSIGNMENTS ||--o{ SWAP_REQUESTS : raises

4.2 Tables

Conventions: id is a UUIDv7 text column; all timestamps *_at are UTC ISO-8601; all *_date are DATE in the church's local timezone; soft delete only where noted. Money none.

users

Column Type Notes
id text PK
email text unique, required lowercased
phone_e164 text nullable +15551234567, validated
first_name, last_name text
display_name text
system_role text enum above
status text enum above
avatar_url text R2 key
timezone text default church tz, IANA
emergency_contact text nullable name + phone, for booth emergencies
approved_by, approved_at text, ts
last_served_at ts denormalized, maintained on confirm
reliability_score numeric 0–100, computed nightly
notes text (rich text JSON) admin-only
created_at, updated_at, deactivated_at ts

Indexes: lower(email), status, system_role.

roles — production positions

Column Type Notes
id, slug, name text audio, livestream, slides
description text shown to volunteers
color_hex text calendar/grid colour
call_time_offset_minutes integer e.g. audio = -90 (arrive 90 min before service)
requires_certification boolean default true — when true, a solo assignment requires the position's core skills at required_level (see §5.8)
default_headcount integer default 1
sort_order integer

The skill taxonomy — five admin-defined tables, zero hardcoded lists

No category, vendor, product, function, position or skill name appears in application code. Every one is a row an admin can rename, reorder, retire or add. The only seeded artifact is seed/catalog.json, a starter library loaded on first boot and thereafter plain data.

Ontology — the distinction matters, so the schema enforces it:

Concept Is Example Who defines it
Category a domain grouping Audio, Video, Slides, Lighting, Networking Admin
Vendor (company) who makes the gear Blackmagic Design, Renewed Vision, Roland, Shure, Allen & Heath Admin
Technology (product) a specific tool, versioned ATEM Mini Pro, ProPresenter 7, V-1HD, QL5 Admin
Function an operation a person performs Camera switching, Lyric playback, Gain staging, Stream encoding Admin
Position a schedulable seat on a service Audio, Livestream, Slides, Lighting Admin
Skill a rated competency = function applied to a technology (either may be generic) "Switch cameras on ATEM Mini Pro", "Run FOH audio (any console)" Admin, composed from the above

skill_categories

Column Type Notes
id, slug, name text slug immutable after creation; name editable
description, color_hex, icon text drives chips and the matrix grouping
sort_order, active deactivated categories hide from pickers, keep history

vendors — technology companies

Column Type Notes
id, slug, name text
support_url, support_phone text nullable who to call when the board dies at 8:40 — genuinely useful in a booth
notes, active, sort_order

technologies — products

Column Type Notes
id, slug, name text "ATEM Mini Pro"
vendor_id FK, category_id FK text both required; a product may sit in one category
model_number, version_label text "SWATEMMINIBPR", "v9.2 firmware"
docs_url text linked from lessons and the gear page
purchased_on, serial_number date, text nullable optional asset tracking
retired_at ts nullable replaced gear stays for history
successor_technology_id text nullable "ATEM Mini Pro → ATEM SDI Pro ISO" migration hint
active, sort_order

functions — what a person does

Column Type Notes
id, slug, name text "Camera switching", "Lyric playback"
category_id FK text functions are grouped, not enumerated
description text the verb explained in one sentence
sort_order, active

skills — the rated unit (what a volunteer has a level in)

Column Type Notes
id, slug, name text auto-composed on create ("Switch cameras on ATEM Mini Pro"), then freely editable
category_id FK text required — every skill belongs to a domain
technology_id FK text nullable null = technology-agnostic ("Run FOH audio")
function_id FK text nullable null = "operate this thing" generically
dedupe_key text unique `category
description text what "qualified" means here — shown beside the volunteer's slider
mentor_min_level text default expert, overridable per skill
stale_after_days integer default 120
recert_required boolean gear/platform change ⇒ open growth goals for holders
sort_order, active

skill_equivalencies (phase 2)

from_skill_id, to_skill_id, kind[equivalent|supersedes|partial], penalty_levels, note

Swapping a Roland for a Blackmagic shouldn't orphan your roster. An equivalency says "an ATEM expert is qualified on the V-1HD at one level lower until assessed", and the readiness calculation applies penalty_levels with a visible "transferable — confirm on the new gear" note. Never silent certification.

Taxonomy integrity rules (enforced in the data layer, not just the UI):

  1. Nothing referenced is ever deleted. Skills with ratings, functions with skills, technologies with history, positions with assignments — all deactivate only. ON DELETE RESTRICT everywhere in the taxonomy graph.
  2. Slugs freeze after creation. They appear in URLs, ICS exports and notification links; the display name stays editable.
  3. Merge, don't duplicate. Two admins will create "Cameras" and "Camera Ops". A merge tool repoints user_skills, position_skills, skill_assessments, growth_goals and skill_equivalencies to the survivor in one transaction, keeping the highest verified level per user and writing an audit row per moved record count (not per row).
  4. Positions need a core skill. A position with no is_core skill cannot be published — otherwise "anyone can fill it" becomes the rule by accident.
  5. Every taxonomy mutation is admin-only and audit-logged (catalog.created, catalog.updated, catalog.deactivated, catalog.merged).
  6. No taxonomy literals in business logic. A CI test greps src/** for seeded names outside seed/, tests and fixtures; matching 'Audio' inside a query is a build failure. Display strings always come from the database.

Read path and caching. The catalog is read on almost every scheduling render and changes a handful of times a year, so it is loaded once per request into a Map and edge-cached with a catalog cache tag, invalidated on any mutation. Lookups are by id; joins are pre-resolved into a position → skills[] shape so the grid render never issues N+1 queries.

position_skills — what a schedulable position demands

Column Type Notes
position_id FK, skill_id FK text PK (position_id, skill_id)
weight integer 1–5, weight in the readiness score
required_level text minimum verified level to run this position solo
is_core boolean core skills gate hard; non-core only rank

Audio = FOH console (core, qualified) + wireless mics (core, assisted) + stage monitors (weight 2). Livestream = OBS encoder (core, qualified) + cameras (weight 3). Slides = ProPresenter (core, qualified) + lyric library (weight 2). This is the join that turns "who is an audio person" into "who can actually run audio this Sunday".

user_skills — the competency record

Column Type Notes
id, user_id FK, skill_id FK text unique (user_id, skill_id)
self_comfort integer nullable 0–100, the volunteer's own rating; null until they rate it
self_rated_at ts
verified_level text none | observer | assisted | qualified | expert
verified_by, verified_at text, ts mentor or admin who signed off
mentor_opt_in boolean volunteer agrees to teach this skill
mentor_ready boolean derived: verified_level >= skill.mentor_min_level and mentor_opt_in and admin-approved
last_served_on date maintained by the system on assignment completion — never entered by hand
notes text "solid on the new board, still shaky on monitor mixes"

Two numbers, one truth: verified_level is the gate, self_comfort is the signal. Never gate on self-report alone (people both under- and over-rate themselves); never ignore it (a 40%-comfort volunteer on a solo slot is a Sunday-morning phone call).

skill_assessments — append-only progression history

id, user_id, skill_id, assessor_id nullable, kind[self|mentor|admin|quiz], level_from, level_to, comfort_at_time, notes, created_at

Levels never change silently: every move up or down writes a row here. Powers the mentor's queue, the "observer → qualified in three months" growth report, and the audit trail if someone asks why a person was cleared.

growth_goals — "I want to skill up"

Column Type Notes
id, user_id FK, skill_id FK text one active goal per (user, skill)
target_level text usually qualified
target_date date nullable
status text requested | mentor_assigned | in_progress | achieved | paused | declined
mentor_user_id text nullable validated against mentor_ready for that exact skill
shadow_count integer shadow services completed toward the goal
created_by, created_at text, ts self-requested or admin-suggested

services — recurring gathering templates

Column Type Notes
id, name text "Sunday 9:00 AM"
location text "Main Auditorium — Booth"
timezone text IANA, e.g. America/Chicago
rrule text FREQ=WEEKLY;BYDAY=SU (RFC 5545 subset: WEEKLY, BIWEEKLY, MONTHLY)
start_time_local text 09:00
duration_minutes integer 75
doors_open_minutes_before integer 30
active boolean
notes text

service_role_requirements

Column Type Notes
id, service_id FK, role_id FK text unique (service_id, role_id)
headcount integer how many people that role needs
min_level text per-service override of the minimum verified level (Christmas Eve may demand expert); defaults to position_skills.required_level

This is what makes "3 people every week" data, not code: Sunday 9:00 → audio ×1 (qualified), livestream ×1 (qualified), slides ×1 (qualified). Christmas Eve can demand 2 audio, 1 livestream, 2 slides.

service_instances — materialized occurrences

Column Type Notes
id text PK
service_id FK text template it came from
occurs_on date local date, e.g. 2027-01-10
starts_at, ends_at ts UTC instants, computed from local time + tz (DST-safe)
is_special boolean one-off (Christmas Eve, Good Friday)
title_override text nullable
status text draft | published | cancelled
published_at, published_by ts, text
notes text rich text JSON

Unique: (service_id, starts_at). Instance generation is idempotent on this key. Rolling window: cron keeps 16 weeks of future instances. Publishing is per week, not per instance.

slots

Column Type Notes
id text PK
service_instance_id FK text nullable cascade delete; exactly one of this or event_id (CHECK constraint)
event_id FK text nullable one-off event coverage; reuses the entire assignment pipeline
role_id FK text
slot_index integer 1..headcount, for labels ("Audio 2")
call_time ts = starts_at + role.call_time_offset_minutes
status text enum above, derived but stored for query speed
slot_note text "shadowing — Jordan training"
is_trainee_slot boolean shadow slots don't count toward coverage
paired_with_user_id text nullable mentor shadowing alongside this slot (see 5.8)

Indexes: (service_instance_id, role_id), status.

assignments

Column Type Notes
id text PK
slot_id FK text
user_id FK text
status text proposed | confirmed | declined | completed | no_show | cancelled
source text manual / auto / swap / import
assigned_by, assigned_at text, ts
responded_at ts
decline_reason text enum + free note
confirmed_via text app | email_link | sms_reply | admin
reminder_count integer

Invariant: at most one non-terminal assignment per slot: CREATE UNIQUE INDEX uq_active_assignment ON assignments(slot_id) WHERE status IN ('proposed','confirmed','completed'); History is preserved by keeping declined/cancelled rows.

unavailability — blackout dates

Column Type Notes
id, user_id FK text
kind text blackout | vacation | recurring | preference
starts_on, ends_on date inclusive; same day = one day
all_day boolean default true
reason text nullable private by default; admin visible
rrule text nullable recurring pattern, e.g. every other week
status text active | cancelled
created_at ts
created_by text self or admin

Constraints: ends_on >= starts_on; max span 365 days; block ranges overlapping an existing confirmed assignment with a warning (not a hard stop) so admins see the conflict. Conflict query (range overlap against a slot's local date):

SELECT a.id FROM assignments a
JOIN slots s ON s.id = a.slot_id
JOIN service_instances si ON si.id = s.service_instance_id
WHERE a.user_id = ?
  AND a.status IN ('proposed','confirmed')
  AND si.occurs_on BETWEEN ? AND ?;

notification_preferences

Column Type Notes
user_id PK text
email_enabled boolean default true
sms_enabled boolean default false until opted in
sms_consent_at, sms_consent_source ts, text web_signup | paper_form | admin_import — TCPA evidence
sms_consent_ip text
reminder_lead_days integer default 7
quiet_hours_start, quiet_hours_end text 21:00–08:00 local, SMS suppressed outside
digest_only boolean one weekly email instead of per-event

notification_templates

Column Type Notes
id, key text unique assignment.published, reminder.friday, reminder.day_of
channel text email | sms
subject text email only, supports {{vars}}
body_json, body_html, body_text text rich text authored in admin, rendered server-side
sms_body text ≤ 320 chars, merged at send
active, updated_by, updated_at

Variables are a typed allowlist, not arbitrary template syntax: {{volunteer.first_name}}, {{role.name}}, {{service.name}}, {{service.starts_at_local}}, {{slot.call_time_local}}, {{confirm_url}}, {{decline_url}}, {{team_names}}, {{location}}. Unknown variable → build fails in CI, not at send time.

notification_rules

Column Type Rules
id, key text t_7, friday, day_of, unfilled_alert
event text assignment.created | assignment.unconfirmed | slot.unfilled
offset_days integer -2 produces the Friday-before-Sunday reminder
send_at_local_time text 18:00
channel_set text email, email+sms, sms
applies_to_service_id text nullable null = all services
active boolean

Offset-based rules are the design decision that makes "Friday before" work for a Wednesday service too (it becomes Monday), without special-case code.

notifications — outbox (the queue is a table)

Column Type Notes
id text PK
user_id FK, channel text
template_key text
rule_key text nullable
assignment_id, slot_id text nullable traceability
payload_json text fully merged at enqueue time (audit)
dedupe_key text unique friday:{assignment_id}:sms
scheduled_for ts
status text queued | sending | sent | failed | suppressed | cancelled
attempts integer max 3 with backoff
provider_id, provider_status, error text
sent_at, created_at ts

Index: (status, scheduled_for). This is the single most important operational table — the admin notification log reads directly from it.

Training

courses(id, title, slug, summary, cover_image_url, role_id nullable, required_for_role boolean, sort_order, published, created_by, timestamps) lessons(id, course_id, title, slug, sort_order, content_json, content_html, video_provider enum[youtube,vimeo,r2,none], video_id, duration_seconds, published, timestamps) lesson_progress(id, user_id, lesson_id, status[not_started,in_progress,complete], watched_seconds, completed_at, unique(user_id, lesson_id)) quizzes(id, lesson_id, pass_score, questions_json) + quiz_attempts(id, user_id, quiz_id, score, answers_json, passed, created_at) — phase 3.

Rule: roles.requires_certification = true + a course with required_for_role = true ⇒ user cannot be assigned to that role until lesson_progress covers every required lesson and quizzes pass. Admin can override with a reason, which is written to audit_log.

Content

pages(id, slug, title, content_json, content_html, audience[public,members,leaders], updated_by, timestamps) — handbook, policies, gear guides. announcements(id, title, content_json, content_html, author_id, pinned, audience_role_id nullable, published_at, expires_at, email_blast_id nullable) run_sheets(id, service_instance_id unique, content_json, content_html, updated_by, timestamps) — order of service, cue times, song keys, special elements, "what could go wrong" notes. Printable.

swap_requests

id, assignment_id, requested_by, target_user_id nullable (null = open to team), reason, status[pending, accepted_by_peer, approved, rejected, expired, cancelled], resolved_by, resolved_at, created_at

Flow: volunteer requests → peer accepts (if targeted or open) → coordinator approves → assignment moves. A swap never silently changes a published schedule without approval.

media_assets

id, r2_key, filename, mime, bytes, width, height, kind[image,video,doc], uploaded_by, alt_text, created_at

event_types — admin-defined

id, slug, name, color_hex, default_position_ids_json, requires_media_release, active, sort_order

Weddings, baptisms, youth nights, outreach, productions, conferences. Nothing about event categories lives in code; the defaults just prefill the position list when someone creates that kind of event.

events — the second scheduling axis

Weekly services are a recurrence; events are one-offs with a requester and a deliverable. They are deliberately separate rows but the same assignment machinery.

Column Type Notes
id, slug, title text "Baptism Sunday — 4 candidates"
event_type_id FK text from event_types
starts_at, ends_at, timezone ts, text UTC instants + IANA tz, same rules as services
is_all_day boolean
location, room text
requester_name, requester_phone, requester_id text nullable who asked for coverage — usually a ministry leader who will also review the photos
description_json, description_html text rich text: what's happening, who matters, what to capture
brief_json, brief_html text the shot list / creative brief the photographer reads on their phone
status text draft | published | covered | uploaded | editing | delivered | cancelled | archived
positions_needed_note text "2 shooters, one at the back for wide"
gear_note text "bring the 70–200; house flash is in the cabinet"
media_release_required boolean default from event_types; blocks publishing galleries for events with minors present
publish_gallery boolean opt-in, never automatic
created_by, created_at, updated_at
cancelled_reason text nullable

Index: (starts_at), (status, starts_at).

event_positions

id, event_id FK, position_id FK, headcount, min_level, call_time_offset_minutes, notes

Position rows come from the same positions catalog (Photographer, Second Shooter, Videographer, Livestream…), so a photographer's competency, mentor and availability logic is identical to an audio volunteer's. Photography is a position category, not a second product.

event_gear_assignments (phase 2)

id, event_id, gear_item_id, assigned_user_id, checked_out_at, returned_at, condition_note — who took which body and lens, so gear stops disappearing into someone's trunk.

upload_batches (phase 2 — media library)

Column Type Notes
id, event_id FK, uploaded_by text
status text open | uploading | complete | abandoned
file_count, bytes_total integer running totals
multipart_manifest_json text part ETags per file — this is what makes resume work
manifest_checksum text batch-level SHA-256 of the file list
license_accepted_at ts photographer usage-licence acknowledgement
created_at, completed_at ts

event_media (phase 2 — media library)

Column Type Notes
id, event_id FK, batch_id FK text
r2_key text events/{eventId}/{batchId}/raw/{filename}
proxy_r2_key text nullable JPEG preview for the browser (see 8.5.3)
filename, camera_model, shot_at text, ts from EXIF where available
format text raw | jpeg | video
bytes, width, height, checksum_sha256 integer, text checksum gives idempotent re-upload
status text original | selected | edited | published | rejected
uploaded_by, created_at
retention_expires_at ts originals expire per policy; finals do not

Unique (event_id, checksum_sha256) — uploading the same RAW twice is a no-op with a friendly message, not a duplicate.

media_downloads

id, media_id FK, user_id, granted_by, purpose, expires_at, downloaded_at, ip_hash

Every RAW download is a row. "Who took the originals?" is answerable, and RAW access is a permission (media.raw_download), not a role assumption.

export_jobs

Column Type Notes
id text PK
requested_by text FK
dataset text schedule | booth_sheet | roster | availability | training_progress | serving_history | notifications | audit
format text csv | xlsx | pdf
params_json text date range, filters, include_phone, include_notes, source screens — the receipt for what was in the file
scope_role_id text nullable coordinator scoping, enforced at query time
status text queued | running | ready | failed | expired
row_count, bytes integer
r2_key text nullable rendered artifact
error text nullable
expires_at ts ready + 7 days, then the object is deleted
created_at, completed_at ts

Index: (requested_by, created_at desc), (status, created_at).

audit_log

id, actor_id, actor_ip_hash, action, entity_type, entity_id, before_json, after_json, created_at Actions: user.approved, user.denied, role.granted, assignment.created, assignment.declined, week.published, blackout.created_on_behalf, template.updated, content.published, settings.changed, export.generated, assignment.override. Retention 24 months. No update/delete rights from the app.

ai_runs

id, user_id, feature, model, prompt_tokens, completion_tokens, cost_cents, latency_ms, status, input_hash, output_json, created_at Redacted prompts only; no phone numbers or email bodies stored.

settings

Key/value JSON: church.name, church.timezone, church.address, branding.primary_color, scheduling.window_weeks, scheduling.allow_self_assign, notifications.default_lead_days, sms.sender_label, training.cert_required.

cron_heartbeats

job_name PK, last_run_at, last_status, last_duration_ms, consecutive_failures — powers an admin banner when the reminder worker dies silently.

4.3 Migrations & seeding

  • Drizzle migrations, forward-only, committed to the repo, applied by CI before deploy.
  • Seed script creates: 3 roles, Sunday 9:00 & 11:00 services, requirement matrix, 6 sample volunteers, 8 weeks of instances, 2 courses.
  • Production bootstrap: create first admin via CLI (npm run bootstrap:admin -- email=...), then invite everyone else from A3.

5. Domain logic

5.1 Instance generation

Cron 0 6 * * * (church-local 06:00, expressed in UTC):

target = today + 16 weeks
for each active service:
  dates = expandRRULE(service.rrule, now, target)
  for each date:
    starts_at = zonedTimeToUtc(date + service.start_time_local, service.timezone)
    upsert service_instances(service_id, starts_at) where status != 'cancelled'
    if new: create slots from service_role_requirements (skip if instance already published)

Rules: never modify a published instance's slot set; never delete past instances; cancelled instances are excluded from generation via the unique key plus status='cancelled' guard. DST is handled by storing UTC instants and rendering with the IANA timezone — never by adding 24h.

5.2 Slot and assignment state machines

stateDiagram-v2
  [*] --> open
  open --> proposed: assign
  proposed --> confirmed: accept
  proposed --> declined: decline / no response by cutoff
  declined --> proposed: reassign
  open --> confirmed: admin force-confirm
  confirmed --> completed: past date, marked served
  confirmed --> no_show: past date, marked absent
  confirmed --> open: unassign / approved swap out
  • Slot status is derived from its active assignment and cached on write.
  • Coverage = count(slots where status='confirmed' and not is_trainee_slot) / count(slots where not is_trainee_slot).
  • A published week with open slots creates slot.unfilled alerts at T-7 and T-3.

5.3 Conflict detection (runs on every assign attempt)

Blocks with a hard error:

  1. Volunteer inactive or unapproved.
  2. Duplicate person in the same instance (any position).
  3. A core skill verified below the position's required_level.
  4. Shadow pair where the paired mentor is not mentor_ready for that exact skill.

Warns but allows (admin override, reason required → audit_log + skill_assessments note): 5. Overlaps a submitted blackout date. 6. Exceeds max_services_per_month preference (default 3). 7. Volunteer already serves the other service that morning (back-to-back). 8. Self-rated comfort below 50% on the position's core skill — "Jordan rates their comfort on the FOH console at 40%. Confirm they're really ready for a solo slot." 9. Skill is stale (no service on it in stale_after_days) — "Sarah last ran Livestream 5 months ago." 10. Position readiness score below settings.scheduling.readiness_warn_threshold (default 70).

The difference matters: only core-skill gaps stop an assignment outright. Comfort, staleness and non-core gaps are information the admin needs, not decisions the software makes for them.

5.4 Auto-fill (§ the algorithm, not the LLM)

Deterministic, explainable, and always a suggestion the admin accepts:

// 1. HARD FILTERS — availability first, then competency gate
candidates = users where active
  and not unavailable(occurs_on)
  and not alreadyAssigned(instance)
  and underMonthlyCap()
  and allCoreSkills(verifyLevel(position), >= required_level)

// 2. RANK — competency is the second-largest term after fairness
score =  0.30 * fairness       // 1 - (assignments_last_8_weeks / max_assignments_anyone)
       + 0.30 * competencyFit  // 0.7 * levelScore + 0.3 * (self_comfort / 100)
       + 0.15 * reliability    // confirm rate, no-show penalty
       + 0.10 * recencyBonus   // hasn't served this skill in 21+ days
       + 0.10 * growthIntent   // open growth goal here AND a mentor is free that day
       + 0.05 * preference     // prefers this position

// levelScore: none 0 · observer 0.35 · assisted 0.55 · qualified 0.80 · expert 1.00
// weighted by position_skills.weight across the position's skills

Greedy assignment over slots sorted by constraint difficulty (fewest eligible candidates first), ties broken by last_served_at ascending then id for determinism. Output is a proposals[] array rendered as ghost cards on the grid with the score breakdown in a tooltip ("Sarah — 4 slots in 8 wks, confirmed 100%, prefers audio"). Nothing is written until the admin clicks Apply.

This exists because the hard part of volunteer scheduling is fairness and constraints, which are solved better by 60 lines of ranked scoring than by a model.

5.8 Skill & competency model

5.8.1 The taxonomy is data (see §4.2)

Categories, vendor companies, technologies, functions, positions and the skills composed from them are all admin-defined rows. The app ships a starter catalog — FOH console, wireless mics, ProPresenter, OBS encoder, cameras, lighting board — as seed/catalog.json, and treats it exactly like anything an admin adds later: editable, renameable, retirable.

This is a deliberate architectural constraint, not a config screen bolted on afterwards:

  • No enum of skills, positions or vendors exists in code. Adding "Lighting" as a schedulable position, or "Resolume" as a technology, is a data change — no deploy.
  • Business logic reads the taxonomy, never a literal. position_skills rows decide what a slot requires; user_skills rows decide who qualifies.
  • Retiring is not deleting. Gear is sold, positions are renamed, volunteers move on — history must survive all of it.
  • Skill names are composed, not invented per user. Creating a skill from Camera switching × ATEM Mini Pro prefills the name so a church of five admins ends up with one vocabulary instead of five.

5.8.2 Levels

Level Comfort band (self) Meaning Can run solo Can mentor
none 0–24 Never touched it ❌ ❌
observer 25–49 Watched someone run it ❌ ❌
assisted 50–74 Can run it with someone nearby ❌ (pair only) ❌
qualified 75–89 Can run it start to finish alone ✅ ❌
expert 90–100 Runs it alone and can teach it ✅ ✅

Admin-configurable per skill via mentor_min_level; the band is guidance for the volunteer's slider, not the gate.

5.8.3 Position readiness (derivation)

readiness(position, user):
  for each core skill: if verified_level < required_level → BLOCKED (with reason)
  score = Σ(weight_i × levelScore(skill_i)) / Σ(weight_i)
  comfort = mean(self_comfort of the position's core skills)   // null-safe
  blended = comfort == null ? score : 0.7 * score + 0.3 * (comfort / 100)
  return { score: round(blended * 100), blocked: bool, missing: [skill names] }

This is what the picker displays as "Audio readiness 82%" with a breakdown popover: FOH console 0.80 (qualified, verified by Marcus, Apr 12) · wireless mics 0.55 (assisted) · comfort 75%.

5.8.4 The scheduling picker contract (the core requirement)

Open a slot → the candidate list is availability-filtered first, then ranked. Every row shows, in this order:

Name · readiness % · verified level on each required skill · self comfort · mentor badge · last served · status (Away / Already serving / Needs refresher).

  • Sort modes: Best match (default, the score above) · Most rested (fairness first) · Highest skill · Available only (alphabetical, for when the admin already knows who they want).
  • Unavailable people are not hidden — they are greyed with "Away Nov 21–28" and a link to their blackouts. Hiding them causes the admin to wonder if the list is broken.
  • Growing volunteers get an explicit badge: "Wants to learn Slides — 2 shadows in." When a mentor is also free that instance, the picker offers "Assign as shadow pair with Marcus" in one click.
  • Every row has a "Why this person?" popover with the score breakdown. No black box.

5.8.5 Mentors

A mentor is per-skill, not a global title:

  • mentor_ready = verified_level >= skill.mentor_min_level and mentor_opt_in (volunteer agrees to teach) and an admin has approved it. Expertise alone does not volunteer someone.
  • A shadow slot is only valid with a mentor in the same service instance holding that skill at expert. The DB/constraint level and the UI both enforce it.
  • Caps: one mentor supervises at most 2 shadows per service; a mentor's own slot still counts toward coverage, the shadow slot does not.
  • Mentor call time is 15 minutes earlier than the position's, from a skill.mentor_lead_minutes setting, so the brief happens before the room fills.
  • After the service the mentor gets a one-tap assessment prompt: "How did Jordan do on Slides?" → observer / assisted / qualified + note. That single interaction is how competency actually advances in a volunteer organization — not a certification course.

5.8.6 Growth goals lifecycle

stateDiagram-v2
  [*] --> requested: volunteer asks "I want to learn Slides"
  requested --> mentor_assigned: admin picks a mentor_ready volunteer
  requested --> declined: no capacity this season
  mentor_assigned --> in_progress: first shadow scheduled
  in_progress --> in_progress: shadow completed + assessment logged
  in_progress --> achieved: mentor signs off target_level
  achieved --> [*]
  declined --> [*]
  • A volunteer can hold many skills at different levels but only one active goal per skill.
  • Admin view (/admin/growth) sorts by wait time and shows mentor capacity: "3 people want Livestream; Marcus and Dana can mentor; Marcus is available 2 of the next 4 Sundays."
  • When an auto-fill run finds a mentor and a growth candidate both free, it proposes a shadow pair as a separate suggestion — never silently occupying a coverage slot.
  • Achieved goals raise the verified level via a skill_assessments row, which immediately makes the person eligible for solo slots and updates the readiness score everywhere.

5.8.7 Decay and recertification

  • last_served_on is maintained by the system; a skill untouched for stale_after_days (default 120) shows "needs refresher".
  • Stale people rank lower but are never blocked — a church cannot afford to lock out a capable volunteer because they took a quarter off.
  • Stale + a qualified core skill triggers a training suggestion (refresher lesson + one shadow) rather than a hard gate.
  • Live-stream platforms and gear change; a skill can be marked recert_required, which opens a growth goal for everyone holding it at qualified.

5.8.8 How this connects to training

Completing a course sets self_comfort upward suggestion and creates an assessment task for a mentor — it does not auto-certify. Knowledge from a video is not the same as hands on the board at 8:40 on a Sunday, and the model refuses to pretend otherwise.

5.5 Publishing a week

One transaction:

  1. Validate: no slot with open status unless admin ticks "publish with gaps".
  2. Set service_instances.status = 'published', published_at.
  3. For each assignment: enqueue assignment.published (email now; SMS only if inside 72h or user is sms-only).
  4. Enqueue rule-based reminders by computing send_at = instance.starts_at + offset_days at send_at_local_time in church tz, skipping rules whose send time is already past.
  5. Generate ICS payloads (or rely on the subscribed feed).
  6. Write audit_log row week.published.

Unpublishing is allowed only while no volunteer has confirmed; otherwise the UI requires unassigning first.

Every notification carries signed, single-purpose tokens:

/respond?t=<jwt>&a=confirm|decline
payload: { assignmentId, userId, exp: +14d, jti }
  • HS256 with a rotating server secret, assignmentId binding, single use recorded by jti in a used_tokens table.
  • GET renders a confirmation page (never mutates); POST performs the action. This prevents link prefetchers from auto-accepting shifts.
  • After acting, the page offers "Add to calendar" and "Open full schedule" (magic-link sign-in).

5.7 ICS feed

GET /api/calendar/{userId}/{token}.ics — stable opaque token per user, revocable in settings. Contains confirmed + proposed assignments for 8 weeks past / 16 weeks future, VEVENT per slot with SUMMARY = Audio — Sunday 9:00, LOCATION, DTSTART = call_time, DESCRIPTION = role notes + run sheet link. X-WR-CALNAME = Media Team. This alone removes most "when am I serving?" texts.


6. Notification subsystem

Launch scope: email-only. The pipeline is channel-agnostic; SMS (Twilio) is a later addition with no rework — see §3.3.

6.1 Pipeline

flowchart LR
  E[Domain event<br/>assignment.created / week.published] --> R[Rule resolver]
  R -->|offset + local send time| Q[(notifications outbox)]
  Q --> C{Cron every 5 min}
  C --> G{Guards}
  G -->|dedupe, quiet hours,<br/>consent, cancel-if-declined| S[Send]
  S --> P[Postmark]
  S --> T[Twilio]
  P --> W1[webhook: delivered / bounced]
  T --> W2[webhook: delivered / undelivered / STOP]
  W1 --> Q
  W2 --> Q
  G -->|suppressed| Q

Guards before send (in this order): already sent? → dedupe key exists? → assignment still active and not declined? → user still active? → channel consented? → quiet hours for SMS (queue to 08:00 next day) → send.

Failure policy: 3 attempts with 5/30/120-minute backoff. After final failure, mark failed, post to admin dashboard, and — if the channel was SMS — re-send the same content by email. A failed reminder on a Friday night must page the admin, not sit in a table.

6.2 Reminder matrix (defaults)

Key Event Offset Local time Email SMS To
invite user invited now — ✅ — invitee
user.approved approval now — ✅ — volunteer
assignment.published week published now — ✅ ✅ if <72h volunteer
reminder.t7 assignment unconfirmed −7 d 09:00 ✅ — volunteer
reminder.friday assignment −2 d 18:00 ✅ ✅ volunteer
reminder.day_of assignment 0 d 06:30 — ✅ volunteer
reminder.t3_unconfirmed still unconfirmed −3 d 09:00 ✅ ✅ volunteer + coordinator
slot.unfilled open slot on published week −7 d, −3 d 09:00 ✅ ✅ coordinators
swap.requested swap created now — ✅ — coordinator
swap.approved swap approved now — ✅ ✅ both volunteers
training.assigned course required now — ✅ — volunteer
digest.weekly Monday summary −6 d from next Sunday 07:00 ✅ — admins
growth.assigned mentor matched to a skill-up goal now — ✅ — volunteer + mentor
assessment.due shadow service completed +1 d 19:00 ✅ ✅ mentor
level.verified mentor signs off a level now — ✅ — volunteer
refresher.suggested skill stale past threshold weekly check 09:00 ✅ — volunteer
event.assigned photographer assigned to an event now — ✅ ✅ photographer
event.reminder event coverage −2 d 09:00 ✅ ✅ photographer
event.unfilled event position open −7 d, −3 d 09:00 ✅ ✅ admins
media.deliverable_due event past deliverable_due with no upload +1 d after due 09:00 ✅ ✅ photographer + admin

The headline requirement — Friday before — is reminder.friday at −2 days, 18:00 local, both channels. Because it is a rule row, the church can move it to Thursday 20:00 in the admin UI without a deploy.

6.3 Message design

Friday SMS (must fit two segments, include call time and a link):

Media Team: Brian, you're on SLIDES this Sunday, Nov 22 at 9:00 AM.
Call time 8:15 AM · Main Auditorium booth.
Confirm: https://media.church.org/r/abc123
Reply STOP to opt out.

Rules: church name first (sender identity), name + role + date + call time in the first line, one short link, no ALL CAPS shouting, no more than one link. Email is the full version: role, call time, location, who else is serving, run sheet link, "can't make it?" swap button, and a plain-text alternative.

Email deliverability: dedicated subdomain (media.church.org), SPF + DKIM + DMARC p=none → quarantine, List-Unsubscribe header with one-click, no marketing content in transactional mail, and a Reply-To that a human reads.

6.4 SMS compliance (must-do, not optional)

  • A2P 10DLC registration with The Campaign Registry via Twilio before any production send: brand (EIN) + campaign use case ("volunteer scheduling reminders"), ~1–3 weeks lead time. Budget for one-time brand+campaign fees and a small monthly campaign fee.
  • Explicit opt-in with timestamp, source, and IP stored in notification_preferences. Signup copy: "Text me scheduling reminders. Message frequency varies (about 4/month). Msg & data rates may apply. Reply STOP to cancel, HELP for help." Consent is never bundled with the account terms.
  • STOP/START/HELP handled by Twilio's Messaging Service; the webhook flips sms_enabled and writes an audit row.
  • Send window 08:00–21:00 local only; quiet hours queue rather than drop.
  • No PII beyond first name, role and date. No URLs with tokens in SMS logs.

7. Rich text subsystem

TipTap is used in five places: training lessons, notification templates, announcements/pages, run sheets, and admin notes.

7.1 Editor configuration

StarterKit (headings 1–3, bold/italic/strike, lists, blockquote, code block, hard break, history), plus:

Extension Purpose
Link auto-link, rel="noopener noreferrer", blocks javascript:
Image upload to R2, caption, alt text required
Table run sheets, gear checklists
TaskList / TaskItem pre-service checklists
TextAlign, Highlight, Placeholder, CharacterCount
Youtube / custom VideoEmbed node tutorial videos
Mention @Brian linking to a user profile
Callout (custom node) ⚠️ "don't touch the gain knob" style warnings
SlashCommand /video, /callout, /checklist for non-technical authors

7.2 Storage & rendering contract

  • Canonical storage is ProseMirror JSON (content_json). Never store user HTML as the source of truth.
  • On save, the server runs generateHTML(json, schema) with the same allowlisted schema and stores content_html for fast list/email rendering. Client HTML is never trusted.
  • Any imported/pasted content is normalized through the schema (Google Docs paste is cleaned by prosemirror-paste-rules).
  • Links: allow https:, mailto:, tel: only. Images: allow https: on approved hosts.
  • Embeds: iframe src must match an allowlist (youtube-nocookie.com, player.vimeo.com); stored as provider + id, rendered from a component — never a raw iframe string.
  • Versioning: content_revisions(entity, entity_id, content_json, author_id, created_at) on publish, keeping the last 20 per entity, with a diff/restore view. Authors will overwrite a lesson.
  • Email rendering: a separate React Email component consumes the same JSON → table-based HTML (email clients ignore modern CSS). One content model, two renderers.
  • Accessibility: heading order validated on publish; images without alt text block publishing; tables need a header row.

7.3 Media pipeline

POST /api/uploads/sign → validates type/size → returns presigned R2 PUT (10 MB images, 500 MB video) → client uploads directly → POST /api/uploads/complete records media_assets. Images are served through Cloudflare image resizing (/cdn-cgi/image/w=800). Video for v1 is unlisted YouTube/Vimeo (free transcoding, adaptive bitrate, works on church wifi); direct R2 video is phase 3 with signed playback URLs.

Orphans: nightly job deletes media_assets unreferenced for 30 days.


8. Training subsystem

  • Course → Lessons. A course is a role pathway ("Audio 101"), a lesson is a rich text + optional video page.
  • Progress is per lesson (not_started → in_progress → complete), aggregated to a per-course ring. Video progress is tracked with player events at 90% watched; text lessons complete on an explicit "Mark complete" after a 30-second minimum dwell.
  • Gating: if a course is required_for_role, only users with all lessons complete (and quiz passed, phase 3) appear in that role's assignment picker. Admins see a clearly labelled override.
  • Assignment: coordinator can assign a course to a new volunteer; it enqueues training.assigned and shows as an onboarding task.
  • Authoring UX: lesson list with drag-reorder, split-pane editor/preview, "publish" vs "save draft", ? help text everywhere. Non-technical authors are the users.
  • Video QA: a lesson with a dead embed must be catchable — nightly link check on embeds and external links, results on the admin dashboard.

8.5 Events, photography & media library

8.5.1 Why this is separate but not a second system

A Sunday service repeats; a wedding, baptism, youth night or outreach does not. Events need a requester, a brief, a deliverable deadline and often two shooters. So events get their own rows and their own screens — but they reuse availability, skill gating, the candidate ranker, confirm/decline tokens, the outbox and the audit log. Duplicating that pipeline would double every bug.

The one schema change that makes this work: slots accepts either a service_instance_id or an event_id, with a CHECK constraint enforcing exactly one. Assignments, reminders and confirmations then need no new code path.

8.5.2 Assignment flow

  1. A ministry leader submits an event request (form, or an admin creates it on their behalf).
  2. Admin sets positions: Photographer ×1 (qualified), Second Shooter ×1 (assisted), optionally Videographer.
  3. The same picker ranks people by availability → photography skill → fairness. Photography skills (photographer, second-shooter, plus technologies like canon-r6, sony-a7iv, speedlight) live in the normal catalog.
  4. Reminders use the same rule rows, with an event default of T-2 days at 09:00 rather than 18:00, because weeknight events exist.
  5. Confirm/decline uses the same magic links. The brief page is a phone-friendly attachment to the reminder.
  6. After the event: covered → uploaded → editing → delivered. Status is manual until the media library exists, then it advances on upload.

8.5.3 Media library — the constraints that decide the design

This is phase 2, but the design must be right now because it drives storage choices.

RAW files break naive upload. A body produces 25–80 MB per frame; a wedding is 800–2,000 frames. That is 20–100 GB per event, from a phone hotspot in a church lobby.

Constraint Consequence
Browsers cannot render CR3/NEF/ARW No native RAW thumbnail. Either the photographer uploads JPEG proxies from Lightroom/Capture One or a Node worker runs exiftool + libraw. Start with proxies — zero infrastructure, and the photographer already exports them.
Single PUT hits memory/time limits R2 multipart upload, 8 MB parts, 3–6 in flight, parts presigned per file
Uploads die on flaky wifi Resumable via upload_batches.multipart_manifest_json; resume from the last completed part, never restart the batch
100 GB cannot stream through one Worker Upload direct to R2 from the browser; the Worker only signs
Duplicate uploads are likely checksum_sha256 unique per event → idempotent accept
Editors want "all originals" A 60 GB ZIP is not a download. Offer a manifest CSV + sequential signed links, or select-N download. Say this out loud in the UI.

Pipeline: sign → multipart upload → complete (verify checksums, write event_media) → optional proxy association → cull (selected/rejected) → edit → re-upload finals as edited → publish gallery.

Permissions and privacy — this is the part that matters at a church:

  • RAW download requires media.raw_download, held by named editors only. Every download writes media_downloads (who, when, which file, purpose).
  • Signed URLs are 15 minutes, single use, and never logged with the token.
  • media_release_required blocks gallery publishing until an admin confirms consent, specifically covering minors.
  • A per-image rejected status is the practical "don't publish this one" control.
  • Photographers acknowledge a usage licence at batch creation (church may use for ministry promotion, photographer retains copyright) — stored, not implied.

Retention and cost: originals expire after settings.media.raw_retention_days (default 90, configurable up to 365); edited finals persist. A nightly job deletes expired objects and nulls r2_key while keeping the row for audit. At ~20 events/year × 40 GB, R2 storage lands near $12/month, and R2 charges no egress — which is why originals live there instead of S3.

8.5.4 Table

Concern Decision
Event schedule vs service schedule Same grid component, ?view=events, separate queries — never mixed into one week view
Photographer competency Normal skills; a Photography category with cameras, lenses and flash as technologies
Overlapping events Hard conflict: a person cannot be in two events whose times overlap
Unfilled photographer event.unfilled alert at T-7 and T-3, same as slots
Never uploaded Status stuck at covered past deliverable_due → dashboard flag + reminder to the photographer
Public galleries Phase 3; requires release confirmation, watermark option and a read-only route

9. AI features (assistive, never load-bearing)

Principles:

  1. The schedule works with the LLM offline. Every AI feature degrades to a form or a list.
  2. Deterministic math stays deterministic. Fairness ranking and constraint checks are code; the model may explain a result, never compute it.
  3. No autonomous writes. AI returns proposals and drafts. A human clicks Apply/Save. Every applied AI action is in audit_log with source='ai'.
  4. Minimum data. Send first names, roles, dates and availability flags — never phone numbers, emails, or pastoral notes.
  5. Bounded cost. Per-user daily call cap, model allowlist server-side, 8s timeout, max_tokens per feature, cost written to ai_runs.
ID Feature Implementation Phase
AI-1 Ask the schedule — "who can do audio Dec 7?", "who's out next month?" Tool-calling over 3 read-only functions (findAvailable, getCoverage, getAvailability); returns a table + prose 4
AI-2 Draft the message — announcement/reminder copy in the church's voice content_json in, content_json out, rendered into TipTap; tone presets 4
AI-3 Explain the auto-fill — "why Sarah and not Marcus?" Feeds the score breakdown to the model for a one-paragraph rationale 4
AI-4 Draft training lessons from a service recording transcript Transcript → outline → draft lesson (admin edits before publish) 5
AI-5 Coverage risk digest — Monday summary with the two riskiest slots Deterministic stats first, model writes the narrative 4
AI-6 Training assistant — "how do I set gain on the board?" RAG over published lessons + handbook, answers with citations to lesson URLs, refusal when no source 5
AI-7 Triage replies — parse "can't make it, I'm sick" into a structured decline Deterministic keyword match first, model only for ambiguous text, always shows a confirm chip 4

Guardrails: prompt-injection defence (user content is data, delimited and never concatenated into system instructions), output rendered through the TipTap schema so it cannot inject HTML/iframes, and a kill switch (settings.ai.enabled = false) that hides every AI affordance.


10. Security & privacy

Concern Control
Authorization Single requirePermission() chokepoint called in every server action and route handler; role + scope + resource-ownership checks; tests assert 403s
Session OIDC/httpOnly cookies, SameSite=Lax, 30-day sliding; magic-link tokens single-use, 15 min
CSRF Server actions + Origin check on all mutations; no state-changing GETs
PII Phone numbers and emails are the sensitive set: masked in lists (•••-1234), never in logs, never in AI prompts, export restricted to admin with audit row
Minors A is_minor flag requires a guardian contact; guardian receives all notifications; youth cannot be scheduled past 21:00
Uploads Presigned, type-sniffed server-side, size-capped, served from a separate origin/path, Content-Disposition: attachment for non-images
Rate limits 5 magic links/hour/email, 10 AI calls/day/user, 100 API req/min/IP, 20 login attempts/hour
Secrets Server env only; rotated quarterly; Twilio/Postmark webhooks signature-verified
Backups D1 Time Travel (30 days) + weekly JSON export to R2 (90-day retention) with a documented restore drill; user-facing exports are separate from backups and never contain secrets
Access review Quarterly listing of admins; offboarding checklist (deactivate + revoke ICS token + remove certs)

11. API surface

Server actions are the primary interface; these routes exist for webhooks, feeds and the PWA.

Method Route Purpose Auth
GET / Volunteer home: my next assignment session
GET /schedule Month/week view session
GET /availability Blackout manager session
GET /training, /training/[slug], /training/[slug]/[lesson] Library + lesson viewer session
GET/POST /respond Magic-link confirm/decline signed token
POST /api/swaps Create swap request session
GET /api/calendar/[userId]/[token].ics ICS feed opaque token
POST /api/uploads/sign, /complete R2 uploads session
POST /api/webhooks/postmark Delivery events signature
POST /api/webhooks/twilio Delivery + STOP/HELP signature
POST /api/webhooks/llm n/a — reserved —
GET /api/health Liveness + last cron heartbeat none
POST /api/events Create/update an event (rich-text brief) admin / coordinator
POST /api/events/[id]/positions Set required positions + headcount admin
GET /api/events/[id]/brief Phone-friendly brief (shareable, token) signed token
POST /api/uploads/multipart Create/complete/abort a multipart upload batch (phase 2) media.raw_upload
GET /api/media/[id]/download 15-min signed URL + media_downloads row (phase 2) media.raw_download
GET /api/events/[id]/manifest.csv Original-filename manifest for editors (phase 2) media.raw_download
POST /api/exports Create an export job (dataset, format, filters) admin / scoped coordinator
GET /api/exports/[id] Job status + short-lived signed download URL owner or admin
GET /api/exports/[id]/file Streams the rendered file from R2 signed URL
POST /api/ai/* AI features, rate-limited session

Admin screens are RSC pages under /admin/*; no public JSON API for scheduling in v1 (avoids building a second auth surface).

Response conventions: server actions return { ok: true, data } or { ok: false, error: { code, message, fieldErrors } }; user-facing copy is plain language, not error codes.


12. Operations

  • Logs: structured JSON (requestId, userId, action, durationMs), 30-day retention. No PII.
  • Sentry: errors with release tag; alert to admin email on > 5 errors/min.
  • Cron heartbeats: admin dashboard banner if the notification worker hasn't run in 20 minutes. This is the single highest-value monitor — silent reminder failures are the failure mode that hurts most.
  • Notification health panel: last 24h counts by status/channel, failed rows with error, one-click retry, "send test to me".
  • Runbook: rotate Twilio/Postmark keys; replay failed notifications; regenerate instances after an RRULE change; restore from export; deactivate a volunteer mid-week.
  • Uptime: target 99.9% during 06:00–13:00 Sunday local; acceptable degradation = read-only schedule (static cache) if the DB is unreachable.

12.5 Export & reporting subsystem

Three formats, one dataset. The rendered file is always a projection of a single authorized query — never a second implementation of the business rules.

12.5.1 Pipeline

flowchart LR
  U[Admin: Export ▾] --> V{Scope + limits<br/>90 days / 25k rows}
  V -->|ok| J[(export_jobs queued)]
  V -->|too big| X[Rejected with guidance]
  J --> W[Render worker<br/>same query as the UI]
  W --> C[CSV writer]
  W --> X1[ExcelJS workbook]
  W --> P[@react-pdf/renderer]
  C --> R2[(R2 artifact)]
  X1 --> R2
  P --> R2
  R2 -->|signed URL, 15 min| D[Download or emailed link]
  R2 -.->|7 days| G[Expiry job deletes object]
  • Under 5,000 rows renders inline in the request (target < 1.5 s) and streams the file back; no job row download step.
  • Above that, the row is queued and rendered by the same cron worker that drains notifications (registered as a second job in the same tick), writing to R2 and marking ready, plus an email with a 7-day link.
  • Scheduled reports reuse the identical code path with requested_by = system: Monday coverage PDF to coordinators, first-of-month leadership pack, quarterly serving-hours report.

12.5.2 Rendering constraints on Workers

Problem Decision
No headless Chromium available HTML→PDF via a browser is out. @react-pdf/renderer builds PDFs from React primitives in pure JS and runs in workerd; the printable booth sheet also works client-side through window.print() with a dedicated print stylesheet, which is higher fidelity for one-offs
ExcelJS expects Node streams/Buffers Runs on the Node runtime (or browser). On Workers, either enable nodejs_compat and build the workbook into a Uint8Array, or generate XLSX client-side from an authorized JSON payload. Prefer the server when a file must be emailed or scheduled
Fonts for PDF Embed two fonts (one sans, one mono) as binary modules at build time; never fetch fonts at request time
Memory ceiling Stream CSV row-by-row; for XLSX use WorkbookWriter streaming. Hard cap 25k rows, 10 MB
Time limits 30 s CPU per request → anything bigger is a background job, never an inline render

12.5.3 Format contracts

CSV — RFC 4180, UTF-8 with BOM, CRLF, header row, ISO-8601 dates. Writer rules:

// Prevent spreadsheet formula injection. A name like =HYPERLINK("http://evil","x")
// must never execute in the director's Excel.
const DANGEROUS = /^[=+\-@\t\r]/;
const cell = (v: string) => (DANGEROUS.test(v) ? `'${v}` : v);

Quoting is unconditional for any field containing ,, ", \n or \r; quotes doubled.

XLSX — sheets per logical table; a Read me sheet first containing dataset name, filters applied, timestamp, requester, row counts and a column glossary; frozen header row and autofilter on every sheet; real date/time cells with a yyyy-mm-dd hh:mm number format; column widths tuned per column; one row per slot (not merged cells) so filters and pivots work; no macros, no external links, no hidden sheets.

PDF — Letter, 0.5" margins, embedded fonts, tagged text where the renderer supports it. Header: church name + logo + report title. Footer: Generated {timestamp} by {name} · Page {n} of {m} · Confidential — contains volunteer contact information (that last part only when phones are included). Tables repeat their header row across pages and never split a row. Booth-sheet variant: 11pt minimum, one page per service, colour-coded role chips, run-sheet short link, blank notes strip at the bottom.

12.5.4 Security & retention

  • Authorization happens on the dataset query, using the same requirePermission chokepoint and scope_role_id filter as the on-screen list. A coordinator with Audio scope gets Audio rows only — verified by test, not by hiding the button.
  • Phone numbers and emails are only included when the requester is an admin and ticks "include phone numbers"; the default is masked (•••-4567).
  • Filenames carry no PII: media-team_schedule_2027-01-10_2027-02-07_v1.xlsx.
  • Every artifact lives in a private R2 prefix, served only via a signed URL (15-minute TTL) or an authenticated stream; bucket-level public access is off.
  • export_jobs.params_json is the audit receipt (export.generated in audit_log): dataset, format, filters, row count, requester, timestamp. This is what answers "who took the volunteer phone list out?"
  • Artifacts expire in 7 days via a nightly job; the job row remains for 12 months for audit, with r2_key nulled on expiry.
  • No export content is ever written to application logs, Sentry, or AI prompts.

12.5.5 Limits

Limit Value Behaviour
Date range 90 days Rejected in the dialog with a suggested narrower range
Rows 25,000 Rejected; suggest CSV by month
File size 10 MB Rejected; suggest narrowing columns
Concurrent jobs per user 3 Queued, not rejected
Artifact lifetime 7 days Nightly cleanup
Rate 30 exports/hour/user 429 with a plain message

13. Performance & accessibility budgets

Metric Target
LCP on Moto G / 4G < 2.0 s
Volunteer "my schedule" TTFB < 300 ms (edge cached, revalidated on assignment change)
Schedule grid interaction < 100 ms optimistic drag response
Bundle (volunteer route) < 180 KB gzip (TipTap only loads on authoring routes)
Accessibility WCAG 2.1 AA; full keyboard scheduling; screen-reader labels on the grid; 44px touch targets; contrast ≥ 4.5:1
Offline PWA shell + last-known schedule cached; confirmations queue and replay

14. Cost model (monthly, steady state)

Item Estimate
Cloudflare Workers Paid + D1 + R2 $5 + < $2 storage/ops
R2 event media (phase 2): ~20 events × 40 GB ~$12 storage; $0 egress
Postmark (~1,000 emails) $15 (10k tier)
Twilio number + ~600 SMS ~$2 + ~$6 all-in with carrier fees
10DLC brand + campaign (amortized) ~$2–4
LLM (assistive features, capped) $3–10
Domain / misc ~$2
Total ≈ $35–40/month

At ~120 volunteers and 3 roles × 2 services × 4.3 weeks ≈ 2,600 slots/year, cost per covered slot is well under $0.25. Keep the SMS volume honest: only Friday + day-of + urgent, not every event.


15. Risks

Risk Impact Mitigation
10DLC registration delay (1–3 weeks) SMS launches late Start registration in week 1; email covers the Friday reminder meanwhile
Volunteers ignore another app Adoption fails Magic links, ICS feed, 3-tap confirm, SMS as the primary nudge; pilot with one service first
Email lands in spam Reminders missed Dedicated subdomain, DKIM/DMARC, warm-up, Postmark monitoring; SMS fallback
Timezone/DST bugs Wrong reminder day UTC storage + IANA tz + tests across both 2027 DST transitions
Single-admin bus factor Schedule stalls Two admins, documented runbook, coordinator role scoped to one service
Scope creep into full ChMS Never ships Explicit non-goals, phased backlog, CSV import as the integration answer
Rich text abuse (paste from Word) Broken layout Schema normalization, preview, revision history
PII exposure Trust damage Masking, no PII in logs/AI, admin-only exports with audit
RAW library growth outruns storage budget Cost creep, slow galleries Hard retention default 90 days, per-event size shown before upload, admin sees a storage counter
Photos of minors published without consent Serious pastoral and legal problem media_release_required blocks publishing; per-image reject; publishing is a deliberate admin action
Photographer never uploads Event silently incomplete deliverable_due flag + reminder; dashboard shows events stuck in covered

16. Decision log

# Decision Rationale Reversible
ADR-1 Next.js on Workers, SQL via Drizzle One deploy target, typed schema, cheap Yes (Postgres swap)
ADR-2 Outbox table instead of a queue service Transactional with the schedule change, inspectable by admins Yes
ADR-3 Offset-based notification rules "Friday before" generalizes to any service time No (core model)
ADR-4 TipTap + JSON as source of truth Sanitizable, versionable, multi-renderer Hard
ADR-5 Deterministic auto-fill; LLM explains only Explainability and reliability beat cleverness Yes
ADR-6 Publish-per-week gate Volunteers only see committed schedules; no notification storms No
ADR-7 Magic-link responses Removes login friction at the exact moment of contact Yes
ADR-8 YouTube/Vimeo for training video in v1 No transcoding pipeline; church wifi friendly Yes