Compare commits

..
Author SHA1 Message Date
joshuaandClaude Opus 5.5 eb4e44a735 Release events@2.3.0, contracts@1.3.0 and agent@1.0.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 22:23:11 +02:00
joshua 3bcde954fb Merge branch 'feat/totp' 2026-11-17 22:23:11 +02:00
joshua 328b2ce11a Merge branch 'feat/agent-1.0' 2026-11-17 22:15:31 +02:00
joshuaandClaude Opus 5.5 f4955bee9d Fetch tags with --force: the release tag on the server wins
Found in the VM test: when a tag had moved (a re-tagged release), a church's
fetch refused it and every later deploy failed its checks. The deploy checks
out the tag the Hub asked for, so the remote's tag is the one to trust.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdni7EfytGYqQTprME
2026-11-17 19:08:53 +02:00
joshuaandClaude Opus 5.5 570f2dda5a PM2 runs under its own systemd unit, never as a child of the agent
Found in the VM test: a site's PM2 daemon started from the agent's install
job belonged to the agent's service, so stopping or updating the agent took
down every site it had installed. Before any PM2 command as a site user,
the scripts now make sure that user's daemon runs under pm2-<user> (moving
one that runs elsewhere, keeping its process list). The agent's stats no
longer start an empty daemon by asking one that isn't running. Uninstall
stops the unit before removing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:40:12 +02:00
joshuaandClaude Opus 5.5 19709c2c75 frpc: restart it the first time the admin lines are added (a reload can't work yet)
Found in the VM test: the new install's tunnels never opened, because
frpc only reads admin_addr when it starts, so the first reload failed.
That first time (and whenever a reload fails), frpc is restarted under
systemd and the report says so; later changes reload as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:48:28 +02:00
joshuaandClaude Opus 5.5 f3f6dc8f7a Events env template: HUB_PUBLIC_KEY in the defaults, for a Hub other than production
Without it a site installed from a staging Hub (or the VM test's Hub)
can't check its licence. Blank in production, so it isn't written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:35:50 +02:00
joshuaandClaude Opus 5.5 0d7e6b52d2 agent install / self-update: install the root's build tools too
Found in the VM test: npm ci -w packages/contracts -w apps/agent skipped
the monorepo root's devDependencies (tsup, typescript), so the agent
couldn't be built. --include-workspace-root brings them in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:35:13 +02:00
joshuaandClaude Opus 5.5 2479cbbd0a deploy: after a failed migration, mark it rolled back so later deploys aren't blocked
Found in the VM test: Prisma records a failed migration and then refuses
every later migrate deploy (P3009), so one broken release left a church
unable to update. On rollback, failed migrations the previous release
doesn't have are marked rolled back (prisma migrate resolve); the
backup still has the database as it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:30:18 +02:00
joshuaandClaude Opus 5.5 c8d46ef2d9 adopt: apply the release's new migrations in the switch-over (events@2.2.0 has one)
Found in the VM test: adopt refused events@2.2.0 because the AI tokens
migration made it into the release, and adopt only moved installs with
no migrations. Now the migrations the release has and the old install
doesn't run after the backup, while neither version runs; a failure
starts the old install again. They're recorded (EVENTS_ADOPT_MIGRATIONS)
so adopt --undo can still go back past them (they only add columns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 15:15:09 +02:00
joshuaandClaude Opus 5.5 ee65ff358c Events 2.3.0 (phase 1c): two-factor with an authenticator app, recovery codes
- TOTP (RFC 6238) next to email and WhatsApp: QR code and key to set up,
  the app's first code confirms it, a code can't be used twice, nothing
  is sent. The secret is stored encrypted.
- 10 single-use recovery codes whenever two-factor is turned on, shown
  once; accepted at sign-in in place of any code; a new set on request.
- Admins see each account's method; Reset 2FA clears the app and codes.
- Profile & Security, sign-in and Users pages; API types; 10 new tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:55:22 +02:00
joshuaandClaude Opus 5.5 b207d17db8 WIP Events 2.3.0: TOTP util, schema and migration for authenticator-app 2FA
Not wired up yet: twoFactor.js, login, enable/confirm/disable, recovery
codes endpoints and the frontend still to do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:37:52 +02:00
joshuaandClaude Opus 5.5 92869d2683 crosscode: envtpl as .cjs (Node CommonJS for the root lint)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:26:00 +02:00
joshuaandClaude Opus 5.5 d61b3e5978 Docs: agent 1.0 built (changes while building), handover, changelogs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:19:41 +02:00
joshuaandClaude Opus 5.5 1eeaf4d94f Agent 1.0.0: polls the Hub for signed jobs, runs crosscode, sends reports and stats
apps/agent (docs/AGENT-1.0-PLAN.md §3-4, §10): listens on nothing; checks
every job (pinned Hub key, server, time window, replays for 90 days,
type per mode, strict arguments) before running crosscode with an
argument array; opens the sealed config into a root-only file only for
the job; redacts log lines; keeps unsent reports in an outbox; encrypts
exports before upload; check-ports on the central server (read-only);
self-update with automatic revert. One bundled dist/cli.js, a systemd
unit and the install script that joins a server with a one-time token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:58:08 +02:00
joshuaandClaude Opus 5.5 e9e9b5a97f crosscode: --json reports, --config, env templates, frpc tunnels, restart/export/uninstall/purge
- Every command takes --json (crosscode.script-report/1 on stdout, the
  log on stderr) and --config (the .env values by layer, from the agent).
- .env files come from the release's env.template.json (lib/envtpl.js):
  written whole on install; on deploy only new variables are appended,
  and a new required one with no value stops the deploy at the checks.
- install --frp: Hub-given ports, a marked frpc.ini block (backup,
  frpc verify, reload; [common] admin lines added once), no nginx.
  A database on another server via DB_ADMIN_URL. Refuses an existing
  database or role. Everything the run made is removed if it fails.
- restart, export (crosscode.church-export/1 ZIP), uninstall (final
  backup, uploads and .env kept 30 days) and purge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:50:19 +02:00
joshuaandClaude Opus 5.5 350ab9f4e8 Events: env template, church export, register with HUB_LICENCE_KEY
- apps/events/env.template.json (crosscode.env-template/1): every .env
  variable with its layer (server, defaults, install, generated).
- scripts/export-church.ts writes crosscode.church-export/1 (export-only
  references, no internal ids or secrets) for crosscode export.
- Installs made from the Hub register by themselves on first start when
  HUB_LICENCE_KEY is set (retries while the Hub is unreachable).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:06:01 +02:00
joshuaandClaude Opus 5.5 90a98a4306 contracts 1.3.0: agent jobs, reports, stats, join/poll, env templates, church export
Jobs of fixed types with strict argument schemas, signed by the Hub with
Ed25519 over canonical JSON. Agent requests signed with the server's
Ed25519 key. Config sealed to the server's X25519 key (X25519 + HKDF +
AES-256-GCM; Node has no XSalsa20). Exports encrypted with a key that
only travels in the download link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:02:24 +02:00
joshuaandClaude Opus 5.5 53e15fdd69 Release events@2.2.0 and contracts@1.2.0
Events 2.2.0: the move into the monorepo and the crosscode script, plus
AI use in tokens and the backend under /api. Contracts 1.2.0: token
fields on the AI status. Agent phase 1d moves to contracts 1.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:38:09 +02:00
joshua a0ab22fbf3 Merge branch 'feat/api-prefix'
# Conflicts:
#	apps/events/CHANGELOG.md
2026-11-17 11:31:34 +02:00
joshua 52099c310d Merge branch 'feat/ai-tokens' 2026-11-17 11:31:06 +02:00
joshuaandClaude Opus 5.5 61a64cf339 Docs: AI tokens and /api under Events 2.3.0 in the roadmap and handover
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:12:01 +02:00
joshuaandClaude Opus 5.5 afaccf79d1 Events: everything the backend serves is under /api (for 2.3.0)
The site and its API can share one address with one proxy rule (/api to
the backend, everything else to the frontend). Status page at /api (/
redirects), /api/health, /api/docs/v2, /api/uploads. Stored upload
paths stay /uploads/… and are given out as /api/uploads/…. Old paths
still answer (/health, /uploads) or redirect (/docs, /docs/v2), so
two-address sites keep working. DEPLOYMENT.md and the agent plan
describe the single rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 11:11:46 +02:00
joshuaandClaude Opus 5.5 38ebce24ab Events: AI use in tokens, not rand (for 2.3.0); contracts: token fields on the AI status
Site settings → AI, the usage tables and the 80% email show input/output
tokens and the percentage; the rand amounts from the Hub are dropped on
arrival. AiCall stores each call's tokens (migration ai_tokens). v2
/ai/status and /ai/usage carry tokens instead of cents. Needs Hub 2.0.1
for the token figures; older Hubs show the percentage only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:59:36 +02:00
joshua e8853cf0c8 Merge branch 'feat/crosscode-script' 2026-11-12 19:27:57 +02:00
joshuaandClaude Opus 5.5 c442fe0d42 crosscode script: deploy, status, install, adopt (Events 2.2.0, plan §4-5)
One script for installing, updating and moving church installs, replacing
hope-events' scripts/deploy.sh and install.sh:

- deploy <church> [events] / --every-church, with --version, --main, --check
  and --allow-local-changes: checks every product first (files changed by
  hand, Node, release requirements from WHATS-NEW.md headings), then each
  product in order with backup, checkout, install, migrate, build, PM2 reload
  and a /health version check; a failure rolls that product back and stops.
- status [<church>]: checked-out and latest release, /health, and the old
  folder kept after adopt.
- install <church> --products events --domain <address>: a new church under
  /var/www/sites/<church>, writing church.env.
- adopt <church> --events-dir <old> builds the monorepo checkout next to the
  running install and switches PM2 over; adopt --undo goes back to it.

Product hooks live in scripts/products/events.sh. shellcheck (lint:scripts)
and 47 bats tests (test:scripts) are part of npm run check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:17:06 +02:00
joshua f174285711 Merge branch 'move/events' (Cross Events into apps/events) 2026-11-12 17:34:45 +02:00
joshuaandClaude Opus 5.5 47f346b0a6 Events move: workspaces and one root lockfile, versions pinned to 2.1.1
- Workspaces: apps/events/backend and apps/events/frontend; apps/events itself
  excluded (npm doesn't install node_modules for a workspace nested in another).
  Its dev tools (Playwright, axe, concurrently) move to the root.
- Packages renamed @crosscode/events, -backend, -frontend; nested lockfiles removed.
- allowScripts moved to the root (npm ignores it in workspaces), same choices.
- Direct dependencies that moved pinned to their 2.1.1 versions in root overrides;
  @sentry/node pinned only inside the backend.
- Same results as 2.1.1: 52 suites / 711 backend tests, typecheck, both builds.
- EVENTS-2.2-PLAN §2 and HANDOVER updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:34:45 +02:00
joshuaandClaude Opus 5.5 1ef1af64b7 Events move: root lint ignores apps/events, drop doc pointer stubs, fix handover links
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:38:35 +02:00
joshuaandClaude Opus 5.5 243021c81e Cross Events moves into the monorepo (apps/events), from hope-events e6c9670
History rewritten under apps/events/ (git filter-branch). Commit hashes changed;
the originals stay in the archived hope-events repo. Old v… tags are not brought over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:37:48 +02:00
joshua a800d448f4 Merge branch 'docs/server-agent' 2026-11-12 16:26:51 +02:00
joshuaandClaude Opus 5.5 c398e8071d Docs: server agent and Hub 2.1.0 plan (phase 1d, decisions 27-37)
Agent on every server runs installs, scheduled/emergency updates and
uninstalls on signed jobs from the Hub, polls only (no listening port),
appends to frpc.ini in marked blocks, builds .env files from per-server
config in the Hub. FastPanel and DNS stay manual (emailed instructions).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:26:51 +02:00
joshua 934f7a9eed Merge branch 'docs/adopt-decisions' 2026-11-05 13:51:09 +02:00
joshuaandClaude Opus 5.5 4e58c5c07e Docs: adopt builds next to the install and switches over; adopt --undo (decisions 25-26)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 13:51:08 +02:00
joshua 0ab0ca9fa0 Merge branch 'docs/moved-to-platform' 2026-11-05 09:48:33 +02:00
joshuaandClaude Opus 5.5 897b27cc42 Docs: roadmap v3 and Hub protocol moved to crosscode-platform/docs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:31 +02:00
joshua 8032a5d9e2 Merge branch 'docs/roadmap-and-events-move' 2026-11-05 09:48:28 +02:00
joshuaandClaude Opus 5.5 633d65eec9 Docs: roadmap and Hub protocol move here; handover and Events 2.2.0 plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:48:27 +02:00
joshuaandClaude Opus 5.5 2bb5580e10 Merge branch 'docs/hub-2-released'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:10:34 +02:00
joshuaandClaude Opus 5.5 015495ab56 Docs: Hub 2.0.0 released (phase 1); hub-protocol.md with protocol v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:10:33 +02:00
joshuaandClaude Opus 5.5 9dc2fa8af4 Merge branch 'docs/sites-folder'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:54:05 +02:00
joshuaandClaude Opus 5.5 4cbfcddfbd Docs: church installs under /var/www/sites/<church>/<product>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:54:05 +02:00
joshuaandClaude Opus 5.5 fbf9d3553d Merge branch 'docs/roadmap-monorepo-deploy'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:48:36 +02:00
joshuaandClaude Opus 5.5 e78534328e Docs: monorepo move, crosscode deploy script, releases per product
ROADMAP-v3 decisions 21-24: Cross Events moves into crosscode-platform
(2.2.0); one crosscode script deploys Accounts plus the products named;
the Hub tracks releases per product with requirements; the Hub gets the
contracts as a committed file, not from the package registry. Cross Events
versions in the build order move up by one. HANDOVER updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:48:36 +02:00
joshuaandClaude Opus 5.5 6bb80f75d1 Roadmap v3: four Website templates; SEO for every public site
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:04:13 +02:00
joshuaandClaude Opus 5.5 5ab755cc63 Roadmap v3: Hub protocol v2 (today's is v1), event-feed schema, enum rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:42 +02:00
joshuaandClaude Opus 5.5 6a5aa29494 Roadmap v3: sign-in returns to where you came from; crosscode-site per phase
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:31:29 +02:00
joshuaandClaude Opus 5.5 ca7a14bcf8 Roadmap v3: decisions, pricing and authenticator-app 2FA; handover updated
One install of each product per customer; House of Prayer booking
defaults; email and WhatsApp only (no push); Accounts hidden from
members. Pricing: Website R99 with 5 GB plus storage add-on, App from
R99, address once per church (own domain, crosscode.co.za address R10,
domain included R25). Authenticator app 2FA as Cross Events 2.2.0.
Handover now points at ROADMAP-v3; nothing left open in ROADMAP-v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:48:23 +02:00
joshuaandClaude Opus 5.5 545880fdc7 Roadmap v3: Accounts, Church Website, Church App, Cross Code Hub
Plan for selling three products from one Hub: shared users through a
per-church Accounts service, event sync in any direction on one shared
format (crosscode.event/1), PM2 installs per product per church.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:14:24 +02:00
joshua 01f9a3eeac Merge branch 'fix/feedback-background-send' 2026-11-03 14:11:44 +02:00
joshuaandClaude Opus 5.5 53797e4447 Feedback Send now and Remind run in the background (2.1.1)
- Send now and Remind answer straight away with who they're going to and
  queue the feedback-send task; the Feedback page refreshes to show progress.
- One-off background tasks (enqueueTask in src/jobs/index.js): pg-boss with
  retries, or in-process after the response when the queue is off.
- Reminders are claimed with the 24-hour rule, so two tasks at once never
  remind the same person twice.
- Tests: tests/tasks.test.js, tests/feedbackPage.test.ts, e2e/feedback.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:11:44 +02:00
joshuaandClaude Opus 5.5 a345b3c824 Handover: Hub 1.7.0 bills on the income bands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:42:46 +02:00
joshua aca6f7728d Merge branch 'feat/feedback-page' 2026-11-03 13:03:05 +02:00
joshuaandClaude Opus 5.5 9dda0d1851 Feedback page: results, responses, who hasn't answered, reminders (2.1.0)
- Supervisor -> Feedback (supervisors and admins, campus-scoped): every
  event's form with answered of asked, response rate, average rating and
  last reminder; per event the results per question (with the AI summary),
  each response, and on named forms who was asked and who has answered.
- Remind those who haven't answered (or one person on a named form): a
  fresh link, plus the form to anyone eligible who hasn't had it; nobody gets
  the form or a reminder twice within 24 hours. The 3-day job is unchanged.
- Anonymous forms show no names and no list of who has answered.
- FeedbackInvite.reminderCount (migration 20261103120000_feedback_reminders);
  access log action feedback_responses; help page; dashboard and Ctrl+K links.
- Roadmap: the AI helpers on the privacy pages are dropped; 2.1.0 is the
  feedback page.
- Tests: tests/feedbackPage.test.ts, e2e/feedback.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:03:05 +02:00
joshua c018772ded Merge branch 'feat/billing-income-bands' 2026-11-03 12:18:01 +02:00
joshuaandClaude Opus 5.5 aabf3cbe07 Billing income bands up to R10m, 12-month event income in the heartbeat (2.0.2)
- Heartbeat income bands widened from "over R100 000" to 14 bands up to
  "over R10 000 000"; every licence-tier edge is a band edge (tested).
- New income.eventIncome12m: last 12 months' event income without donations,
  sponsorships or donation legs, which the licence tier is billed on.
- Fix: donation legs were counted twice in the heartbeat income bands.
- Protocol doc, roadmap pricing decisions, changelog, what's new, handover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:18:01 +02:00
joshua cebfe52be5 Merge branch 'fix/ai-summary-all-reports' 2026-11-02 18:42:27 +02:00
joshuaandClaude Opus 5.5 40fa8b2dba Summarise this report on every report (2.0.1)
The eight reports that list people get the AI summary too, sent as
anonymised totals built on the screen (aiReportData.ts): no names,
contact details, notes or comments; consent and medical only as counts.
The server refuses personal columns on those reports and logs each
summary in the access log (ai_report; sensitive for consent and medical).

Roadmap §18: 2.0.1, then crosscode.co.za, then 2.1.0 (AI helpers on the
Consent log and Access log).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:42:27 +02:00
joshua 8d7269a1e2 Merge branch 'docs/marketing-site' 2026-11-02 18:01:25 +02:00
joshuaandClaude Opus 5.5 d33284b1ec Docs: marketing site decisions (crosscode.co.za)
crosscode.co.za as Cross Code's main site with a Cross Events page;
church website and app as "coming later"; repo joshua/crosscode-site;
own server; no prices yet; contact form to info@crosscode.co.za;
privacy notice and terms of use; no cookies. Content from Joshua later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:01:23 +02:00
joshua 391baa0d67 Merge branch 'release/2.0' (2.0.0) 2026-11-02 17:49:34 +02:00
joshuaandClaude Opus 5.5 b58123adab Release 2.0.0
AI helpers, API v1 removed, Argon2id passwords, React Compiler lint
rules back to errors, migration guide. Docs (HANDOVER, roadmap) mark
2.0.0 as released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:49:30 +02:00
joshuaandClaude Opus 5.5 abd2c36e97 WIP 2.0.0: React Compiler lint rules back to errors; docs
- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

e2e 102/102 (PayFast sandbox skipped); production build passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 17:45:25 +02:00
joshuaandClaude Opus 5.5 3f59164ab2 WIP 2.0.0: v1 removed; Argon2id passwords; node-fetch gone
- /api (v1) answers 410 API_V1_REMOVED, except provider webhooks
  (/api/webhooks/*, /api/whatsapp/webhook) and links in sent messages
  (308s, one-click POST). 43 v1 route files and deprecation.ts removed;
  /docs redirects to /docs/v2; API_DOCUMENTATION.md points there.
- Read-only and impersonation lists name v2 paths only. The campus
  scope route test now runs over v2 routes (v2CampusScope.test.ts).
- Passwords hashed with Argon2id (@node-rs/argon2); bcrypt hashes still
  sign in and are re-hashed at the next sign-in.
- e2e on /api/v2 only (v2() helper); Playwright waits on /api/v2.
- MIGRATING-TO-2.md with the full v1 -> v2 table.
- Two documented response shapes corrected.

Backend 690 tests and e2e 102/102 (PayFast sandbox skipped) pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:35:06 +02:00
joshua 57b3c41067 Merge branch 'main' into release/2.0 (1.52.3)
# Conflicts:
#	CHANGELOG.md
2026-11-02 15:15:08 +02:00
joshua fa48e3bb24 Merge branch 'fix/read-only-v2' 2026-11-02 15:14:50 +02:00
joshuaandClaude Opus 5.5 edd3ee6e76 Fix: licence read-only mode blocks the v2 routes too (1.52.3)
The read-only guard only listed v1 paths, and every screen has used
/api/v2 since 1.51.15, so a suspended, revoked or unlicensed site could
still create events, take registrations and start payments. The v2
successors of each blocked v1 route are blocked now; a test checks each
blocked v2 path exists in the OpenAPI document.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:14:50 +02:00
joshua b41dbab667 Merge branch 'main' into release/2.0 (1.52.2)
# Conflicts:
#	CHANGELOG.md
#	docs/HANDOVER.md
2026-11-02 14:13:12 +02:00
joshua 76f17ab0e9 Merge branch 'fix/deploy-local-changes' 2026-11-02 14:04:27 +02:00
joshuaandClaude Opus 5.5 50639088b2 Deploy: stop first when files in the install were changed by hand (1.52.2)
A setup wizard run on one server added files to backend/src that the
backend build picked up, so the deploy failed part-way and rolled back.
deploy.sh now lists files git reports as changed or added (ignored files
and the PM2 config don't count) and stops before backing up or checking
out. --check runs only that; ALLOW_LOCAL_CHANGES=1 deploys anyway; the
script also runs from a copy outside the install (the folder you're in).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:03:12 +02:00
joshua d53eba29ea Merge branch 'main' into release/2.0 (1.52.0, 1.52.1)
# Conflicts:
#	CHANGELOG.md
#	docs/HANDOVER.md
2026-11-02 13:45:28 +02:00
joshua 72edb4da30 Merge branch 'docs/openapi-complete' 2026-11-02 13:27:05 +02:00
joshuaandClaude Opus 5.5 d74af96f1d Docs: every v2 route documents its body, answer and parameters (1.52.1)
Most routes answered by a v1 handler showed an empty body and
`data: unknown` in /docs/v2. Each now documents what its handler reads
and answers, and every path and query parameter is described.

- `documented: { body?, response? }` on v1Route/defineRoute, with shared
  shapes in src/v2/docs.ts. Documentation only: not enforced, so nothing
  that works can start failing; outside production a body or answer that
  doesn't fit is logged ("doesn't match its documented schema").
- QUERY_HELP / PATH_HELP describe common parameters; empty bodies say
  "No body needed".
- Declared the funnel's eventIds and webhook deliveries' status/before.
- tests/v2Docs.test.ts keeps the document complete; frontend types
  regenerated, three call sites' types tightened (no payload change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 13:26:15 +02:00
joshua 6e64e64bff Merge branch 'fix/door-tickets-corrections' 2026-11-02 12:24:00 +02:00
joshuaandClaude Opus 5.5 db214a1013 Fix: door and manual registrations get their tickets; admin Corrections (1.52.0)
On events with a required attendee form, tickets waited for the forms, but
At the door and Manual registration never asked for them: payment was
recorded and nobody could be checked in.

- The form pops up at the door and in Manual registration; "Fill in later"
  (any staff) issues the tickets once paid and sends the payer a link
  (Registration.formWaivedAt, POST /api/v2/registrations/{id}/form-later).
- One form per person on picked-session bookings; a required form with no
  questions no longer holds tickets back; every caller asks the ticket
  generator (formsOutstanding).
- Kiosk asks for the forms the server says are missing; headings show as text.
- Admin Corrections page and /api/v2/corrections: issue missing tickets,
  pay later (ticketsReleasedAt), make it free (complimentaryDiscount),
  check in or undo after the event.
- Migration 20261102120000_corrections; unit and e2e tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:01:10 +02:00
joshuaandClaude Opus 5.5 ba121118ea WIP 2.0.0: message drafts use event placeholders only with an event
Found by the first real eval run (Sonnet 5.5 through the local Hub,
19/19 checks): without an event the drafts still used {{event.title}}
and added an event-details block. The instructions now offer those
placeholders only when an event is given; the eval checks for it, and
adds up split themes when counting feedback. Route tests for the five
AI helpers in v2.test.ts; the eval script loads backend/.env.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMeckMWrKPfc1MMyMJF
2026-10-30 18:25:57 +02:00
joshuaandClaude Opus 5.5 4924d1ed76 WIP 2.0.0: AI buttons on the five screens, eval set, privacy notice
Describe your event (new event), Improve/Shorter/Fix mistakes (event
description, banner, email and WhatsApp boxes), Draft with AI (email and
WhatsApp attendees), Summarise this report (people-free reports) and
Summarise feedback (per event). Built-in privacy notice text for AI
(2.0.0 entry in BUILT_IN_UPDATES). npm run ai:eval runs the trial cases
through the Hub with fact checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMeckMWrKPfc1MMyMJF
2026-10-30 18:19:46 +02:00
joshuaandClaude Opus 5.5 d4f54f2cc8 WIP 2.0.0: the five AI helpers' API
src/ai/helpers.ts: instructions, schemas and inputs for draft event,
summarise report (people-free reports only), draft message, summarise
feedback (no names, access-logged) and improve text. Contact details
are swapped for placeholders before sending and restored after; every
helper gets today's date; weekday clashes and break-even over capacity
are checked in code. v2 routes /ai/draft-event and friends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:38:16 +02:00
joshuaandClaude Opus 5.5 cbdc7ad10a Docs: Sonnet 5.5 for every AI helper (Hub 1.6.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:25:16 +02:00
joshuaandClaude Opus 5.5 20d53b79f1 Docs: 2.0 progress, marketing site plan, AI tested
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:58:48 +02:00
joshuaandClaude Opus 5.5 dbec47aae3 WIP 2.0.0: AI helper plumbing (status, usage, Site settings -> AI)
The site calls AI through the Hub (protocol 3b, Hub 1.6.0): src/ai
works out whether the AI buttons show (licence token first, then the
Hub, cached a minute), runs a helper call with per-helper switches and
a per-person daily limit, logs AiCall rows, and emails admins at 80%.
v2 /ai/status, /ai/usage, /ai/settings; useAiStatus, AiButton, AiTab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:25:36 +02:00
joshua 838a6b3c3d Merge branch 'docs/handover-roadmap-tidy' 2026-10-30 09:00:49 +02:00
joshuaandClaude Opus 5.5 0f915d345d Docs: bring HANDOVER and ROADMAP-v2 up to date after 1.51.17
HANDOVER: version table in order with 1.51.4/1.51.5 added; Next up
renumbered with the 2.0 clean-ups (lint rules, node-fetch, password
hashing); event picker points at fetchManagedEvents; stale lines fixed.
ROADMAP: status rewritten as a dated summary; section 14 marks what's
done and that CI was removed; Haiku prices flagged to check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:00:49 +02:00
joshua 792b5b291b Merge branch 'fix/forgot-password-enumeration' 2026-10-30 08:51:41 +02:00
joshuaandClaude Opus 5.5 839a56ddbd Security: forgot password and sign-in don't reveal accounts (1.51.17)
- Forgot password answers the same (message, status, timing) for every email; the reset link
  is made and sent after the answer. Rate-limited like sign-in.
- Sign-in with an unknown email is refused exactly like a wrong password, after a password
  check against a stand-in hash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:51:41 +02:00
joshuaandClaude Opus 5.5 0e4a251c9a WIP 1.51.17: forgot password and sign-in don't reveal accounts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:47:04 +02:00
joshua 558c433b8f Merge branch 'feat/api-v2-webhooks-links' 2026-10-30 08:34:41 +02:00
joshuaandClaude Opus 5.5 82e8f9cd62 Incoming webhooks and message links on API v2 (1.51.16)
- /api/v2/webhooks/{yoco,payfast,whatsapp}; new provider set-ups use them, the v1 addresses
  keep working with the same handlers.
- Calendar and one-click unsubscribe links point at v2; old links answer 308 (a one-click POST
  to the old address is still handled there).
- /api/webhooks/whatsapp runs the real WhatsApp handler (was an empty stub).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:34:41 +02:00
joshuaandClaude Opus 5.5 d31ffdce0c WIP 1.51.16: incoming webhooks and message links on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:30:05 +02:00
joshua 20d43b63c2 Merge branch 'feat/api-v2-privacy-admin' 2026-10-30 08:23:49 +02:00
joshuaandClaude Opus 5.5 044a113af5 Privacy and admin on API v2 (1.51.15)
- v2: my privacy, unsubscribe links, the privacy admin, audit log, jobs, impersonation,
  settings and first-run set-up, the Hub, outbound webhooks, backups, Yoco/PayFast settings.
- Every call the app makes is now on /api/v2 (incoming webhooks and message links: 1.51.16).
- v1Route handles res.download/sendFile; impersonation end/log allowed on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:23:49 +02:00
joshuaandClaude Opus 5.5 68c6559136 WIP 1.51.15: privacy and admin on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:19:24 +02:00
joshua 7b20ffbe08 Merge branch 'feat/api-v2-people-messaging' 2026-10-30 08:11:48 +02:00
joshuaandClaude Opus 5.5 23ff8dd31f People and messaging on API v2 (1.51.14)
- v2: the rest of accounts (code resend, password reset, activation, sessions, closing,
  activity, two-step sign-in; admin users), /event-listing, messaging and broadcasts,
  scheduled messages, automations, WhatsApp connection, banner, saved filters, dashboards,
  stats, analytics, report files.
- GET /me carries the session fields the app needs (prompts, campus scope, 2FA required).
- defineRoute refuses duplicate routes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:11:48 +02:00
joshuaandClaude Opus 5.5 3b5ba6b9c6 WIP 1.51.14: GET /me carries the session fields the app needs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-30 08:07:06 +02:00
joshuaandClaude Opus 5.5 ba351be029 WIP 1.51.14: people and messaging on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 17:02:26 +02:00
joshua 1bc236ddd1 Merge branch 'feat/api-v2-kids-volunteers' 2026-10-29 16:50:11 +02:00
joshuaandClaude Opus 5.5 165e4d14f0 Kids check-in and volunteers on API v2 (1.51.13)
- v2: my family, kids set-up and the check-in desk (board, families, check-in/out, codes,
  offline), volunteering (roles, sign-up, swaps, self check-in) and rosters (roles, assigning,
  manual check-in, hours).
- Frontend: kids desk, rooms, family, serving and rosters on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:50:10 +02:00
joshuaandClaude Opus 5.5 d1452c6645 WIP 1.51.13: kids check-in and volunteers on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:46:40 +02:00
joshua 11a90e572e Merge branch 'feat/api-v2-tickets-attendance' 2026-10-29 16:40:28 +02:00
joshuaandClaude Opus 5.5 237cd89f6a Tickets and attendance on API v2 (1.51.12)
- v2: tickets (mine, one, send, issue, transfers, scans), scan locks, the attendance register
  and its export, certificates, allocations.
- Frontend: apiV2Raw() for string-path helpers; every ticket/attendance screen on v2.
- v1Route can run a v1 router by URL; an unanswered chain is a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 16:40:27 +02:00
joshuaandClaude Opus 5.5 fe6034f10f WIP 1.51.12: tickets, scan locks, attendance, allocations on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:52:31 +02:00
joshua 91fa42ba5f Merge branch 'feat/api-v2-money' 2026-10-29 13:47:49 +02:00
joshuaandClaude Opus 5.5 50205c03f0 Money on API v2 (1.51.11)
- v2: payments, refunds, donations, payment links and the pay page, providers, cash-ups,
  provider transactions, waitlist, sponsorship, consent, form responses, feedback.
- src/v2/viaV1.ts: v1Route() answers a v2 route with the v1 handler in-process.
- /docs/v2 opens collapsed with a filter (Swagger UI stopped drawing past ~130 endpoints).
- Frontend: every money screen on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:47:49 +02:00
joshuaandClaude Opus 5.5 fb36e9c8ac WIP 1.51.11: money on v2 via v1 handlers (viaV1 adapter)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:43:36 +02:00
joshua de08f057ad Merge branch 'feat/api-v2-registrations-staff' 2026-10-29 13:16:59 +02:00
joshuaandClaude Opus 5.5 a7a9382a93 Managing registrations on API v2 (1.51.10)
- v2: staff list (paged), event registrations, registration in full (+ /me), status, manual
  registration, bulk, items, invoice, coupon, attendees and form links, form drafts and responses.
- src/services/registrationAdmin.ts holds the rest of registrationController.js (now v1 wrappers).
- Frontend: fetchAllRegistrations(); every registration screen on v2.
- Roadmap: money gets its own release (1.51.11); webhooks and links move to 1.51.16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:16:59 +02:00
joshuaandClaude Opus 5.5 7eb6f99e97 WIP 1.51.10: registration management on v2 (routes, frontend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 13:04:31 +02:00
joshuaandClaude Opus 5.5 5a3bfa1100 WIP 1.51.10: registration management moved to src/services/registrationAdmin.ts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:57:02 +02:00
joshua 4fa0d831d8 Merge branch 'feat/api-v2-series-deals' 2026-10-29 12:39:28 +02:00
joshuaandClaude Opus 5.5 af43b72c04 Series, season passes, deals and campuses on API v2 (1.51.9)
- v2: series (+ page, compare, follow), season passes (+ buy, pay, mine), bundle deals
  (+ quote), coupon codes (+ check, redemptions), campuses (+ admin, enabled, order, audience).
- src/services/series.ts, deals.ts, campuses.ts; the five controllers are thin v1 wrappers.
- v2 errors carry a service's own code as `reason`.
- Frontend: apiV2Data() for screens with their own record types; these screens on v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:39:27 +02:00
joshuaandClaude Opus 5.5 684560119f WIP 1.51.9: frontend on v2 for series, passes, bundles, coupons, campuses
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:34:49 +02:00
joshuaandClaude Opus 5.5 0498ee1854 WIP 1.51.9: series, season passes, bundles, coupons and campuses on v2 (backend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:28:00 +02:00
joshua a387570098 Merge branch 'feat/api-v2-events-rest' 2026-10-29 12:18:29 +02:00
joshuaandClaude Opus 5.5 c1fc8628d3 The rest of event set-up on API v2 (1.51.8)
- v2: event in full, calendar file, alias, ticket options and variants, attachments
  (multipart), sections, planned costs, image uploads.
- src/services/eventDetails.ts and src/services/setup.ts; v1 uses them.
- v2 routes can send files (fileResponse) and take uploads (documented as multipart).
- Frontend: fetchEvent() everywhere, lib/eventSetup.ts for set-up calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:18:29 +02:00
joshuaandClaude Opus 5.5 d1927cd334 WIP 1.51.8: frontend on v2 for event detail, options, sections, attachments, costs, uploads
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:14:01 +02:00
joshuaandClaude Opus 5.5 96b9b8c23f WIP 1.51.8: sections, costs and uploads on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:08:03 +02:00
joshuaandClaude Opus 5.5 006c4db02f WIP 1.51.8: event detail, options, variants, attachments, calendar and alias on v2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 12:04:06 +02:00
joshua 4a7f75a8ec Merge branch 'feat/api-v2-events' 2026-10-29 11:57:08 +02:00
joshuaandClaude Opus 5.5 a564436f3b Setting events up on API v2, pg-boss 11 (1.51.7)
- v2: /events/manage, create, PATCH, deactivate, copy-from, notify-recipients.
- src/services/events.ts (from eventController.js, with the schedule helpers); v1 uses it.
- fetchManagedEvents() for every picker; the event wizard writes through v2.
- pg-boss 11 in its own schema (pgboss_v11); old pgboss schema left in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:57:08 +02:00
joshua 3e2895a9ce Merge branch 'feat/palette-excelts' 2026-10-29 11:16:38 +02:00
joshuaandClaude Opus 5.5 d74c37f5b3 Complete command palette, ExcelTS 10, roadmap: v2 for webhooks and sent links (1.51.6)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:14:19 +02:00
joshua fa9da3dc06 Merge branch 'chore/next16' 2026-10-29 11:00:31 +02:00
joshuaandClaude Opus 5.5 0044eec881 Next.js 16, React 19.3, ESLint 10 (1.51.5)
- Next 16 (Turbopack dev and build), React 19.3; tsconfig jsx react-jsx; images remotePatterns.
- ESLint 10 with eslint-config-next 16 flat configs; npm run lint = eslint src. React
  Compiler-era react-hooks rules set to warn (181 existing places) until screens move to v2.
- Removed the empty pass-through middleware.ts.
- e2e: wait for the palette to be ready before Ctrl+K on the staff dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 11:00:30 +02:00
joshua 2b8f39b4e7 Merge branch 'chore/dependencies' 2026-10-29 10:19:43 +02:00
joshuaandClaude Opus 5.5 81e6aeb7c2 Security and dependency updates, Node 24 for new installs (1.51.4)
- npm audit fixes: next 15.5.28 and @sentry/nextjs 10.78 (critical), zod 4.6.7, multer 2.5.0
  (high), nodemailer 10.3.0, fast-uri, ip-address (moderate). Minimum versions raised.
- cron-parser 5 (v4 unmaintained).
- install.sh installs Node 24 LTS; deploy.sh warns on Node < 22; DEPLOYMENT.md "Upgrading Node".
- Roadmap: every endpoint moves to v2 before 2.0 (1.51.5 - 1.51.11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 10:19:43 +02:00
joshua d5580cf9f0 Merge branch 'chore/roadmap-v1-decision' 2026-10-29 09:49:54 +02:00
joshuaandClaude Opus 5.5 a630b1ccc6 Roadmap: 2.0 retires only the v1 endpoints that have a v2 replacement
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:49:54 +02:00
joshua bee209faf2 Merge branch 'feat/api-v2-express5' 2026-10-29 09:46:24 +02:00
joshuaandClaude Opus 5.5 91047bcde2 Express 5, scanner on API v2, v1 deprecation headers (1.51.3)
- Express 5 (qs query parser and req.body = {} kept as in Express 4).
- Scanner and at-the-door check-in use /api/v2/checkin; look-up gives attendee, bookedBy,
  ticketOptionId.
- Shared middleware errors on /api/v2 rewritten to { error: { code, message, reason } };
  apiFetch treats reason like v1's code.
- Deprecation + Link: rel="successor-version" on v1 endpoints that have a v2 replacement.
- Roadmap: open question on how much of v1 to retire in 2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:46:24 +02:00
joshua 1b7adcf7fe Merge branch 'feat/api-v2-checkin-accounts' 2026-10-29 09:31:01 +02:00
joshuaandClaude Opus 5.5 6816e8bc67 API v2 accounts and check-in (1.51.2)
- v2: auth/signup, auth/login (+ code step, rate limited), PATCH /me; check-in look-up and
  scan returning an outcome for every normal result. Campus rule as v1.
- Sign up/login/2FA/profile moved to src/services/auth.ts; scan preview and scan to
  src/services/checkin.ts. v1 answers unchanged (ServiceError v1Status).
- Login, 2FA step, sign up and profile/password pages use v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:31:00 +02:00
joshua 440c43e530 Merge branch 'feat/api-v2-writes' 2026-10-29 09:09:09 +02:00
joshuaandClaude Opus 5.5 310684a563 API v2 registrations and payments (1.51.1)
- v2: register, get, cancel and checkout a registration (owner/admin only).
- Registration create/cancel moved to src/services/registrations.ts and online checkout to
  src/services/payments.ts; v1 controllers call the same services (ServiceError carries status).
- Typed frontend calls: npm run api:types writes openapi.json and schema.d.ts; apiV2() helper.
  Register page, Pay now and My Events cancel use v2; apiFetch reads v2 errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 09:09:09 +02:00
joshua 966fa256b6 Merge branch 'feat/api-v2-foundations' 2026-10-29 08:48:54 +02:00
joshuaandClaude Opus 5.5 6b3c55902e TypeScript backend and /api/v2 foundations (1.51.0)
- tsconfig (allowJs, strict .ts), npm run build -> dist/, typecheck, dev via tsx, ts-jest.
- src/index.js is now a launcher (dist build when it matches, else tsx); server moved to app.js.
- /api/v2: defineRoute with zod -> request validation, response stripping, OpenAPI 3.1 at
  /docs/v2; one error shape and one paged-list shape. First endpoints: events, event, me,
  my registrations.
- deploy.sh/install.sh build the backend; rollback to older releases skips the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:48:54 +02:00
joshua 7e736d8d41 Merge branch 'chore/roadmap-ai-markup' 2026-10-29 08:29:15 +02:00
joshuaandClaude Opus 5.5 ea0f0cc7ca Roadmap: AI buttons follow the cap, markup on AI usage
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:29:15 +02:00
joshua fbf8b6199c Merge branch 'feat/event-pickers-webhook-docs' 2026-10-29 08:23:09 +02:00
joshuaandClaude Opus 5.5 b6c16a7ec4 Searchable event picker and webhook guide (1.50.2)
- EventPicker replaces the plain event dropdowns on staff/supervisor pages and the kiosk:
  upcoming first, past behind "Show past events", search across all, keyboard support.
- Reports events list can be searched ("Select these N").
- Site settings -> Webhooks: "How webhooks work" guide with headers, signature checking
  (Node.js/PHP) and an example of every event type (EVENT_TYPES[].example, shape-tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 08:23:09 +02:00
joshua b5c1224b76 Merge branch 'feat/long-lists' 2026-10-29 06:53:54 +02:00
joshuaandClaude Opus 5.5 43bbdbc405 Pagination and search on long lists (1.50.1)
Audit log: search (person, target, IP), role filter, every action in the
filter, inclusive To date. Data requests: search and paging (was cut at
200). Webhook deliveries: status filter and Load older. Supervisor Payments
loads only what it needs (unpaid registrations, recent/today/donation
payments, a person's own for refunds) instead of everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
2026-10-29 06:53:54 +02:00
joshua b9a886fc52 Merge branch 'feat/accessibility' 2026-10-28 15:41:19 +02:00
joshuaandClaude Opus 5.5 9548efdb45 Accessibility pass, WCAG 2.2 AA (1.50.0)
Public pages, auth, registration, payment, My Events and the kiosk: skip
link, focus ring, labels tied to fields, named quantity buttons, announced
errors, ModalOverlay popups (focus trap, Escape, focus return), contrast
and underlined in-text links, reduced motion. Branding warns about a primary
colour too light for white text and offers a darker shade. axe-core and
keyboard checks in e2e/accessibility.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:41:19 +02:00
joshua eac21f3860 Merge branch 'chore/roadmap-no-afrikaans' 2026-10-28 15:02:22 +02:00
joshuaandClaude Opus 5.5 ed1feed59d Roadmap: languages (Afrikaans) removed from scope
The accessibility pass becomes 1.50.0 and the TypeScript backend /
OpenAPI / api v2 1.51.0. Section 10 is kept for reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:02:22 +02:00
joshua 2b78193b35 Merge branch 'feat/saved-filters' 2026-10-28 14:57:34 +02:00
joshuaandClaude Opus 5.5 0bfa86bd06 Saved filters on list pages (1.49.2)
Manage registrations, Users, Events and Reports: save the current
filters under a name, apply one with a click, star one as the default
for the page (not applied over a deep link). Per person, stored on the
server, removed when an account is anonymised. /api/saved-filters.
Migration 20261028180000_saved_filters. Completes roadmap section 9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:57:34 +02:00
joshua 0f099b71f4 Merge branch 'feat/bulk-actions' 2026-10-28 14:43:01 +02:00
joshuaandClaude Opus 5.5 7b00eb7c99 Bulk actions on registrations (1.49.1)
Manage registrations: tick registrations (or all shown) and message
them (email/WhatsApp event update), mark them paid (the balance, by
method), move them to another ticket (same tickets and QR codes,
repriced, places checked), put their people in a room or group, export
to Excel, or cancel. Each runs the same handlers as doing it one at a
time, with a result per registration. POST /api/registrations/bulk,
campus-checked per id. Migration 20261028170000_registrations_bulk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:43:00 +02:00
joshua 35e58592db Merge branch 'feat/dashboard-palette' 2026-10-28 14:17:23 +02:00
joshuaandClaude Opus 5.5 ac5581a6f9 Dashboard Today and Waiting for you; Ctrl+K command palette (1.49.0)
Staff, supervisor and admin dashboards start with what's on today
(checked in vs places, children in now, volunteers here; money in today
and this week for supervisors) and, for supervisors and admins, what's
waiting for someone (unpaid registrations, consent, waitlists, cover
requests, roster gaps; for admins cashups, reconciling, privacy
requests, failed webhooks), each linking to where it's dealt with.
Ctrl+K opens a palette of pages, settings, reports and actions for the
role, with search: events, payments by amount, people and
registrations (admins). All campus-scoped. Bulk actions and saved
filters follow as 1.49.1 and 1.49.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:17:22 +02:00
joshua ecb375ecf5 Merge branch 'feat/demo-seeds' 2026-10-28 14:02:56 +02:00
joshuaandClaude Opus 5.5 a4bdbf8412 Four demo seeds; fix set-demo wiping the admin (1.48.2)
npm run demo:small | demo:events | demo:ministry | demo:multicampus
(demo:list describes them; set-demo -- --profile=<name> in backend/).
New builders: courses with sessions, attendance and certificates, a
pick-your-days conference, kids church with families, rooms and live
check-ins, volunteer rosters, a series with followers and a season
pass, and three campuses with campus-limited staff.

set-demo had failed since 1.43.0: TRUNCATE CASCADE on Campus also
emptied User (homeCampusId), deleting the admin it keeps. Tables that
User points at are now emptied with DELETE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:02:56 +02:00
joshua 434784ecbc Merge branch 'fix/privacy-notice-draft' 2026-10-28 13:15:57 +02:00
joshuaandClaude Opus 5.5 adb6e11000 Privacy notice: built-in text up to date, review flow, acceptance (1.48.1)
The built-in notice now covers volunteer rosters, event series, season
passes, webhooks, how people agree to it, and the provider-notices
storage item. Sites with their own published version see what changed
in the editor (sections marked, use new text per section or all, add
missing sections, "Done - hide this"). Account activation asks for
agreement to the terms and notice; anyone who never accepted is asked
once after login. The cookie button shows above any cookie section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:15:57 +02:00
joshua aa79168660 Merge branch 'feat/webhooks' 2026-10-28 13:00:59 +02:00
joshuaandClaude Opus 5.5 51dc908630 Outbound webhooks (1.48.0)
Site settings -> Webhooks: admins add https endpoints and choose event
types (registration created/paid/cancelled, payment received/refunded,
ticket checked in, account created, event published). Events are
noticed by a Prisma client extension so every write path is covered,
re-checked before sending, and delivered as signed JSON
(X-CrossEvents-Signature, HMAC-SHA256) with retries, a 30-day delivery
log, Send test and Resend. Public https addresses only; each endpoint
is added to the operator register; kids and volunteer tickets are never
sent. New `webhooks` job. Migration 20261028160000_webhooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:00:59 +02:00
joshua 50e0cbe62d Merge branch 'fix/update-request-newer' 2026-10-28 12:16:56 +02:00
joshuaandClaude Opus 5.5 e66d39f6ff Fix: update request for an older version than the latest (1.47.4)
After asking for an update, a newer version coming out made the Licence
page claim the newer version was requested, with no way to ask for it.
Now it shows the version asked for, that a newer one is out, and "Ask
for X instead"; the banner shows again. Hub 1.5.0 moves the open request
on (`changed`); with an older Hub the site withdraws and asks again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:16:56 +02:00
joshua 8ec5dcefb9 Merge branch 'feat/season-pass' 2026-10-28 11:19:58 +02:00
joshuaandClaude Opus 5.5 cf7d00bdf3 Season passes (1.47.3)
A pass sells a ticket at each of several events in a series for one
price. Supervisors set passes up on the Event series page (events and
ticket per event; fixed once sold). Buying on the series page registers
the buyer at every event at once with one checkout (free passes give
tickets straight away; Pay now if online payment isn't possible). The
price is split over the events in proportion to their normal prices:
each registration line is priced at its share and the webhook records
one Payment per event, so cashups stay per event. Pass registrations
aren't repriced, take no coupons and can't be edited. Migration
20261028150000_season_pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:19:58 +02:00
joshua 24cd604b43 Merge branch 'feat/series-reports' 2026-10-28 10:57:04 +02:00
joshuaandClaude Opus 5.5 bc8021cde0 Series: year on year report (1.47.2)
New report (Reports -> Other, or "Compare" on the Event series page):
each event in a series side by side, oldest first - registrations,
tickets, income (dashboard definition), people checked in (average per
session on multi-session events) and attendance rate, with the change
from the event before. Exports like the other reports; campus-scoped
staff see only their campuses' events. GET /api/series/:id/compare.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:57:04 +02:00
joshua e221d83ff8 Merge branch 'feat/event-series' 2026-10-28 10:29:59 +02:00
joshuaandClaude Opus 5.5 164c74e5dd Event series (1.47.1)
Group separate events (Camp 2025, Camp 2026) on a series page at
/series/<slug> with upcoming and past events. Events join a series from
the event editor (copies keep it); a series can span campuses. Event
pages show "Part of ..." and "Next in this series". Signed-in people can
follow a series; the new `series` job emails followers once when a new
event in it goes live, as News & announcements (opted-in only, with
unsubscribe). Follows are in the data export and removed on
anonymising. Migration 20261028140000_event_series.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:29:59 +02:00
joshua 6bdf33b0e5 Merge branch 'feat/event-clone' 2026-10-28 10:01:18 +02:00
joshuaandClaude Opus 5.5 7148051896 Copy an event (1.47.0)
"Copy" on each event card opens the event editor filled in from that
event (campus, sessions, options, variants, early birds, sections, form,
recipients, feedback questions, certificates, reminders). "New start"
moves every date with it. Allocation groups and, for admins, planned
costs are copied by POST /api/events/:id/copy-from. Registrations,
coupons, attachments, kids check-in and volunteer roles are not copied.

Roadmap: event series and cloning ships as 1.47.0-1.47.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:01:17 +02:00
joshua ddf5290bbd Merge branch 'chore/whats-new-history' 2026-10-28 09:25:08 +02:00
joshuaandClaude Opus 5.5 1b5a967acf WHATS-NEW.md: church-facing notes for every version back to 1.0.0
The Hub reads this file from main (Hub 1.4.1), so these show on sites' Licence
page without a new release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:25:08 +02:00
joshua ae0458bf8f Merge branch 'chore/licence-updates' 2026-10-28 09:13:30 +02:00
joshuaandClaude Opus 5.5 443b73773d WHATS-NEW.md for churches; docs, changelog (1.46.2)
Client-facing release notes the Hub reads from git with the version tags, so
the latest version and its notes reach installs without touching the Hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:13:30 +02:00
joshuaandClaude Opus 5.5 a9baa3b127 Licence page: what's new, withdraw request, Not now, provider notices
- Site settings -> Licence shows the release notes for every newer version from
  the Hub; urgent (security/serious) updates are marked and can't be put off.
- Withdraw an update request (the provider is told through the Hub).
- "Not now" on the banner or Licence page hides update reminders until the
  next version.
- Notices from the provider show as a dashboard banner for site admins and
  supervisors, in their time window, and on the Licence page.
- New audit actions (migration), API docs, help, protocol doc, tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:54:35 +02:00
joshua 44af96c0ee Merge branch 'chore/remove-ci' 2026-10-28 08:15:45 +02:00
joshuaandClaude Opus 5.5 d6d7cdf56d Remove the Gitea CI workflow; docs, changelog (1.46.1)
There's no Actions runner (no machine that can run Docker), so every push
left a run stuck on "Waiting". Tests and lint are run by hand before a
release, and releases are deployed with scripts/deploy.sh on the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:15:44 +02:00
joshua 6bc7a7ec22 Merge branch 'feat/volunteer-rosters' 2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 e11c3caaab Volunteer rosters: docs, changelog (1.46.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 4166096706 Volunteer rosters: serving, roster and check-in pages, help, e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshuaandClaude Opus 5.5 a9f13a1b0a Volunteer rosters: roles, sign-ups, swaps, QR check-in, kids-room duty (backend)
Serving roles per event or session, sign-ups and assigning with an overlap
check, swaps that happen on accept (notify recipients emailed), QR and manual
check-in (kids-room roles start rostered duty), optional free volunteer ticket,
day-before reminder job, hours served, privacy hooks. The kids check-in and
volunteer tickets are left out of public event pages and public registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 03:59:52 +02:00
joshua a4fc2c0a88 Merge branch 'fix/legal-pages' 2026-10-28 01:09:51 +02:00
joshuaandClaude Opus 5.5 4515fde7aa Privacy notice and terms of use brought up to date (1.45.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMccH2LkkfYmsSLwPaq
2026-10-28 01:09:51 +02:00
joshua 2f550bc9e8 Merge branch 'feat/kids-check-in' 2026-10-28 01:01:09 +02:00
joshuaandClaude Opus 5.5 b6a0d49c5c Kids check-in: docs, changelog (1.45.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:01:08 +02:00
joshuaandClaude Opus 5.5 f9de6b84ee Kids check-in: desk, room screen, setup and parent pages, help, e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 01:01:08 +02:00
joshuaandClaude Opus 5.5 115dbb177f Kids check-in: families, pickup codes, rooms, check-in/out, offline sync (backend)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:46:41 +02:00
joshuaandClaude Opus 5.5 b28434f2e2 Roadmap: kids check-in fully digital, wallet passes removed from scope
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:29:10 +02:00
joshua 2ed9f4bbc1 Merge branch 'feat/campus-scoped-staff' 2026-10-27 22:59:00 +02:00
joshuaandClaude Opus 5.5 116a2ce4b4 Campus-scoped staff: help, docs, changelog (1.44.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:52:11 +02:00
joshuaandClaude Opus 5.5 193cf4267a Campus-scoped staff: frontend and e2e
Admin -> Users 'Limit to campuses'; staff campus pickers, reports, dashboards
and audience picker follow the scope (useMyCampuses); scoped people pick one
of their campuses for new events, and church-wide / other campuses' events
open read-only; 'You work with ...' note; warning before turning campuses off
while staff are limited. e2e: scanner refusal naming the campus, scoped
events list and read-only editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:50:03 +02:00
joshuaandClaude Opus 5.5 f8a567615c Campus-scoped staff: admins set limits; profile returns the scope
PUT /api/users/:id takes scopedCampusIds (supervisors/staff only, audited as
user_campus_scope_changed); GET returns scopedCampuses; the profile returns
campusScope (null when unscoped or campuses are off).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:40:32 +02:00
joshuaandClaude Opus 5.5 fd1cbb3239 Campus-scoped staff: every staff/supervisor route checked
Events, payments, registrations, scan locks and tickets marked; list
controllers filtered (registrations, payments, tickets, scans, stats,
coupons, scheduled messages, form responses, funnel). Owner-or-staff routes
check staff against the record's event (ownerOk). Scanner names the campus
of another campus's ticket. Route test passes; unit tests for the rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:37:42 +02:00
joshuaandClaude Opus 5.5 2ac2ec36e0 Campus-scoped staff: schema, campusScope helper, route test, first 79 routes
UserCampusScope relation and audit action; scopeEvent/scopeList/unscopedOnly/
campusIndependent/scopeBroadcast markers; tests/campusScopeRoutes.test.js
(still failing: events, payments, registrations, scan locks, tickets left).
Can't delete a campus that has scoped staff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:28:30 +02:00
joshuaandClaude Opus 5.5 ab4152960b Roadmap: 1.44.0 campus-scoped staff decisions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:17:32 +02:00
joshua eff2cb108b Merge branch 'feat/campuses' 2026-10-27 16:56:07 +02:00
joshuaandClaude Opus 5.5 7e8eeaa7a5 Campuses frontend, docs and e2e (1.43.0)
Site settings -> Campuses tab; campus picker in the event editor; campus
filter and badges on the events list, public events page (remembered,
starts on home campus) and reports/dashboards; /campus/<slug> pages and
sitemap; home campus on the profile; "Everyone at a campus" in email and
WhatsApp broadcasts. Help, FEATURES, SETTINGS, API docs, protocol doc
(campusCount), handover and roadmap updated; campuses seeded for e2e.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:45:43 +02:00
joshuaandClaude Opus 5.5 e138d4811d Campuses backend: model, admin/public API, events per campus, filters
- Campus model, Event.campusId (null = all campuses), User.homeCampusId,
  per-campus summary recipients; campuses_enabled setting (off by default)
- /api/campuses: public list and landing page, admin CRUD/order/archive,
  "everyone at campus X" audience (home campus + optional 12-month registrants)
- Events: campus on create/update (audited when moved), ?campus= on the
  public list (with church-wide events) and staff list; campus included
- Home campus on the profile; cleared when anonymising
- Overview stats ?campus= filter; campus summary recipients; campus on
  ticket PDFs; heartbeat reports the real campus setting
- Migration also adds hub_update_requested, missing since 1.42.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:23:33 +02:00
joshua 388ba26c33 Merge branch 'docs/multi-campus-plan' 2026-10-27 16:09:06 +02:00
joshuaandClaude Opus 5.5 07f5dc1969 Roadmap: split multi-campus into 1.43.0 campuses and 1.44.0 scoped staff
Records the decisions: scoped staff view and scan "All campuses" events but
can't edit them; "everyone at campus X" is home campus plus optional recent
registrants; campus landing pages in 1.43.0. Later phases move up by one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:09:04 +02:00
joshua 8e63639713 Merge branch 'fix/hub-public-key' 2026-10-27 14:28:49 +02:00
joshuaandClaude Opus 5.5 3bbaacbac1 Build the production Hub public key in (1.42.1)
PRODUCTION_PUBLIC_KEY is the key the production Hub serves at
/api/public-key, normalised to PEM, so installs no longer need
HUB_PUBLIC_KEY. Test covers the built-in key with the env var unset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:28:48 +02:00
joshua 4f40ef195f Merge branch 'docs/handover-roadmap' 2026-10-27 14:03:01 +02:00
joshuaandClaude Opus 5.5 c2034fd523 Handover and roadmap: Cross Events rename, Request update, versions moved up
1.41.3 and 1.42.0 / Hub 1.1.0 recorded; Multi-campus is now 1.43.0 and
later phases move up by one. Next steps: roll out update requests, build
the Hub public key in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:03:00 +02:00
joshua b33936eac0 Merge branch 'feat/request-update' 2026-10-27 13:55:06 +02:00
joshuaandClaude Opus 5.5 f37ec5c8ef Request update button instead of the deploy command (1.42.0)
Site settings -> Licence sends a signed update request to the Hub
(docs/hub-protocol.md 3a) instead of showing bash scripts/deploy.sh. Shows
"Update requested" until the site runs that version and hides the update
banner meanwhile. Audit-logged as hub_update_requested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:55:05 +02:00
joshua c777515025 Merge branch 'fix/cross-events-name' 2026-10-27 13:06:22 +02:00
joshuaandClaude Opus 5.5 a238e7fc22 Bump to 1.41.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:06:21 +02:00
joshuaandClaude Opus 5.5 0367e0ca6d Rename the product to Cross Events in UI text and docs
Display text only: storage keys, slugs, the encryption salt, the repo URL
and applied migrations keep their old names so existing installs keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:06:20 +02:00
joshua afe1e25cde Merge branch 'docs/frp-deployment' 2026-10-27 12:11:14 +02:00
joshuaandClaude Opus 5.5 3091783bdd Deployment guide for installs behind an frp tunnel
DEPLOYMENT.md: install with --no-ssl, switch URLs to https, TRUST_PROXY,
nginx and /etc/frp/frpc.ini for TLS on the VPS or in frpc (https2http),
checking visitor IPs, updates and troubleshooting. Linked from the README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:11:11 +02:00
joshua a47c04e4a4 Merge branch 'fix/job-times' 2026-10-27 11:06:54 +02:00
joshuaandClaude Opus 5.5 2ca48a3d06 Bump to 1.41.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:06:54 +02:00
joshuaandClaude Opus 5.5 e16c7ee09d Background jobs: show last-run times in the right time zone
pg-boss timestamps are timestamptz, and Prisma's pg adapter drops the offset in raw queries (10:55+02 came back as 10:55Z, shown as 12:55). Read them AT TIME ZONE 'UTC'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:06:51 +02:00
joshuaandClaude Opus 5.5 b2b126068a Document APP_TIMEZONE in .env.example and SETTINGS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:49:16 +02:00
joshua 95401baff7 Merge branch 'fix/licence-checks' 2026-10-27 10:45:41 +02:00
joshuaandClaude Opus 5.5 b495fb8d36 Bump to 1.41.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:45:40 +02:00
joshuaandClaude Opus 5.5 d1d6c90821 Licence: no licence is read-only, editing events blocked, heartbeat 30 s after start
- A site the Hub answers INSTALL_NOT_FOUND for drops its install and licence, so it
  no longer shows "Active" on the old token.
- Unlicensed is read-only like suspended; read-only also blocks editing events,
  options and variants. LICENCE_CHECK_DISABLED (ignored in production) for e2e.
- Heartbeat 30 s after the server starts and after a licence key is connected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 10:45:38 +02:00
joshua 1adf6e426d Merge branch 'feat/hub-client' 2026-10-26 13:03:53 +02:00
joshuaandClaude Opus 5.5 1fe9048aa2 Bump to 1.41.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 13:03:53 +02:00
joshuaandClaude Opus 5.5 51ad8f0bb0 Handover and roadmap: 1.41.0 and Hub 1.0.0; next steps to go live
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 13:03:50 +02:00
joshuaandClaude Opus 5.5 ff98a6fdfd Hub client: accept the public key pasted on one line; clearer error for a bad key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 12:58:44 +02:00
joshuaandClaude Opus 5.5 b67f40c2df Hub client: licence, heartbeat, read-only mode, /health, install script
- Connect with a licence key (/setup last screen, Site settings -> Licence)
- hub-heartbeat job every 15 min: version, health, totals (income as a band)
- Licence tokens verified with the Hub's public key; states active / grace
  (banner for site admins only) / suspended / revoked (read-only) /
  unlicensed; Hub keys kept out of the generic settings endpoints
- /health; "update available" for admins; scripts/install.sh
- docs/hub-protocol.md shared with the events-hub repo
- Unit tests (hub.test.js); docs

The production Hub public key (backend/src/hub/publicKey.js) must be set
before this is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-26 12:25:52 +02:00
joshua 9960c4e938 Merge branch 'docs/hub-repo' 2026-10-24 16:03:43 +02:00
joshuaandClaude Opus 5.5 e07d62a125 Roadmap: Hub repo is joshua/events-hub; grace banner for site admins only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-24 16:03:43 +02:00
joshua 7e4b657f41 Merge branch 'docs/ai-roadmap' 2026-10-24 14:36:25 +02:00
joshuaandClaude Opus 5.5 8146628627 Roadmap: AI helpers as the 2.0 headline, and later AI stages
- §15 AI helpers (2.0): one-button helpers (draft an event, summarise
  reports and feedback, draft messages, improve text) on Claude Haiku 5.5,
  called through the Hub, which holds the key, meters usage in rand and
  enforces a monthly cap per licence; admin usage view; POPIA notes
- §16 AI later stages (unversioned): Ask AI, help/navigation assistant,
  actions with confirmation, more helpers, long-term self-hosted AI
- Hub: AI cap as the first per-licence limit, AiUsage model; decisions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-24 14:36:25 +02:00
joshua 11528d2239 Merge branch 'feat/popia-retention' 2026-10-23 20:26:01 +02:00
joshuaandClaude Opus 5.5 9ac63e2406 Bump to 1.40.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 20:26:01 +02:00
joshuaandClaude Opus 5.5 6907bc3bd3 POPIA toolkit part 3: retention, breach register, readiness
- Retention policies (Admin -> Privacy -> Retention) applied by a nightly
  `retention` job: inactive accounts anonymised after 5 years with a
  30-day warning (on by default; never staff roles or people with an
  upcoming registration), form answers, login history, payer details in
  payment notifications, audit/access logs
- User.lastLoginAt (set on login, backfilled) and inactivityWarnedAt
- Breach register (SecurityBreach) with drafts for the people affected
  and the Information Regulator
- Readiness checklist with a score
- Children's/medical flag in the access log; {retention} placeholder in
  the privacy notice
- Unit tests (retention.test.js), e2e (privacy-retention.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 20:25:58 +02:00
joshua 7f5e31461a Merge branch 'feat/popia-admin-tools' 2026-10-23 19:11:23 +02:00
joshuaandClaude Opus 5.5 91cb7ddc6f Bump to 1.39.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 19:11:23 +02:00
joshuaandClaude Opus 5.5 34f9e96e4e POPIA toolkit part 2: privacy notice editor, operators, consent and access logs
- Admin -> Privacy (POPIA): edit the privacy notice (built-in text as the
  start, placeholders for org/IO/operators), drafts, preview, numbered
  versions; earlier versions readable on /legal/privacy?version=N
- "Significant change" versions are accepted once after login
  (NoticePrompt); sign-up records the version accepted
- Operator register (seeded with the services the app uses), listed in
  the notice via {operators}
- Consent log (news opt-ins, notice acceptances, parental consent) and
  access log (report exports, registers, certificates, group lists, form
  answers, consent/medical lists, backups, impersonation)
- Information Officer on the contact page
- Unit tests (privacyNotice.test.js), e2e (privacy-notice.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 19:11:20 +02:00
joshua 04be99b930 Merge branch 'feat/popia-privacy-centre' 2026-10-23 18:24:07 +02:00
joshuaandClaude Opus 5.5 3201397f2c Bump to 1.38.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 18:24:07 +02:00
joshuaandClaude Opus 5.5 18f35ceeb3 POPIA toolkit part 1: privacy page, unsubscribe, WhatsApp STOP, data requests
- Privacy page: news opt-in per channel with history, download my data
  (JSON + PDF), correction and deletion requests
- Bulk messages are an Event update or News & announcements; news only
  reaches people who opted in, with unsubscribe links, one-click
  List-Unsubscribe headers and "Reply STOP" on WhatsApp
- WhatsApp STOP via WAWP's message webhook, checked against a secret in
  the webhook URL
- Sign-up opt-in box; existing accounts kept opted in and asked once
- Admin -> Data requests with 30-day due dates and a daily reminder job
- Deleting an account is a request; anonymising now covers attendees,
  form answers, consent details, payer details in provider payloads, etc.
- Unit tests (privacy.test.js) and e2e (privacy.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
2026-10-23 18:13:47 +02:00
joshua f03b766b6e Merge branch 'fix/deploy-script' 2026-10-23 16:20:22 +02:00
joshuaandClaude Opus 5.5 8654473679 Deploy script: roll back once (not inside subshells); docs; bump to 1.37.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:20:22 +02:00
joshuaandClaude Opus 5.5 d0589de592 Deploy: latest main without a tag; per-install PM2 config out of git
- scripts/deploy.sh with no tag deploys the latest main (detached
  origin/main); with a tag, that release.
- ecosystem.config.js is no longer in git (now ecosystem.config.example.js;
  the deploy creates the install's copy from it once). The deploy keeps the
  install's copy safe across checkouts and rollbacks, including releases
  that still tracked it.
- The script runs from a temp copy, so checking out a new deploy.sh can't
  change it mid-run; set -E so failures in functions still roll back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:15:29 +02:00
joshua 39ba82d63b Merge branch 'fix/help-entities' 2026-10-23 15:57:46 +02:00
joshuaandClaude Opus 5.5 569824a75d Fix the production build: escape quotes in the Payments help text
The deploy's next build fails on react/no-unescaped-entities. Bump to
1.37.3; the handover now says to lint the whole frontend before tagging.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:57:46 +02:00
joshua eeb929d931 Merge branch 'feat/payment-status' 2026-10-23 15:28:31 +02:00
joshuaandClaude Opus 5.5 966cf5eb1c Bump to 1.37.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:28:31 +02:00
joshuaandClaude Opus 5.5 2064ba2e42 Payment status checks for notifications that never arrive
- src/payments/status.js: open checkouts, checkCheckouts and the
  payment-status job (every 15 min, checkouts 10 min - 3 days old). Found
  payments are settled exactly as their webhook would be (settlePayment,
  extracted from the webhook handler: amount check, record, emails).
- PayFast: signed API client (alphabetical signature, testing=true in
  sandbox), findPayments from the transaction history CSV matched on
  M Payment ID, and testConnection (signed /ping). Verified against a
  real sandbox account.
- Yoco documents no checkout lookup, so its checkouts are "can't check".
- Payments -> Reconcile: "Waiting for payment" with Check status /
  Check all; PayFast card: Test connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:28:28 +02:00
joshua 67730d3eb0 Merge branch 'feat/hide-pay-online' 2026-10-23 15:05:01 +02:00
joshuaandClaude Opus 5.5 4c58b9457a Bump to 1.37.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:05:01 +02:00
joshuaandClaude Opus 5.5 fcb7a00121 Hide "Pay online" when no provider is on or the amount is under R15
A shared useOnlinePayments hook (GET /api/payments/providers) gates the
registration success page, My Events (Make payment, Make donation), the
donate page, Sponsor a spot, the register form's donation box and the
supervisor Payment Link tab; they explain why where it helps.

Roadmap: SnapScan and Zapper dropped; later versions move up by two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:04:58 +02:00
joshua e91a538ced Merge branch 'feat/payfast' 2026-10-23 14:26:09 +02:00
joshuaandClaude Opus 5.5 c9785efa7e Bump to 1.37.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:26:09 +02:00
joshuaandClaude Opus 5.5 228719ef96 PayFast provider, Pay online page, amount checks on payments
- PayFast (custom integration): signed form (PHP-style encoding, checked
  against a real sandbox), ITN checks (signature over all posted fields,
  PayFast host, VALID from /eng/query/validate, amount vs checkout).
- ProviderCheckout records every checkout (amount, metadata, request);
  webhooks match payments to it and hold a different amount for review
  (ProviderTransaction.note).
- /pay/<id>: payers choose a provider when several are on, and the
  browser posts PayFast's form from there, so payment links work for
  every provider.
- Site settings → Payments: PayFast card (merchant ID/key, encrypted
  passphrase, sandbox/live) while PayFast is enabled.
- Payer-facing wording no longer names Yoco; legal pages name both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:25:49 +02:00
joshua 1fc5e44183 Merge branch 'feat/payment-providers' 2026-10-23 12:17:56 +02:00
joshuaandClaude Opus 5.5 15e9b6faf0 Bump to 1.36.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:17:56 +02:00
joshuaandClaude Opus 5.5 2116d727b9 Payment provider interface: Yoco behind it, Site settings → Payments
- src/payments: provider registry and PaymentProvider interface
  (createCheckout, verifyWebhook/parseWebhook, getTransaction, refund,
  listTransactions as capabilities), Yoco as the first provider. All four
  direct Yoco checkout calls go through payments.createCheckout.
- Webhook split into the provider part (signature, parsing) and shared
  processing; same URL (/api/webhooks/yoco), same behaviour.
- YocoTransaction renamed in place to ProviderTransaction (+ provider,
  unique per provider + externalId); Payment.provider added and
  backfilled to "yoco". Payment.method stays the wallet type so cashups
  are unchanged.
- Site settings → Payments: Enabled toggle and order per provider; Yoco's
  settings shown while it's enabled. R15 minimum for all online payments.
- New endpoint names (/api/payments/checkout, /api/provider-transactions);
  the old /yoco-checkout and /yoco-transactions paths still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:17:29 +02:00
joshua 608f3ccec5 Merge branch 'feat/session-gaps' 2026-10-23 11:38:43 +02:00
joshuaandClaude Opus 5.5 c0ed63a885 Bump to 1.35.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:38:43 +02:00
joshuaandClaude Opus 5.5 e368be4dce Session gaps: per-session waitlist, door session picker, all-sessions choice
- Waitlist per session: entries for pick-sessions tickets name a session;
  offers use that session's free places, never run past its start, and
  claim links tick it. Held offers count towards session capacity.
- At the door: the Select items pop-up has the session picker, with
  today's session preselected for new attendees.
- On pick-sessions events every ticket shows the session list straight
  away. "All sessions" tickets record the ticked sessions
  (RegistrationOption.sessionIds) at one price; scanning, attendance,
  certificates, reminders and capacity follow them.
- Fix: per-session stock limits weren't enforced (takenCount filtered
  WaitlistEntry by a sessionId column that didn't exist, and the error
  was swallowed), and the public event page lost its stock info.
- Fix: editing a door registration with picked sessions couldn't be saved.
- Fix: the offline-scanning service worker served /_next/static cache-first
  forever, so dev browsers that had opened the scanner ran stale code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:38:21 +02:00
joshua f6d19a596e Merge branch 'feat/pick-sessions' 2026-10-23 09:25:35 +02:00
joshuaandClaude Opus 5.5 c207ea417a Bump to 1.35.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:25:32 +02:00
joshuaandClaude Opus 5.5 abf9ca714d Pick sessions (frontend), roadmap and handover docs
Event wizard: how people book (whole course / pick sessions), capacity
per session and per-option session mode. Session picker on the public
registration page, Manual registration and the kiosk; at the door points
to Manual registration. Register, tickets and My Events handle picked
sessions. Adds docs/ROADMAP-v2.md and docs/HANDOVER.md so work can carry
on from another machine, and a pick-sessions e2e test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:25:21 +02:00
joshuaandClaude Opus 5.5 e22566bdeb Pick sessions (backend): book individual sessions with per-session capacity
Options on a multi-day event can be bought per session (one line and
ticket per session, priced per session, bookable until the session
starts). Sessions can have a capacity covering picked places and
whole-course tickets. Picked tickets only scan on their own session; the
register, certificates and reminders follow the sessions booked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:05:48 +02:00
joshua 6a8bc6f9dd Merge branch 'feat/ci-e2e-jobs' 2026-10-22 15:50:00 +02:00
joshuaandClaude Opus 5.5 dd6fe949b7 Bump to 1.34.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:49:56 +02:00
joshuaandClaude Opus 5.5 3f12efc1d4 Run background jobs on a pg-boss queue; add e2e tests, CI and deploy script
Timed jobs move from in-process timers to a job registry run by pg-boss:
once per schedule across processes, retries, run history, cron schedules
in the church timezone, and an admin Background jobs page with Run now.
Playwright end-to-end tests run against their own seeded database. A
Gitea Actions workflow runs backend tests, frontend checks and the e2e
tests, and deploys v* tags with scripts/deploy.sh once secrets are set.
Also fixes the at-the-door check-in count for multi-day tickets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:49:46 +02:00
joshua 60d522c3a9 Merge branch 'feat/multi-day-sessions' 2026-10-22 14:54:03 +02:00
joshuaandClaude Opus 5.5 0c10bda057 Bump to 1.33.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:53:59 +02:00
joshuaandClaude Opus 5.5 f4b358e5c8 Add multi-day events (frontend), attendance register and certificates
Event wizard: one date or multiple sessions with a repeat-pattern builder,
and a new Attendance step (late joining and pricing, check-in window,
session reminders, certificates with preview). Public pages show the
schedule and late prices; the scanner picks today's session; new
attendance register page, My Certificates, and a public verify page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:53:39 +02:00
joshuaandClaude Opus 5.5 623c85ccc5 Add multi-day event sessions (backend)
Events can run over several sessions: per-session check-in with a whole-day
or session-time window, late joining with pro-rata or fixed late pricing,
an attendance register (Excel/PDF), session reminders, and completion
certificates (four templates, public verify page).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:20:52 +02:00
joshua 65986342b3 Merge branch 'feat/early-bird-ribbon' 2026-10-22 13:48:29 +02:00
joshuaandClaude Opus 5.5 da461bbc96 Bump to 1.32.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:48:28 +02:00
joshuaandClaude Opus 5.5 bcd3de94b4 Show an early-bird ribbon on event cards
Event cards on the home page and events list get a diagonal "Early bird"
ribbon in the top-right corner while an early-bird tier is running and
registration is open. GET /api/events returns earlyBirdEndsAt per event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:48:22 +02:00
joshua 49c379a13e Merge branch 'feat/google-site-verification' 2026-10-22 11:43:01 +02:00
joshuaandClaude Opus 5.5 896d533736 Bump to 1.31.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:43:00 +02:00
joshuaandClaude Opus 5.5 0ae5afabd4 Add Google Search Console verification setting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:42:56 +02:00
joshuaandClaude Opus 5.5 6fb1866f41 Merge branch 'feat/seo-and-traffic-sources'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:17 +02:00
joshuaandClaude Opus 5.5 92903e35d8 Bump to 1.31.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:15 +02:00
joshuaandClaude Opus 5.5 866b340a4e Add event structured data, canonical URLs and referrer-based traffic sources
- Event pages emit schema.org Event JSON-LD (dates, venue, image,
  organizer, ZAR offers, sold-out status) for Google event results.
- Event pages, the events list and home page set a canonical URL so
  tagged and alias links don't split rankings.
- Funnel tracking falls back to the referring site (Facebook, Instagram,
  Google, ...) and fbclid/gclid when a link has no utm_source/src.
- Share and Save QR on the event page tag their links as share / qr.
- getServerSettings moves to lib/serverSettings.ts for reuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:26:02 +02:00
joshuaandClaude Opus 5.5 2dff048d12 Merge branch 'feat/unified-ticket-design'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:24 +02:00
joshuaandClaude Opus 5.5 c4c18140ed Bump to 1.30.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:21 +02:00
joshuaandClaude Opus 5.5 6c555525c7 Use the dashboard ticket design for all tickets
The emailed/WhatsApp ticket PDF and the staff and at-the-door print
views now match the user dashboard's printed tickets: rounded cards with
a light border and soft shadow. Printing goes through a shared helper in
lib/ticketPrint.ts, which also escapes names in the print HTML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:59:07 +02:00
joshuaandClaude Opus 5.5 b2a7996e6d Merge branch 'feat/registration-donation'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:29:17 +02:00
joshuaandClaude Opus 5.5 a6387ba79b Bump to 1.30.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:29:11 +02:00
joshuaandClaude Opus 5.5 eadd9a8329 Add optional donation to registration; fix soldOutLines server crash
The register form now offers a "Donation amount" (suggested amounts,
custom, or none) under the ticket options. The donation is added to the
Yoco checkout as its own line and the webhook records it as a separate
donation payment linked to the registration payment.

Move soldOutLines() out of the "use client" JoinWaitlistButton module
into lib/waitlist.ts so the server-rendered event page can call it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:27:47 +02:00
joshuaandClaude Opus 5.5 0aabc03fe6 Bump to 1.29.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:17 +02:00
joshuaandClaude Opus 5.5 88f3014750 Merge branch 'feat/coupons-redesign'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:16 +02:00
joshuaandClaude Opus 5.5 ebd3e1f951 Redesign the Coupon codes page to match Bundle deals
Cards instead of the table, phone-friendly sheets for the form and the uses list,
inactive codes hidden by default, and the events picker shows upcoming events only
(with search and a Show past events option).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:36:16 +02:00
joshuaandClaude Opus 5.5 c98545b5e4 Bump to 1.29.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 3bc9704769 Merge branch 'feat/bundle-types'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 3369794097 Add bundle types: pick any, buy X get Y free, group discount
Bundles get a kind: exact (as before), mix (any setSize of the qualifying tickets for
a set price), free (cheapest freeCount in each set free) and group (setSize or more
qualifying tickets at a per-ticket price or % off, applied once). The supervisor page
has a type picker, buyers see a one-line description of each deal, and the Complete
bundle cards handle every type. Demo: Family Fun Day adds a Lunch for four deal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:21:05 +02:00
joshuaandClaude Opus 5.5 44d18cbdd6 Bump to 1.28.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:03:22 +02:00
joshuaandClaude Opus 5.5 454868a6bf Fix the bundle edit form's ticket rows
The quantity input had both w-full and w-16; w-full won, filling the row and pushing
the ticket picker off the side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 16:03:21 +02:00
joshuaandClaude Opus 5.5 f84d57a5b4 Bump to 1.28.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:56:04 +02:00
joshuaandClaude Opus 5.5 5805a65d3b Redesign the Bundle deals page
Upcoming events only by default (with a Show past events option), bundles as cards
instead of a table, and a mobile-friendly edit form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:56:03 +02:00
joshuaandClaude Opus 5.5 0368b7ee86 Add bundle deals to manual registration
Lists the event's deals and shows the Complete bundle / + cards, as at the door and
on the kiosk. Part of 1.28.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:32:17 +02:00
joshuaandClaude Opus 5.5 a7954837f0 Bump to 1.28.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:49 +02:00
joshuaandClaude Opus 5.5 2c2acc49e4 Merge branch 'feat/bundles-door-kiosk'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:48 +02:00
joshuaandClaude Opus 5.5 a513f893d0 Add bundle deals to at the door and the kiosk
Both list the event's deals and show the Complete bundle / + cards from the register
form. At the door gets the standard Back to dashboard link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:22:48 +02:00
joshuaandClaude Opus 5.5 125c2e7f53 Bump to 1.28.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 981056a045 Merge branch 'feat/bundle-deals'
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 268781d610 Add bundle deals
Sell a set of tickets together for one price (e.g. 5 Adult + 3 Child for R500).
Bundles apply automatically, as many times as a registration's tickets allow, and
only when cheaper than the prices actually charged. Coupons come off afterwards.

- EventBundle/EventBundleItem/RegistrationBundle models and Registration.bundleDiscount
- Supervisor "Bundle deals" page, quote endpoint, bundle lines on invoices,
  receipts, emails, WhatsApp and Yoco checkout, Discounts report rows
- Register form shows started bundles with "Complete bundle" and "+" buttons
- Demo: Family Fun Day sells a Family deal bundle instead of the Family pass ticket

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:14:53 +02:00
joshuaandClaude Opus 5.5 2a8e8c7c11 Bump to 1.27.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:39:48 +02:00
joshua 988b23ec73 Merge branch 'chore/demo-history' 2026-10-21 13:39:47 +02:00
joshuaandClaude Opus 5.5 9bf2fb594c Add ten completed events to the demo data
set-demo now also stages ten past events with door sales, staff cash
counts, check-ins, refunds, donations and feedback. Their cashups run
through the real cashup code after the insert and cover every path:
quick close, full settlements (card fees, deposit fee, shortfall, cash
on hand, an unaccounted amount), close-reopen-close, and pending EFT
money received later or still outstanding. One recent event is left
open with the cash counted for a live demo. Funnel sessions older than
90 days are rolled up into daily totals, as the app does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:39:47 +02:00
joshuaandClaude Opus 5.5 f0313cd346 Bump to 1.27.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:29:29 +02:00
joshua 8270fa2cc3 Merge branch 'feat/cashup-settlement' 2026-10-21 13:29:28 +02:00
joshuaandClaude Opus 5.5 6725005c86 Take cash deposit fees out of the counted cash
A bank charge on a cash deposit comes out of cash that was counted and
banked, so cash on hand is now the count less what reached the bank and
any bank-charge write-off. Before, a deposit fee showed as money "more
than expected".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:29:17 +02:00
joshuaandClaude Opus 5.5 7eb3744ec5 Add cashup settlement and back links to the changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:19 +02:00
joshuaandClaude Opus 5.5 1d8f5616c8 Settle cashups: where the money ended up
A full cashup now records, per payment method, how much of the expected
takings is in the bank, still on hand (cash) or pending (on the card
report or with a POP), and writes off what was lost to card fees, bank
charges or a shortfall. Whatever is left is shown as unaccounted; closing
with an unaccounted amount is allowed after a warning.

Pending money can be marked received or written off after the event is
closed, without reopening it. Reopening starts the next cashup from the
last one. Write-offs come off net profit and show as "Bank & card
charges" in the cashup, finance and profit reports.

The reports page also moves to the shared back link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:04 +02:00
joshuaandClaude Opus 5.5 724424246c Use one back link style across the dashboards
Every dashboard page now uses the shared BackLink, the small
"← Back to dashboard" link above the page title that the Waitlist page
already had, instead of a mix of grey Back buttons in different places.
Pages that had no way back (site settings, profile, donate, manual
registration) get one too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:04 +02:00
joshuaandClaude Opus 5.5 fc9e6e1277 Bump to 1.26.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:23:51 +02:00
joshua 056a1ba4af Merge branch 'chore/demo-data' 2026-10-21 12:21:03 +02:00
joshuaandClaude Opus 5.5 f341cc1d06 Add set-demo script for staging demo data
npm run set-demo wipes the database, keeping the site settings and the
admin account, and stages six upcoming events with registrations,
payments, tickets, a waitlist, camp cabins, coupons, costs and funnel
stats for showing the platform to other churches. Documented in
backend/DEMO_DATA.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:21:03 +02:00
joshuaandClaude Opus 5.5 c6628e8a80 Merge branch 'chore/frontend-lint'
Includes chore/deps-security-prisma7 (Prisma 7 upgrade and npm audit fixes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:16:38 +02:00
joshuaandClaude Opus 5.5 2c12c42c3f Bump to 1.26.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:16:38 +02:00
joshuaandClaude Opus 5.5 22e0edca38 Add frontend lint cleanup to the changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:11:49 +02:00
joshuaandClaude Opus 5.5 6caf6794fb Type the reports page and turn lint back on in builds
ReportsV2 gets typed API responses (funnel, feedback summary, coupon
redemptions, cashup audit, consent) and derived rows. Master-order
quantities move into a per-row map, so an option name can no longer
overwrite a fixed column. Consent row types move to src/types. Removes
unused export helpers and state.

With the frontend now at zero lint errors and warnings, next build runs
ESLint again (eslint.ignoreDuringBuilds is gone).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 8360a78026 Type the at-the-door page and share pricing helpers
Each door panel and modal gets typed props; unused setError/setInfo/
onCreated props are dropped. The current early-bird price helpers move
to src/lib/pricing.ts (shared with manual registration), dead fallbacks
for a legacy registration 'options' field are removed, and the refund
history now shows a refund's reason (stored in its status field) instead
of a 'reason' field that never exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 5ee1880339 Type payments and user dashboard pages
Moves the duplicated registration-option pricing helper into
src/lib/pricing.ts and drops an unused users list from payments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 d03a5f1493 Type supervisor forms, manual registration and events pages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 f2728892b4 Type registrations, email and WhatsApp messaging pages
Adds typed payloads and results for the email/WhatsApp attendee and
broadcast endpoints. The WhatsApp page's messageDirty flag becomes a ref
(it only gated the template effect), and a no-op branch in the email
template effect is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 b21e7857d0 Type more frontend pages and fix their hook dependencies
Cashup, users, profile, consent, allocations, event options, forms,
event tickets, ticket scanning and manual registration now use real
types. Data loaders are wrapped in useCallback and listed as effect
dependencies. Also adds shared Attendee, Section and form response
types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 dc4d2fff41 Add shared API types and type the smaller frontend pages
Expand src/types with User, Event, EventOption, Registration, Payment,
Ticket, paginated results and dashboard stats, modelled on the Prisma
schema. apiFetch now defaults to unknown instead of any. Dashboard
loaders are wrapped in useCallback so their effects can list them as
dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:01 +02:00
joshuaandClaude Opus 5.5 5024ab7241 Type caught errors as unknown in the frontend
Replace `catch (e: any)` with `catch (e)` and read the message through a
new errorMessage() helper. ApiError.data gets a real type, and
useDismissingState's setter keeps one identity across renders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:00 +02:00
joshuaandClaude Opus 5.5 9e8244bb71 Fix frontend lint: links, unused code, quotes, img elements
- Internal links use next/link instead of <a> (no full page reload).
- Remove dead code: RegisterForm's unreachable Yoco checkout branch, the
  unused AttendeeForms on the registration success page, unused Geist
  fonts, and assorted unused variables and catch bindings.
- Escape quotes in JSX text; replace @ts-ignore in apiFetch with a cast.
- Keep the intentional raw <img> elements (data URLs, runtime API host)
  with a documented lint exception; the event editor uses ApiImage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:00 +02:00
joshuaandClaude Opus 5.5 700b220906 Upgrade to Prisma 7 and clear npm audit advisories
- Prisma 5.22 -> 7.10 using the @prisma/adapter-pg driver adapter; the
  datasource URL moves to backend/prisma.config.js. All clients are built
  in src/config/db.js, and index.js reuses the shared client.
- Backend: patch follow-redirects, drop nodemon for `node --watch`, and use
  js-yaml 4 for the Jest coverage loader. npm audit reports 0.
- Frontend: override postcss-selector-parser to 7.1.7 (Tailwind 3 output
  is unchanged). braces has no patched release and stays, build/lint only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 09:58:11 +02:00
joshua 789f59760b Merge branch 'fix/mobile-cookie-banner' 2026-10-20 12:47:41 +02:00
joshuaandClaude Opus 5.5 114ba6af6e Bump to 1.25.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:47:36 +02:00
joshuaandClaude Opus 5.5 5ad0a3d8e3 Lift cookie banner and help button above mobile bottom nav
The cookie consent banner was fixed at bottom-0 under the z-50 BottomNav, so
on mobile it was hidden. It now sits above the nav (h-16 + safe-area) and
publishes its height as --cookie-banner-h, which HelpFab adds to its offset
so the banner no longer covers the help button either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:47:13 +02:00
joshua 9ab446e409 Merge branch 'feat/yoco-settings' 2026-10-20 10:28:57 +02:00
joshuaandClaude Opus 5.5 f263f418b7 Bump to 1.25.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:53 +02:00
joshuaandClaude Opus 5.5 3ee3667886 Store Yoco secrets in the database; add Yoco settings tab
The Yoco secret key and webhook secret now live in AppSetting (AES-256-GCM
encrypted), with .env as a fallback. A new Site Settings → Yoco tab shows
them masked card-style, registers a webhook with Yoco (storing the secret it
returns) or accepts one entered by hand, and lists/deletes the account's
webhooks. Generic settings endpoints never read or write these keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:28:50 +02:00
joshua 832a2c579e Merge branch 'feat/privacy-transfer-accept' 2026-10-19 18:46:43 +02:00
joshuaandClaude Opus 5.5 d1d417f294 Bump to 1.24.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:46:25 +02:00
joshuaandClaude Opus 5.5 c28cdb28f8 Require acceptance for ticket transfers; privacy and legal updates
Transfers now send the new holder a link (to the email/phone typed) and
only complete once they accept; they can decline and the sender can
cancel. No response reveals whether contact details belong to an
account, and attendee account links are no longer sent to payers.
Terms of Use and Privacy Policy are updated for all features since
1.12, with a full cookie policy and a "Cookie settings" control. The
/docs route list now covers every mounted route, and account
activation auto-login is fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:46:15 +02:00
joshua 1bd976f863 Merge branch 'feat/impersonate-user' 2026-10-19 18:25:10 +02:00
joshuaandClaude Opus 5.5 5bc7019863 Bump to 1.23.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:25:08 +02:00
joshuaandClaude Opus 5.5 bd7e5e8e0e Add read-only admin impersonation
Admins (with 2FA) can view the site as a non-admin user for up to 30
minutes, with a required reason and a "Viewing as" banner. It is
strictly read-only: a guard mounted before every route refuses any
write made with an impersonation token, protect/optionalAuth check the
session is live, and GET handlers skip the price-refresh writes. Start,
end, reason and every page/API call (including blocked attempts) are
audited; optional email to the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:25:02 +02:00
joshua 6b958884d6 Merge branch 'feat/funnel-stats' 2026-10-19 18:14:29 +02:00
joshuaandClaude Opus 5.5 996e0a2d89 Bump to 1.22.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:14:24 +02:00
joshuaandClaude Opus 5.5 904b674378 Add registration funnel stats
First-party, consent-based funnel tracking: a cookie notice asks once,
and only visitors who allow it get an anonymous visit id. Event page
views and registration starts are tracked from the browser; submit and
paid come from the registration. Adds the Registration funnel report
(conversion per stage, daily trend, by source/device/ticket option), a
conversion tile on the supervisor/admin dashboards, short-link source
tagging, and a daily rollup of raw rows older than 90 days.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CP62L9JxHomA36aYP1ekCe
2026-10-19 18:14:18 +02:00
joshua 141dce60ee Merge branch 'feat/feedback-forms' 2026-10-19 15:28:48 +02:00
joshuaandClaude Opus 5.5 b82de64d4d Bump to 1.21.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:42 +02:00
joshuaandClaude Opus 5.5 204a4268b6 Add post-event feedback forms
A Feedback step in the event wizard builds a survey that is sent at a
chosen time to everyone who checked in (or everyone registered), with
personal links and one reminder after 3 days. Answers can be anonymous.
Adds rating (1-5 stars) and multiple-choice field types, also usable on
attendee forms, and a Feedback summary report with response rate,
average ratings, choice breakdowns, comments and event comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:28:29 +02:00
joshua 1c3045b43f Merge branch 'feat/sponsor-a-spot' 2026-10-19 15:04:40 +02:00
joshuaandClaude Opus 5.5 6a6f56f377 Bump to 1.20.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:04:37 +02:00
joshuaandClaude Opus 5.5 dff83d47af Add sponsor a spot
Events can allow sponsorships: a "Sponsor a spot" button lets anyone
(guests included) pay through Yoco for whole spots or a custom amount,
anonymously or with a name and message. Payments land as event
donations in a sponsorship pool that supervisors assign with the
existing donation flow. Adds optional public progress towards a goal,
a sponsor receipt and Automations thank-you, pool columns in the
Donations report, and sponsorship labels/filter in Payments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 15:04:29 +02:00
joshua 9bdd3250bf Merge branch 'feat/room-allocation' 2026-10-19 14:45:09 +02:00
joshuaandClaude Opus 5.5 4a2e6ba01b Bump to 1.19.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:45:06 +02:00
joshuaandClaude Opus 5.5 a6549bc032 Add rooms & groups allocation
Supervisors can split an event's named attendees into allocation sets
(rooms, small groups, buses) with capacity, gender and leader per group,
using a drag-and-drop board or auto-allocate (keep bookings together or
split them). Adds printable group and master lists (medical view
audited), the group on tickets and in My Events, messaging by group,
a "My groups" page for leaders, and an optional per-event gender
question for named attendees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:44:58 +02:00
joshua ab2260db1f Merge branch 'feat/ticket-transfer' 2026-10-19 14:23:34 +02:00
joshuaandClaude Opus 5.5 35f61a8ffb Bump to 1.18.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:23:31 +02:00
joshuaandClaude Opus 5.5 c40542dafd Add ticket transfer
Payers and holders can hand a ticket to someone else before the event.
The new holder gets a new QR code (and an inactive account with an
activation link if they're new); the old code stops working and scans
of it, online or in offline sync, say it was transferred. One place can
be split off a shared group ticket. Transfers can be turned off per
event (supervisors can always transfer from At the door), youth events
need the new holder's own consent, and every transfer is audited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:23:24 +02:00
joshua e280c7fab5 Merge branch 'feat/offline-scanning' 2026-10-19 14:06:40 +02:00
joshuaandClaude Opus 5.5 4e5faff617 Bump to 1.17.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:34 +02:00
joshuaandClaude Opus 5.5 ae7dbf457c Add offline ticket scanning
Staff can lock a section (or the whole event) to their device, download
its tickets and keep scanning with no connection. Scans are queued in
IndexedDB and synced idempotently when back online; conflicts go into a
sync report for supervisors, who can also force-release a lost device.
The server now validates scan sections and refuses scans in a scope
locked to another device. Adds a web app manifest and a service worker
for the scanner page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 14:06:22 +02:00
joshua c5b0032e1d Merge branch 'feat/waitlist' 2026-10-19 13:43:20 +02:00
joshuaandClaude Opus 5.5 50c6c61afb Bump to 1.16.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:43:16 +02:00
joshuaandClaude Opus 5.5 736d17caff Add waitlist for sold-out tickets
Events can take a waitlist for sold-out lines. When places free up
(cancellation, smaller booking, higher stock limit) the next person is
offered them with a claim link and the places are held for a set time;
unclaimed offers expire and move on, with optional partial offers. Stock
is now counted in one place (utils/stock.js), including held places,
and manual registrations and booking edits are now stock-checked. Adds a
supervisor waitlist page, My Events waitlists, and the daily summary count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:43:10 +02:00
joshua 123fb288b1 Merge branch 'feat/parental-consent' 2026-10-19 13:25:02 +02:00
joshuaandClaude Opus 5.5 a13b443ab7 Bump to 1.15.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:24:57 +02:00
joshuaandClaude Opus 5.5 f55353ecc6 Add parental consent for youth events
Youth events need a name and date of birth for every attendee, and a
parent/guardian's details for under-18s. Parents get an email and
WhatsApp link to a consent page that records the signed name, time, IP,
device and exact consent text; medical and emergency details are stored
encrypted. Tickets are issued but check-in is blocked until consent is
given (supervisor override audited). A daily job sends reminders and
purges medical details after the retention period. Adds a supervisor
consent tracker, consent status and medical list reports, and clears
consent data when an account is anonymised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:24:44 +02:00
joshua 03b79972e6 Merge branch 'feat/group-tickets' 2026-10-19 12:12:52 +02:00
joshuaandClaude Opus 5.5 1f42f35835 Bump to 1.14.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:12:44 +02:00
joshuaandClaude Opus 5.5 a357dea50f Add group tickets with named attendees
Events can take a name (and optional email/phone) for each main-ticket
place. Each named person gets their own quantity-1 ticket and attendee
form; unnamed places share one ticket. Tickets go to the payer or to each
person, attendees matching one existing account are linked to it, and
the payer can edit names and send form links from My Events. Ticket
generation is now planned per line (utils/attendees.js), free
registrations use the same generator, and guest registration matches
accounts by phone too, refusing conflicting email/phone pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 12:12:33 +02:00
joshua 66a0dc99bf Merge branch 'feat/coupon-codes' 2026-10-19 11:43:36 +02:00
joshuaandClaude Opus 5.5 0968fb02be Bump to 1.13.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:43:26 +02:00
joshuaandClaude Opus 5.5 efcac8b2c2 Add coupon codes and staff pricing
Percentage, fixed-amount and comp codes, limited by event, ticket option
or variant, dates, use counts, minimum quantity, and people, roles or an
email domain. The discount is locked in on the registration (mirrored on
Registration.discountTotal so every total sees it), shows on invoices,
receipts, emails and the Yoco checkout, and is released on cancellation.
Use limits are enforced under an advisory lock.

Ticket options and variants can also carry a staff price that Staff and
above get automatically. Adds a Supervisor > Coupon codes page, code
fields on registration, My Events, manual registration, at the door and
the kiosk, a Discounts report, and audit log entries. Also fixes Yoco
line items and the free-registration check for lines spanning several
price tranches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:43:10 +02:00
joshua 38b53f3195 Merge branch 'feat/required-2fa-staff-roles' 2026-10-19 11:00:51 +02:00
joshuaandClaude Opus 5.5 7dcb1a83e0 Bump to 1.12.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:00:47 +02:00
joshuaandClaude Opus 5.5 3f3a8cad66 Require two-factor authentication for admins and supervisors
Admins and supervisors without 2FA are sent a code at their next login,
and verifying it turns 2FA on. They can change the channel but not turn
it off. Older sessions without 2FA are rejected with TWO_FACTOR_REQUIRED,
and promoting a user ends their sessions so they enrol at next login.
The requirement is skipped when no email or WhatsApp channel can deliver
a code, and TWO_FACTOR_REQUIRED_ROLES=false switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:00:12 +02:00
joshuaandClaude Opus 5.5 12832dea67 Add FEATURES.md and refresh info.md
FEATURES.md is a repo-root overview of everything the platform does.
info.md, the overview for prospective churches, is brought up to date
with features added since it was written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:06:06 +02:00
joshuaandClaude Opus 5.5 ba79f25571 Bump to 1.11.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:49:34 +02:00
joshuaandClaude Opus 5.5 a21f12ae3c Add optional two-factor authentication
Users can turn on 2FA from Profile & Security and receive a 6-digit
login code by email or WhatsApp, with a "trust this device for 30 days"
option. Admins can reset it for a locked-out user, and the self-service
kiosk handles the code step at setup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 14:49:34 +02:00
joshuaandClaude Opus 5.5 c06e12b7d9 Bump to 1.10.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:37 +02:00
joshuaandClaude Opus 5.5 05043379d9 Fix frontend build hanging when the backend is unreachable
Server-side fetches now fail fast when no API base URL is configured,
and the home and events pages build with an empty list if /api/events
can't be reached during next build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:30 +02:00
joshuaandClaude Opus 5.5 d6c99657a2 Update dependencies to clear npm audit advisories
Run npm audit fix in root, backend and frontend, bump nodemailer to 10,
override shell-quote in the root package, and allow-list the dependency
install scripts npm was blocking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:59:22 +02:00
joshuaandClaude Opus 5.5 abf7883490 Bump to 1.10.5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:46:36 +02:00
joshuaandClaude Opus 5.5 84ae0dbc55 Show in-progress events on home and events pages
Filter by endDate instead of startDate so events stay listed until they finish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 14:46:04 +02:00
joshuaandClaude Sonnet 5 2cf4aa79a1 Bump to 1.10.4
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAwumFeBwx6XSsQXp8Nfqt
2026-09-01 09:04:31 +02:00
joshuaandClaude Sonnet 5 0c9676a466 Fix "Add to calendar" 400 when FRONTEND_URL lacks a scheme
The ics library's url validator requires a scheme (https://...), but
production's FRONTEND_URL/APP_BASE_URL was configured without one, so
createEvent() rejected every request before generating a .ics file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PAwumFeBwx6XSsQXp8Nfqt
2026-09-01 09:00:17 +02:00
joshua 97c5c4cc6a Merge pull request 'Log event creation to admin audit log, add back button, bump to 1.10.3' (#3) from fix/event-create-audit-log-and-back-button into main 2026-08-28 14:49:24 +02:00
joshuaandClaude Sonnet 5 af39a25695 Also log staff cancellations via PUT /api/registrations/:id
Registrations can be cancelled two ways: DELETE /:id (owner or admin,
already logged registration_cancelled) and PUT /:id (staff+, status
change endpoint) — the latter was silently unlogged. Since PUT /:id
is staff-only, any transition into 'cancelled' there is inherently a
staff-initiated cancellation, so it's now logged the same way.

Audited all six categories promised in the 1.10.0 changelog entry
(refunds, donation assign/unassign, manual registrations,
staff-initiated cancellations, event create/update/delete, settings
changes) against their actual logAdminAction call sites and route
wiring — this was the only other gap found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 14:48:17 +02:00
joshuaandClaude Sonnet 5 08995d9882 Log event creation to admin audit log, add back button, bump to 1.10.3
createEvent never called logAdminAction, even though 1.10.0 already
listed event_created as a filterable action on the audit-log page —
only updateEvent/deleteEvent actually logged. Event creation is now
logged the same way, at every return path including the legacy
pre-migration retry branches.

Also adds a "Back to dashboard" link to Admin -> Audit log, matching
the existing back-link pattern on the Cashup page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 14:44:23 +02:00
joshua d892a0d153 Merge pull request 'Fix Sentry not instrumenting Express, bump version to 1.10.2' (#2) from fix/sentry-express-instrumentation-order into main 2026-08-28 13:22:54 +02:00
joshuaandClaude Sonnet 5 1a33f510f2 Fix Sentry not instrumenting Express, bump version to 1.10.2
express, cors, and @prisma/client were required at the top of
backend/src/index.js before Sentry.init() ran, so Sentry's
auto-instrumentation (which patches those modules via a require hook)
missed them — startup logged "[Sentry] express is not instrumented".
Sentry.init() now runs immediately after dotenv.config(), before any
of the libraries it instruments are required.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 13:21:19 +02:00
joshua 40880434f2 Merge pull request 'Fix upload path-traversal RCE vector, patch all known-vulnerable deps' (#1) from security/upload-path-traversal-and-dep-fixes into main 2026-08-28 12:44:21 +02:00
joshuaandClaude Sonnet 5 24679ed6ac Bump version to 1.10.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 12:36:55 +02:00
joshuaandClaude Sonnet 5 3e7ddcbe62 Fix upload path-traversal RCE vector, patch all known-vulnerable deps
Path traversal (CWE-22/CWE-73): event-image, branding (logo/favicon),
and event-attachment uploads built the saved filename from the
client-supplied original filename with no sanitization, and multer's
diskStorage joins that straight into the destination path. A crafted
filename containing `../` sequences could write the uploaded file
anywhere the server process has write access — reachable by any
supervisor-level account, and briefly pre-auth via the branding
uploads during initial /setup. Filenames are now always server-
generated (random bytes + validated extension); the original name is
kept only as display metadata.

Dependencies: express-rate-limit was declared only at the repo root
despite being required directly by backend/src/index.js, so a plain
`cd backend && npm install` (per the deployment doc) would never
install it — moved it into backend/package.json. Bumped next off a
version affected by a critical unauthenticated RCE (React Flight
protocol) and switched it from an exact pin to a caret range so future
patches install automatically. Bumped multer/nodemailer/jsonwebtoken/
uuid to patched versions, with an override forcing the vulnerable
nested uuid inside exceljs and the vulnerable postcss bundled inside
next to the patched versions too. `npm audit` is now clean (0
vulnerabilities) across root, backend, and frontend.

Hardening: jwt.verify() now pins algorithms: ['HS256'] instead of
trusting the token header; /uploads now serves with a restrictive CSP
and X-Content-Type-Options: nosniff so an uploaded SVG containing
<script> can't execute if opened directly.

Verified: backend's Jest suite passes, the backend boots and serves
real requests on the bumped deps, and `next build` compiles/type-
checks cleanly on the bumped frontend deps.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CSWFWQsjTc9GyffPiXEDQT
2026-08-28 11:33:05 +02:00
joshuaandClaude Sonnet 5 9aa1dd6a69 Bump version to 1.10.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 09:25:44 +02:00
joshuaandClaude Sonnet 5 d9dedd935a Ignore hope-events-deployment-setup.txt
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-28 09:22:24 +02:00
joshuaandClaude Sonnet 5 4a9ba8fec8 Add calendar export, SEO, error monitoring, backups, audit trail, and a starter test suite
Six site improvements picked from a "what could be better" review, plus a Jest
test suite covering the two areas with the trickiest money-handling history
in this project (early-bird pricing tranches, donation-leg accounting):

- "Add to calendar" .ics download on event pages and in confirmation emails
- sitemap.xml, robots.txt, and Open Graph/Twitter metadata for public pages
- Sentry error monitoring (backend + frontend), a no-op until SENTRY_DSN is set
- Nightly local pg_dump backups with a Site Settings tab to browse/trigger/download
- Admin audit trail for refunds, donations, manual registrations, event and
  settings changes, and staff-initiated cancellations
- Jest tests reproducing and guarding against the 1.8.0 tranche-pricing bug
  and the 1.4.2 donation-balance-inflation bug

Wallet passes (Google/Apple) were scoped out of this round — Apple Wallet
needs a paid Apple Developer account the project doesn't have yet, and the
user preferred shipping both together later rather than Google alone now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 14:50:11 +02:00
joshua 568a437069 Bump version to 1.9.5 2026-08-27 09:35:58 +02:00
joshua 47bc861487 Merge branch 'fix/alias-route-bot-traffic-oom' into main 2026-08-27 09:35:33 +02:00
joshuaandClaude Sonnet 5 5a83849549 Reject bot-probe paths on the event alias route before hitting the DB
The public [redirectUrl] catch-all route (and its backend counterpart,
GET /api/events/by-alias/:redirectUrl) matched any unmatched top-level
path, so routine bot/scanner traffic (/wp-login.php, /.env, etc.) was
firing a live database query on every hit. That traffic pattern looks
like the cause of the P1017 "server has closed the connection" storms
and OOM crashes seen from v1.7 onward. Both now reject anything that
isn't a plausible alias (letters/numbers/hyphens/underscores) before
touching Prisma.

Also adds a max_memory_restart safety net to PM2 for both processes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 09:33:23 +02:00
joshua 00db2261fb Run frontend PM2 process on port 3000 2026-08-26 14:38:29 +02:00
joshua aeda6f3b4d Add TRUST_PROXY env var for reverse-proxy deployments
Fixes express-rate-limit's ERR_ERL_UNEXPECTED_X_FORWARDED_FOR warning
and incorrect IP keying when nginx runs on a separate server in front
of the app.
2026-08-26 14:36:51 +02:00
joshua 1e50285e95 Add PM2 ecosystem config for production deployment 2026-08-26 11:59:08 +02:00
joshua 80e9595540 Merge branch 'fix/unhandled-rejection-no-crash' into main
Stops the server from hard-crashing on unhandled promise rejections, and bumps version to 1.9.3.
2026-08-26 09:07:06 +02:00
joshua 7a47b141f8 Bump version to 1.9.3 2026-08-26 09:06:52 +02:00
joshua c845c7cf0f Stop crashing the server on unhandled promise rejections
A single missed .catch() anywhere in the notification code (email/WhatsApp
sending) previously took down the whole process via process.exit(1). Log
the error instead and keep running.
2026-08-26 09:03:15 +02:00
joshuaandClaude Sonnet 5 cf549d440a Send activation link immediately for walk-in and manual registration accounts
Accounts created by staff on someone's behalf now get their activation
link (email or WhatsApp) sent right away, instead of only on a first
failed login attempt, matching what the Terms of Use already promised.
This also fixed a real account with a real email being silently
activated with a fixed, undisclosed password (Hope123).

Also fixes the self-service kiosk's "Create an account" password field,
which never actually took effect server-side, and removes the "Guest
(no account)" checkboxes that no longer had any backend effect once
every walk-in account started behaving the same way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 13:29:38 +02:00
joshuaandClaude Sonnet 5 91070e791b Bump version to 1.9.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:24:07 +02:00
joshua f15a035c9f Merge branch 'fix/contact-only-daily-summary' into main 2026-08-22 21:23:24 +02:00
joshuaandClaude Sonnet 5 b8c76c776f Skip daily summary emails for contact-only events
Contact-only events have no registration flow, so their daily
summary (registration/payment stats) was always empty — exclude
them from the query instead of sending a pointless email.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:22:53 +02:00
joshuaandClaude Sonnet 5 2d8db65622 Bump version to 1.9.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:12:37 +02:00
joshua 797440669f Merge branch 'fix/org-name-branding' into main 2026-08-22 21:11:52 +02:00
joshuaandClaude Sonnet 5 a95a7785eb Fix org name not showing in tab title, homepage, and backend pages
The browser tab title, homepage "Welcome to..." heading, and the
backend status/API docs pages all had the "Cross Code" default
hardcoded instead of reading the configured org_name setting.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:09:35 +02:00
joshuaandClaude Sonnet 5 874c58762a Bump version to 1.9.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 11:51:27 +02:00
joshua 1b369fc5c3 Merge branch 'feature/event-location-maps' into main 2026-08-21 11:50:31 +02:00
joshua 72e9ffd42a Add event/organisation location with Google Maps links
Events and the organisation profile now have an address, with a
"Directions" link and an embedded Google Maps view (no API key
required) shown on event pages, event cards, and the Contact page.
New events default their location to the org's configured address.
2026-08-21 11:47:23 +02:00
joshua 56ed3c6da7 Merge branch 'feature/early-bird-tranches-and-contact-events' into main 2026-08-21 10:33:19 +02:00
joshuaandClaude Sonnet 5 3df92ffd00 Bump version to 1.8.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 10:32:17 +02:00
joshuaandClaude Sonnet 5 4b4c7a44a0 Add PDF invoices/receipts with manual send, fix early-bird tier edit data loss
- Registration confirmations attach an invoice PDF (itemized breakdown,
  early-bird discount, balance due, Yoco pay-now link/QR) whenever a
  balance is outstanding; payment/donation confirmations attach a
  payment receipt PDF. Sent as an email attachment and, over WhatsApp,
  as the PDF itself with the existing message as its caption.
- Users can also (re)send either document on demand: an "Invoice"
  button on the registration detail popup, and a "Receipt" button next
  to each payment there and on the Payment history page, each opening
  an Email/WhatsApp choice popup, via two new endpoints restricted to
  the registration/payment's own owner.
- Fix: editing an event option's early-bird tiers deleted and
  recreated every tier for that option with brand-new ids, silently
  severing the appliedTierId link on all historical purchases (losing
  early-bird attribution and undercounting stock-limit usage) even for
  tiers the admin didn't touch. Tiers are now upserted by id.
- Update the "My Events" help content and the API docs index for the
  new endpoints.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 10:26:49 +02:00
joshuaandClaude Sonnet 5 2cc6667378 Fix early-bird total in notifications; group dashboard registration items
Registration/payment/reminder emails and WhatsApp messages loaded
registrations without their price tranches, so any line spanning more
than one tranche fell back to charging the full quantity at the most
recent tranche's price, silently dropping the early-bird discount from
the outstanding balance and itemized amounts shown to the user.

The user dashboard's registration detail popup also listed one raw
line per tranche; it now merges same item/price/tier lines and groups
early-bird lines separately from standard-price ones.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 08:57:29 +02:00
joshuaandClaude Sonnet 5 90ed1d073f Fix early-bird price blending and mislabeling; add contact-only events
- Early-bird pricing: RegistrationOption now tracks each purchase as a
  separate price tranche instead of overwriting a single price/quantity
  on repeat purchases, so buying more tickets after a tier expires no
  longer re-prices tickets already bought at the old price. Stock-limit
  checks, total-due calculation, and the Finance report's revenue-by-
  option are all tranche-aware; pages that showed one blended price per
  line now render/total each tranche. Viewing a pending/partially-paid
  registration (dashboard, detail page, or an event's registration
  list) now refreshes stale pricing on the spot instead of only at
  payment time.
- Fixed the "(early bird)" dashboard label incorrectly firing on any
  line priced below the base option price (e.g. a plain cheaper
  variant) — it now checks the real applied-tier flag.
- Added contact-only events (e.g. baptism): no registration/payment
  flow, shown on the public site with a "Contact us" popup instead of
  a Register button. Configurable via the admin event wizard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 17:26:35 +02:00
joshua cc17459117 Merge branch 'feature/site-branding-customization' into main 2026-08-20 14:57:44 +02:00
joshuaandClaude Sonnet 5 a6de39a08a Bump version to 1.7.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:57:23 +02:00
joshuaandClaude Sonnet 5 4d9e6a5107 Add admin-configurable branding (colors, logo, favicon) and generic default fallbacks
Site Settings -> Branding now supports a Primary/Secondary/Accent brand color
system applied site-wide (buttons, nav, hover states, links) and to outgoing
email header/CTA colors, plus a favicon upload alongside the existing logo
upload, a live preview panel (website/email x desktop/mobile), and
logo-based color suggestions. The setup wizard's Branding step got the same
treatment. Fixes two related bugs found along the way: the setup wizard's
logo/favicon upload was missing its auth token, and a static favicon.ico in
Next's special app/ convention path was silently overriding the dynamic one.

Also replaces every "Hope Events"/"Hope Family Church" default (org name,
email subjects, WhatsApp messages, report metadata, API docs) with a neutral
"Cross Code" placeholder, and the optional legal settings (operator name, IO
details, website URL, effective date) with obviously-generic placeholders
instead of defaulting to real personal/organisational details -- since this
platform is deployed for multiple organisations. Adds SETTINGS.md documenting
every setting's default behaviour.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-20 14:49:51 +02:00
joshua c465c96d95 Merge branch 'feature/supervisor-payments-improvements' into main 2026-08-08 01:24:52 +02:00
joshuaandClaude Sonnet 5 7ff9565f92 Bump version to 1.6.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 01:19:49 +02:00
joshuaandClaude Sonnet 5 12ba1f945f Add search and event filter to the Assigned donations list
Finding a specific leg to unassign meant scanning the whole list by
eye. Adds a text search (matches registrant, donor, or event) and an
event dropdown (built from events that actually have assigned legs)
above the list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 01:15:45 +02:00
joshuaandClaude Sonnet 5 43bf37aa5c Fix donation-assignment admin email reading as a real payment
The internal admin notice for applying a donation to a registration
reused buildPaymentAdminNotice as-is, so it read "Payment recorded" /
"Registration payment" — indistinguishable from an actual incoming
payment even though no new money changed hands. Adds a dedicated
buildDonationAssignmentAdminNotice wrapper (mirroring the one already
added for unassignment) so the subject, heading, and Type field all
say "Donation applied" instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:59:24 +02:00
joshuaandClaude Sonnet 5 393ca2551e Add ability to unassign a donation from a registration
Assigning a donation to a registration was one-way: the refund flow
could reverse the money but left the donation's "leg" payment in
place, permanently locking that portion of the donation as used even
though it had been refunded back out. Adds POST
/api/payments/unassign-donation, which deletes the leg, reverts the
registration's status/tickets the same way a refund downgrade already
does, and notifies the registrant. New "Assigned donations" list on
the supervisor Payments page surfaces existing legs with an Unassign
action, since no such list existed before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:53:21 +02:00
joshuaandClaude Sonnet 5 145f8a2801 Speed up payment/refund processing on the supervisor dashboard
Reconciling a Yoco payment and sending payment links blocked the HTTP
response on ticket-PDF generation and email/WhatsApp sends; they now
run in the background like the other payment flows already did.
Registration/payment option loops (pricing, stock checks, ticket
generation) now resolve concurrently instead of sequentially. The
Payments page dropped a per-registration N+1 fetch and now refreshes
its lists in parallel after each action. Added missing indexes for
dashboard stats and donation-leg lookups, and made GET
/api/registrations optionally paginated.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-08 00:00:29 +02:00
joshua 705eba37d2 Merge branch 'fix/join-us-button-logged-in' into main 2026-08-07 01:57:23 +02:00
joshuaandClaude Sonnet 5 5d8896ecc2 Bump version to 1.5.4
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:57:02 +02:00
joshuaandClaude Sonnet 5 c80e8d3436 Fix Join Us button linking logged-in users to register page
Send logged-in users to their dashboard instead of the registration
form, matching how the Navbar already treats logged-in vs guest users.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:52:35 +02:00
joshua 2be398bdc0 Merge branch 'fix/help-modal-mobile-overflow' into main 2026-08-07 01:17:08 +02:00
joshuaandClaude Sonnet 5 9ee76af63e Bump version to 1.5.3
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:16:53 +02:00
joshuaandClaude Sonnet 5 5ac74859c6 Fix help guide popups overflowing the screen on mobile
The popup card had no overall height cap, only the tab content area
did, so the header/quick-links/footer could push the close button off
screen on short mobile viewports. The card is now capped to the
screen height with the header and footer pinned in place, and only
the tab content scrolls internally.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 01:14:44 +02:00
joshuaandClaude Sonnet 5 e3c837e8b3 Bump version to 1.5.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:47:54 +02:00
joshua d4d7b9df98 Merge branch 'fix/dashboard-mobile-styling' into main 2026-08-07 00:47:14 +02:00
joshua d8e2316f63 Add tab icons and fix mobile dashboard styling issues
- Add matching lucide-react icons to tab/mode switcher buttons on
  payments, at-the-door, manual, email-attendees, whatsapp-attendees,
  and admin cashup pages, mirroring icons already used in their help menus
- Fix navbar Logout button sitting lower than other nav links (missing
  border/padding classes that other links use for their active-underline)
- Fix stat card labels getting truncated on mobile by removing the
  ellipsis-cut label and widening the mobile grid to one column
- Fix Revenue trend / Top performing events rendering outside the
  viewport on mobile by containing horizontal overflow and truncating
  long event titles in the table
2026-08-07 00:41:52 +02:00
joshuaandClaude Sonnet 5 0ac5017204 Stop tracking banner.json runtime data store
Same reasoning as scheduled-emails.json: it's mutated by the running
app (site banner content), not source. readBanner() already falls
back to sane defaults when the file is missing, so untracking it is
safe for fresh checkouts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:04:45 +02:00
joshuaandClaude Sonnet 5 fccf220039 Stop tracking scheduled-emails.json runtime data store
It's mutated by the running app (scheduled job queue), not source -
committing it churns the repo with live recipient/message content.
Kept on disk, just untracked; a fresh checkout will get an empty
store created on demand by ensureStore().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:03:04 +02:00
joshua ef2c82ad7e Merge branch 'fix/whatsapp-scheduling-channel-bug' into main (1.5.1) 2026-08-07 00:01:01 +02:00
joshuaandClaude Sonnet 5 3ae9c9b964 Fix scheduled job list/edit dropping message content
toClient() never returned the message body (html/text for email,
message for WhatsApp), so "Manage scheduled" showed nothing to view
or edit even though the content existed in storage. Editing a
scheduled WhatsApp message also saved to the wrong payload field
(text instead of message), silently discarding the edit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 00:00:43 +02:00
joshuaandClaude Sonnet 5 87b3bff214 Bump version to 1.5.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 23:41:43 +02:00
joshua 520a1ae167 Merge branch 'fix/whatsapp-scheduling-channel-bug' 2026-08-06 23:40:32 +02:00
joshuaandClaude Sonnet 5 8e957d6401 Fix scheduled WhatsApp messages sending as email; add 24h cleanup and recipient display
The scheduled-job store never persisted the channel field, so the
send worker always fell through to its email branch regardless of
what was requested. Also purges sent jobs 24h after sending instead
of keeping them forever, and surfaces who each scheduled job will go
to in the admin "manage scheduled" lists (now correctly filtered per
channel too).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 23:37:35 +02:00
joshuaandClaude Sonnet 5 49ee8682d8 Bump version to 1.5.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:29:17 +02:00
joshuaandClaude Sonnet 5 49e28c15bf Merge branch 'feature/site-redesign' (1.5.0)
Full site visual redesign, site-wide contextual help system, dashboard
KPI overhaul (rolling trailing-month window), and assorted fixes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:27:39 +02:00
joshuaandClaude Sonnet 5 f08959e306 Help guide opens on demand only; add At the door to admin quick actions
- The site-wide help guide no longer auto-opens on first visit to a page
  — it only opens when the help button is clicked. Removed the
  now-pointless "Don't show this again" checkbox and the per-page
  dismissal tracking it drove.
- Admin dashboard quick actions was missing "At the door" (walk-in
  registration, payments, ticket printing), which Supervisor already had.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:17:12 +02:00
joshuaandClaude Sonnet 5 5c2e29ed1b Full site redesign, help system, and dashboard stats fixes
Multi-phase visual facelift (design tokens, dashboards, sidebar/navbar
shell, per-page help guides, and a layout/content pass across every
remaining page) plus backend fixes to the dashboard KPI stats:

- Admin/Supervisor dashboard KPIs (revenue, donations, registrations,
  tickets sold) now use a rolling trailing-month window (today back one
  calendar month, e.g. 9 May - 8 June if today is 8 June) instead of
  calendar month-to-date, which under-counted for most of the month.
  The comparison window shifts the same way, so like is still compared
  with like.
- Reports deep-links from those stat tiles now match the same window
  (range=trailing_month, replacing range=this_month).
- Design tokens (brand-* Tailwind scale + shadcn CSS variables), a
  site-wide contextual help button, fixed dashboard sidebar/navbar,
  Admin/Supervisor/Staff/User dashboard rebuilds backed by a new
  GET /api/stats/overview endpoint, a dedicated Contact page, Site
  Settings restyle with WhatsApp config folded in, and an Account
  activity feed backed by a new SecurityEvent model.
- Every remaining page (home, events, registration flow, auth, legal,
  payment results, and every Admin/Supervisor/Staff/User tool page)
  restyled onto the same design tokens, several with real layout
  upgrades (home hero, events list/detail, donate page, auth pages).
- 20+ new dedicated help guides so the whole site has page-specific
  help content instead of falling back to a generic guide.
- Assorted fixes surfaced along the way: donation-leg double-counting
  in payment stats, donations not counting toward revenue, refund
  netting in per-method report breakdowns, and donation
  over-allocation after a refund.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 15:00:10 +02:00
joshuaandClaude Sonnet 5 d715a45e22 Bump version to 1.4.2
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 09:13:04 +02:00
joshuaandClaude Sonnet 5 a6cec9d8bc Fix supervisor payments mobile tabs, reconcile donor, report method buckets, and refund/donation accounting
- Supervisor Payments: mode tabs now wrap on mobile instead of overflowing off-screen.
- Reconciling a Yoco transaction as a donation now lets staff pick who it's from.
- Reports payment-method breakdown now buckets into Cash/Card/EFT/Other everywhere,
  folding Apple Pay, Google Pay, and Yoco-portal payments into Card.
- Refunds now net against their original method's bucket (Cashup/Finance/Profit reports,
  My Payments filtering/display) instead of vanishing or falling into "Other".
- Refund form's method dropdown mirrors the real payment methods and auto-fills from the
  payment being refunded, replacing an ambiguous generic "Refund" option.
- Fixed donation remaining/unallocated balance inflating instead of shrinking when a
  donation is refunded (assign-donation endpoint, cashup reports, donations reports,
  and the Assign Donation panel all summed refund legs with the wrong sign).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 09:08:53 +02:00
joshuaandClaude Sonnet 5 bdb8993914 Bump version to 1.4.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 15:00:44 +02:00
joshuaandClaude Sonnet 5 8b3a0ced9f Fix Reports mobile layout overflow and desktop date range overflow
Report popup buttons and the page's search/Back controls overflowed
off-screen on mobile instead of wrapping, and the sidebar's custom
date range inputs spilled outside the filter box on desktop.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 14:57:09 +02:00
joshuaandClaude Sonnet 5 d858c7fcf5 Sync root package.json version to 1.4.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:49:03 +02:00
joshua c0f43c0e4c Merge branch 'feature/reports-and-cashup-overhaul' (1.4.0) 2026-08-04 15:46:55 +02:00
joshuaandClaude Sonnet 5 2434a7ffbd Bump version to 1.4.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:46:09 +02:00
joshuaandClaude Sonnet 5 144aee9d54 Hide dashboard sidebar on staff/supervisor/admin sub-pages; fix mobile overflow
- Sidebar now shows only on each role's root landing page
  (/dashboard/staff, /dashboard/supervisor, /dashboard/admin) and hides on
  every sub-page beneath them, not just Reports. Navbar's "Dashboard" link
  always leads back to the role root.
- Fixed two dropdown panels (EventsDropdown, the Email/WhatsApp Attendees
  recipient picker) that could extend past the viewport's right edge on
  narrow screens; both now stretch to their trigger's width like other
  dropdowns in the app already do.
- Wrapped the Admin Cashup event-costs table in the same overflow-auto
  container every sibling table on that page already uses, so it scrolls
  horizontally on narrow screens instead of squeezing its columns.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 15:30:56 +02:00
joshuaandClaude Sonnet 5 98f85e1465 Fix financial double-counting, rebuild cashup accountability, and redesign the Reports page
Financial correctness (donation-leg model):
- Donations are no longer mutated when assigned to a registration; assignment now
  creates an immutable "leg" record referencing the original donation instead.
- Fixed several places where money was double-counted once a donation was partially
  or fully assigned (Payments, Revenue summary, Cashup reconciliation, Finance
  report, Profit report, Master Orders, Revenue Detailed).
- Payments now record who recorded them (recordedBy), separate from who they're for.

Cashup:
- Per-user cash denomination counting (optional, any time) replaces the single
  event-wide manual entry; the event's cash actual is the live sum of these counts.
- New "Payment accountability by staff member" breakdown across all methods, and a
  read-only "Report" tab that opens automatically once an event is closed.

Reports page redesign:
- New shell: sidebar of universal filters (events, date range, past/inactive/closed
  toggles), searchable/categorized report grid, and a popup viewer with
  Print/Email/Excel/WhatsApp actions plus an in-app Reporting Guide.
- Visual pass: colored stat tiles and bar charts on most reports, matching mockups.
- PDF exports (download/Print/Email/WhatsApp) now share a branded design mirroring
  the web report — colored header, stat tiles, bar chart, highlighted totals.
- Excel export now produces a styled .xlsx (via exceljs) instead of a plain CSV.
- Master Orders' "Donations made" table is now included in every export channel.

Bug fixes discovered while testing exports:
- Report emails now go through the shared, DB-configurable mail utility instead of
  a one-off transporter that ignored Site Settings SMTP config.
- WhatsApp report sends now surface the actual WAWP API error and auto-recover a
  disconnected session, instead of a bare axios status-code message.

Also: Admin-editable notification preference, richer Admin Registrations dashboard,
{{payment.link}} placeholder for Email/WhatsApp Attendees, and background
email/WhatsApp attendee sending.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 14:52:54 +02:00
joshua f7ec9b1ca1 Merge branch 'fix/self-service-kiosk-lookup' 2026-08-03 13:03:12 +02:00
joshuaandClaude Sonnet 5 8e38e2faf6 Rework self-service kiosk account lookup for privacy and safety (1.3.2)
Replaces the explicit "look up existing account" search field with automatic
lookup as email/phone are entered, requires operator confirmation before any
matched account's name/email/phone/preference is changed, adds a password
show/hide toggle, and fixes two bugs found during testing: entering a phone
number belonging to a different account could silently overwrite the form
with that account's details, and re-checking an unchanged field (e.g. from
tapping a ticket quantity button) could revert edits already made. Also adds
a server-side check rejecting registrations whose email and phone resolve to
two different existing accounts, as defense in depth.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 12:56:26 +02:00
joshua ce80eb0829 Bump version to 1.3.1 2026-07-28 16:17:37 +02:00
joshua 6cf8c336d7 Merge branch 'fix/self-service-kiosk' 2026-07-28 16:16:31 +02:00
joshua aaa2108824 Populate email/phone from an unmatched kiosk search query
When the account lookup finds no match, carry the typed query into whichever
of Email/Phone it resembles (email-shaped or phone-shaped) instead of
discarding it, so the operator doesn't have to retype it. Leaves both blank
if it matches neither shape, and resets Name/notification preference for a
fresh entry.
2026-07-28 16:05:41 +02:00
joshua f57aea17bb Replace as-you-type account check with an explicit search field
The kiosk previously ran a debounced background lookup on every keystroke
in the visitor Email/Phone fields, silently autofilling matches. Replaced
with a dedicated "Look up existing account" field that only searches when
the operator presses Enter or clicks Search, and matches exactly against
either email or phone (never both from one query, to avoid digits in an
email being misread as an unrelated phone number). Also simplified the
"account already exists" banner wording.
2026-07-28 14:35:28 +02:00
joshua 6af60c739e Update changelog for self-service kiosk fixes 2026-07-28 14:24:21 +02:00
joshua d9fa08b383 Fix self-service kiosk: hide closed events and autofill known visitors
- GET /api/events/all gains an opt-in excludeClosed=true param, used only by
  the kiosk, so closed events no longer show as selectable there while other
  admin/supervisor screens that still need to see closed events are unaffected.
- GET /api/users/check-exists now also returns the matched account's name,
  email, phone, and notification preference (safe fields only). The kiosk's
  existing debounced lookup uses this to autofill whichever fields are still
  blank when a visitor enters an email or phone that matches an existing
  account, without overwriting anything already typed.
2026-07-28 14:21:47 +02:00
joshuaandClaude Sonnet 5 a916274a9d Bump version to 1.3.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:06:08 +02:00
joshuaandClaude Sonnet 5 1f82202776 Merge branch 'feature/door-checkin'
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 15:04:51 +02:00
joshuaandClaude Sonnet 5 734b344ddf Add door check-in flow for Main Tickets
Lets staff redeem a registration's Main Tickets by quantity at the door
(via the Payment/registration flow) instead of scanning each QR code,
and automatically emails/WhatsApps a check-in confirmation to the
attendee. Also routes the At The Door "Open" button and post-payment
flow dynamically: paid registrations jump straight to Check-In instead
of a forced ticket print, since tickets are already sent automatically.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 14:56:31 +02:00
joshuaandClaude Sonnet 5 803d605da4 Bump version to 1.2.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-27 10:35:21 +02:00
joshua d64c0a9fea Fix wrong auth token key and mislabeled loading dialog on payment flows
registration/success read the token from the wrong localStorage key
(token instead of hope_events_token), which broke registration/form
loading there and made the new "Pay with Yoco" checkout call fail with
"Not authorized, token failed" — switched to the shared auth context
like the rest of the app.

dashboard/user's "Make payment" reused the ticket-email dialog, which
hardcoded "Sending tickets…" while loading — the dialog now takes an
optional loading title/subtitle so payNow can show its own message.
2026-07-27 10:29:42 +02:00
joshua 8cc6e58875 Simplify self-service payments to full-amount checkout, add manual-page payment tab
Self-service "pay now" flows (registration success + user dashboard) now go
straight to a Yoco checkout for the full outstanding balance instead of
prompting for a partial amount; that page has been removed. Partial-amount
payment links remain supervisor/admin-only via the Payments dashboard.

Also adds a "Record Payment" tab to the supervisor manual registration page,
pre-filled with the most recently created registration, so staff can capture
a payment right after registering someone without leaving the page.
2026-07-27 10:14:49 +02:00
joshuaandClaude Sonnet 5 4f895b85b3 Bump version to 1.1.0
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 10:36:38 +02:00
joshuaandClaude Sonnet 5 f6dcf3a479 Add registration status badges and auto-dismissing dashboard messages
Two consistency fixes requested after the payment-method work:

1. Registration status (pending/confirmed/partial_paid/paid/cancelled)
   was printed as a raw string on the user dashboard. Added
   RegistrationStatusBadge mirroring the existing EventStatusBadge
   pattern, using the same status colors already established on
   dashboard/admin/registrations.

2. Inline success/error banners across dashboard pages persisted
   indefinitely. Added a shared useDismissingState hook (drop-in
   useState replacement that auto-clears a truthy value after 7s,
   resetting the timer on each update) and swapped it in across ~24
   dashboard files. Excluded: message-only modal dialogs (ticket-
   scanning's success/error confirmations) and two states that mix
   live form-validation feedback with async results inside actively-
   open forms (the registration-edit modal's editError, the event
   create/edit modal's error) - those keep persisting until the user
   acts, since auto-hiding a "fix this field" message mid-edit would
   be a regression. Also fixed at-the-door's existing bespoke
   auto-dismiss timers (10s/15s, one mislabeled as "5s") to the same
   consistent 7s, and removed admin/settings' manual x dismiss button
   in favor of the same auto-only behavior.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 10:17:53 +02:00
joshuaandClaude Sonnet 5 fea9136382 Apply payment method normalization consistently across user-facing views
Audited every place Payment.method reaches the UI. The main user
dashboard's per-registration payment list (fed by GET
/api/payments/registration/:id) was still showing the raw gateway
string, since that endpoint is shared with the staff-facing supervisor
payments page and wasn't touched by the earlier /mypayments fix.

Extracted the cash/card/eft/voucher/other normalization (matching
normalizeUserMethod on the backend) into frontend/src/lib/paymentMethod.ts
and applied it to both user-facing payment displays. Staff-facing views
(supervisor payments, at-the-door, reports, cashup) intentionally keep
showing the raw method for reconciliation and were left unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:41:43 +02:00
joshuaandClaude Sonnet 5 bff568475c Fold apple_pay/google_pay into the card bucket, keep everything else under other
Per feedback: card-network wallet payments (Apple Pay, Google Pay) should
report and filter as "card" on the user payment history page rather than
"other", since they settle the same way as a card payment. Any other
gateway-reported method still falls under "other".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:27:52 +02:00
joshuaandClaude Sonnet 5 3a4ff57188 Switch payment method filter to a static list with an "other" bucket
Per feedback, drop the dynamic /mypayments/methods lookup (wasn't
loading reliably) in favor of a static cash/card/eft/voucher/other
dropdown. Server-side normalization now folds any gateway-reported
method outside those four manual-entry values (apple_pay, google_pay,
yoco, etc.) into "other" instead of "card", both in the returned data
and in the filter query.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:24:53 +02:00
joshuaandClaude Sonnet 5 6860db60c9 Normalize user-facing payment method to cash/card/eft/voucher
Per feedback, stop trying to surface every gateway-reported wallet
type (apple_pay, google_pay, yoco, ...) as its own filter/display
value on the user payment history page. Both /mypayments and
/mypayments/methods now fold anything outside the four manual-entry
methods into "card", both in the returned data and in the filter
query, so Apple Pay/Google Pay payments show up under Card.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:02:59 +02:00
joshuaandClaude Sonnet 5 2ef0cc1bb3 Populate payment method filter from real data instead of a guessed list
The previous fix hardcoded apple_pay/google_pay as extra filter options,
but Payment.method is free-text set by whatever the gateway reports, so
guessing at literal values was fragile and still didn't surface them for
this user. Add GET /api/payments/mypayments/methods returning the
distinct method values actually present in the user's payments, and have
the dashboard filter build its options from that instead. Also switch
the method filter from a startsWith match to an exact match, since the
values now come straight from the same column being filtered.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 08:55:58 +02:00
joshuaandClaude Sonnet 5 c89ed74fea Fix payment method handling for non-default types (apple_pay, google_pay)
Yoco webhook payments are tagged with whatever wallet type the gateway
reports, not just cash/card/eft/voucher. Cashup/report totals were
silently dropping those into the "other" bucket instead of "card", and
the new user payment history page couldn't filter by them and showed
raw snake_case values.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 08:28:59 +02:00
joshua 14465fee66 Add paginated payment history to user dashboard
Users can now view their own payments (excluding donations) with
server-side pagination (25/page), date range, method, and
payment/refund filters, both on the API and the new client page.
2026-07-23 18:02:53 +02:00
joshuaandClaude Sonnet 5 a6ac97309e Bump version to 1.0.1
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 17:08:28 +02:00
joshua 05666e2ab3 Merge branch 'bug/user-dash-closed-events-editable' 2026-07-23 17:07:05 +02:00
joshuaandClaude Sonnet 5 3632f67d8b Add closed/past/inactive status badges to user dashboard event titles
Adds an EventStatusBadge component shown next to every event title on
the dashboard (registrations list, upcoming events, tickets, and the
registration modal), with precedence Closed > Past > Inactive when
more than one applies — reusing the badge styling already established
in the supervisor events list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:56:32 +02:00
joshuaandClaude Sonnet 5 719e2df867 Block self-service payment and cancellation on closed/past registrations
Extends the earlier user-dashboard fix: canEditActive is renamed
canModifyActive and now also gates the "Make payment" and "Cancel
registration" actions, not just editing. Backend enforcement added to
cancelRegistration and createYocoCheckout to block past-event
self-service payment/cancellation server-side (cashup-closed events
were already blocked via assertEventOpen; admins/supervisors are
exempt from the past-date check, consistent with existing overrides).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:51:10 +02:00
joshuaandClaude Sonnet 5 9ed988d774 Fix user dashboard: buried edit errors, closed events not hidden, closed/past registrations editable
Registration-edit errors were set into a page-level error state rendered
behind the edit modal overlay; they now render inside the modal. The
"Show past events" toggle only hid date-based past events, letting
cashup-closed events leak through by default; a shared isEventOver()
check now covers both, applied to registrations, tickets, and the
Edit button visibility (mirroring the backend's own edit block).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 16:43:33 +02:00
joshua 7146f5cf77 Add CHANGELOG.md 2026-07-23 15:38:39 +02:00
joshua fc60671dd8 Normalize package versions to semver 1.0.0 2026-07-23 15:36:37 +02:00
joshua fdd2d241b4 Initial commit
Next.js + Express event management app for Hope Family Church.
2026-07-23 15:26:47 +02:00
794 changed files with 256581 additions and 188 deletions
+55 -1
View File
@@ -2,7 +2,61 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## Unreleased
## events@2.3.0, contracts@1.3.0, agent@1.0.0 - 2026-11-17
Phase 1c (authenticator-app sign-in) and phase 1d (docs/AGENT-1.0-PLAN.md): installs, updates and
uninstalls from the Hub (Hub 2.1.0) through the agent. Tested end to end on a VM (church server +
central server + Hub, AGENT-1.0-PLAN §13 and EVENTS-2.2-PLAN §6).
### Events (2.3.0)
- Two-factor with an authenticator app, and recovery codes. The env template, the church export
and registering by itself from `HUB_LICENCE_KEY` for installs from the Hub. Details in
`apps/events/CHANGELOG.md`.
### Contracts (1.3.0)
- `crosscode.agent-job/1` (fixed job types, strict arguments), `crosscode.agent-report/1`,
`crosscode.script-report/1`, `crosscode.agent-stats/1`, the agent join / poll requests,
`crosscode.env-template/1` and `crosscode.church-export/1`.
- `@crosscode/contracts/signing`: Ed25519 jobs (over canonical JSON) and agent requests, config
sealed to a server (X25519 + HKDF + AES-256-GCM), export encryption.
### Agent (1.0.0)
- `apps/agent`: polls the Hub, checks every job (pinned key, server, time window, replays, type,
arguments) and runs the crosscode script for it; stats every minute; listens on nothing.
Install script, systemd unit, self-update with automatic revert.
### crosscode script
- `--json` reports and `--config` on every command; `.env` files from each release's env template
(appended to, never rewritten, on deploy); `install --frp` with Hub-given ports, a database on
another server, and clean-up on failure; frpc.ini blocks; `restart`, `export`, `uninstall`, `purge`.
- Fixed in the VM test: `adopt` applies a release's new migrations in the switch-over; a failed
migration is marked rolled back so later deploys aren't blocked; frpc is restarted once when its
admin lines are first added; a site's PM2 always runs under its own systemd unit (`pm2-<user>`),
so restarting or updating the agent never stops a site; tags are fetched with `--force`.
## events@2.2.0, contracts@1.2.0 - 2026-11-17
### Events
- **Cross Events 2.2.0**, the first release from this repo (`apps/events`, ROADMAP-v3 phase 1b):
moved in with its history, npm workspaces with one root lockfile, and the `crosscode` script
(`deploy`, `status`, `install`, `adopt`) in `scripts/`. Also AI use shown in tokens instead of
rand, and everything the backend serves under `/api`. Details in `apps/events/CHANGELOG.md`.
### Contracts
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
### Docs
- The roadmap (`docs/ROADMAP-v3.md`) and the Hub protocol (`docs/hub-protocol.md`) move here from
`hope-events/docs/`, since they cover every product. New: `docs/HANDOVER.md` (where each phase
stands) and `docs/EVENTS-2.2-PLAN.md` (phase 1b, Cross Events into the monorepo).
## contracts@1.1.0 - 2026-11-04
+14 -3
View File
@@ -1,7 +1,8 @@
# Cross Code platform
The monorepo for the Cross Code products that come after Cross Events, and the formats they share.
The plan is in `hope-events/docs/ROADMAP-v3.md` (decided 2026-11-03).
The plan for every product is in [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) (decided 2026-11-03); where
things stand is in [`docs/HANDOVER.md`](./docs/HANDOVER.md).
| Folder | What | Status |
|--------|------|--------|
@@ -11,8 +12,18 @@ The plan is in `hope-events/docs/ROADMAP-v3.md` (decided 2026-11-03).
| `apps/website` | Church Website | Placeholder (phase 4) |
| `apps/app` | Church App (PWA) | Placeholder (phase 6) |
Cross Events (`joshua/hope-events`) and Cross Code Hub (`joshua/events-hub`) stay in their own
repos and install `@crosscode/contracts` from Gitea's package registry.
Cross Events (`joshua/hope-events`) moves in as `apps/events` in Events 2.2.0
([`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md)). Cross Code Hub (`joshua/events-hub`) stays in
its own repo and gets `@crosscode/contracts` as a packed release committed there (decision 22).
## Docs
| File | What |
|------|------|
| [`docs/ROADMAP-v3.md`](./docs/ROADMAP-v3.md) | The plan: products, contracts, Accounts, sync, Hub, servers, build order, pricing, decisions |
| [`docs/HANDOVER.md`](./docs/HANDOVER.md) | Where each phase stands and what's next |
| [`docs/hub-protocol.md`](./docs/hub-protocol.md) | Install ↔ Hub protocol, versions 1 and 2 (a copy lives in `events-hub`) |
| [`docs/EVENTS-2.2-PLAN.md`](./docs/EVENTS-2.2-PLAN.md) | Phase 1b: Cross Events into the monorepo, the `crosscode` script |
## Rules (ROADMAP-v3 §1)
+55
View File
@@ -0,0 +1,55 @@
# Cross Code server agent
Runs on every server (docs/AGENT-1.0-PLAN.md). It polls Cross Code Hub every 30 seconds for
signed jobs, runs the `crosscode` script for them, sends the results, and sends the server's
stats every 60 seconds. **It listens on nothing**: no port, no URL; every request goes out to the Hub.
## Joining a server
Hub → Servers → **Add server** shows a command with a one-time token (valid an hour):
```bash
curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
```
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
`crosscode-agent.service`.
## On the server
| What | Where |
|------|-------|
| Config (Hub address, server id, the Hub's pinned job key) | `/etc/crosscode/agent.json` |
| Private keys (never leave the server) | `/etc/crosscode/agent-ed25519.pem`, `agent-x25519.pem` |
| Seen job ids (90 days), unsent reports, exports in progress | `/var/lib/crosscode-agent/` |
| A job's opened config, only while it runs | `/run/crosscode-agent/` |
| Logs | `journalctl -u crosscode-agent` |
## Security
- **Jobs are signed** by the Hub's job key (Ed25519, pinned when joining). The agent refuses a
job that's unsigned, for another server, outside its time window, already seen, of an unknown
type, or with an argument outside its schema. Refusals are reported to the Hub.
- **Only the `crosscode` script runs**, with arguments built from the checked job (an array,
never a shell). There's no "run this command" job.
- **Config** (database admin, server settings) arrives sealed to this server's X25519 key. It's
opened into a root-only file for the job and removed straight after.
- **Log lines** sent with a report are filtered for passwords, tokens, keys and licence keys.
- **Exports** are encrypted on the server with a new key; the key travels in the job's report
so the Hub can email the download link, and the Hub doesn't store it.
## Updates
An `update-agent` job builds the new release next to the running one, switches `current`, and
restarts. If the new agent hasn't polled the Hub within 150 seconds, `revert.sh` switches back.
## Development
```bash
npm run build -w apps/agent # dist/cli.js: one file, everything bundled
npm test -w apps/agent # the no-listening-socket test runs on Linux, after a build
```
+23
View File
@@ -0,0 +1,23 @@
# The Cross Code server agent (docs/AGENT-1.0-PLAN.md §3). Root, because the crosscode script it
# runs needs root (PostgreSQL, PM2 for each app user, frpc). It listens on nothing.
[Unit]
Description=Cross Code server agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/node /opt/crosscode/agent/current/apps/agent/dist/cli.js run
Restart=always
RestartSec=10
RuntimeDirectory=crosscode-agent
RuntimeDirectoryMode=0700
StateDirectory=crosscode-agent
StateDirectoryMode=0700
Environment=NODE_ENV=production
# Logs: journalctl -u crosscode-agent
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# Installs the Cross Code server agent and joins this server to the Hub
# (docs/AGENT-1.0-PLAN.md §3). Hub → Servers → Add server shows the command, with a one-time token:
#
# curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
# | sudo bash -s -- --hub https://hub.crosscode.co.za --token <token> [--central]
#
# Church servers also get the crosscode script (/opt/crosscode/tools, linked as
# /usr/local/bin/crosscode). The central server (--central) only gets the agent, which is
# read-only there. Running it again updates nothing that's there already; use --force to join again.
set -Eeuo pipefail
REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode-platform.git}"
ROOT=/opt/crosscode/agent
TOOLS=/opt/crosscode/tools
HUB="" TOKEN="" MODE=church VERSION="" FORCE=""
die() { printf '!!> %s\n' "$*" >&2; exit 1; }
step() { printf '==> %s\n' "$*"; }
while [ $# -gt 0 ]; do
case "$1" in
--hub) HUB="$2"; shift 2 ;;
--token) TOKEN="$2"; shift 2 ;;
--central) MODE=central; shift ;;
--version) VERSION="$2"; shift 2 ;;
--force) FORCE=--force; shift ;;
*) die "Unknown option $1" ;;
esac
done
[ "$(id -u)" = 0 ] || die "Run as root (sudo bash -s -- …)."
[[ "$HUB" =~ ^https?:// ]] || die "--hub <url> is required."
[[ "$TOKEN" =~ ^[A-Za-z0-9_-]{32,128}$ ]] || die "--token is required (Hub → Servers → Add server)."
[ -z "$VERSION" ] || [[ "$VERSION" =~ ^agent@[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version: expected agent@x.y.z."
step "System packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update -q
apt-get install -y -q git curl ca-certificates
if ! command -v node >/dev/null || [ "$(node -p 'process.versions.node.split(".")[0]')" -lt 24 ]; then
step "Node.js 24"
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
apt-get install -y -q nodejs
fi
if [ -z "$VERSION" ]; then
VERSION="$(git ls-remote --tags --refs "$REPO" 'agent@*' | sed 's#.*refs/tags/##' | sort -t@ -k2 -V | tail -n 1)"
[ -n "$VERSION" ] || die "No agent@x.y.z release yet."
fi
DIR="$ROOT/releases/${VERSION#agent@}"
step "Agent $VERSION in $DIR"
mkdir -p "$ROOT/releases"
chmod 755 /opt/crosscode "$ROOT" 2>/dev/null || true
if [ ! -d "$DIR/.git" ]; then
git clone --quiet --depth 1 --branch "$VERSION" "$REPO" "$DIR"
fi
(
cd "$DIR"
NODE_ENV=development npm ci --no-audit --no-fund --include=dev --include-workspace-root -w packages/contracts -w apps/agent
npm run build -w packages/contracts
npm run build -w apps/agent
)
[ "$(node "$DIR/apps/agent/dist/cli.js" version)" = "${VERSION#agent@}" ] || die "The build doesn't report $VERSION."
ln -sfn "$DIR" "$ROOT/current"
install -m 755 "$DIR/apps/agent/deploy/revert.sh" "$ROOT/revert.sh"
if [ "$MODE" = church ]; then
step "The crosscode script ($TOOLS)"
[ -d "$TOOLS/.git" ] || git clone --quiet "$REPO" "$TOOLS"
ln -sfn "$TOOLS/scripts/crosscode" /usr/local/bin/crosscode
fi
step "Joining the Hub ($HUB)"
mkdir -p /etc/crosscode /var/lib/crosscode-agent
chmod 700 /etc/crosscode /var/lib/crosscode-agent
args=(join --hub "$HUB" --token "$TOKEN")
[ "$MODE" = central ] && args+=(--central)
[ -n "$FORCE" ] && args+=("$FORCE")
if [ -f /etc/crosscode/agent.json ] && [ -z "$FORCE" ]; then
echo " Already joined (/etc/crosscode/agent.json); keeping it."
else
node "$ROOT/current/apps/agent/dist/cli.js" "${args[@]}"
fi
step "systemd"
install -m 644 "$DIR/apps/agent/deploy/crosscode-agent.service" /etc/systemd/system/crosscode-agent.service
systemctl daemon-reload
systemctl enable --now crosscode-agent
systemctl restart crosscode-agent
step "Done: the server shows on Hub → Servers within a minute (journalctl -u crosscode-agent)."
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Started by a one-shot systemd timer after an agent update (src/update.ts). If the new agent
# hasn't polled the Hub by now, update-pending.json is still there: switch back to the previous
# release and restart. Copied to /opt/crosscode/agent/revert.sh by install.sh.
set -euo pipefail
ROOT=/opt/crosscode/agent
PENDING=/var/lib/crosscode-agent/update-pending.json
[ -f "$PENDING" ] || exit 0
[ -L "$ROOT/previous" ] || { echo "crosscode-agent revert: no previous release" >&2; exit 1; }
ln -sfn "$(readlink "$ROOT/previous")" "$ROOT/current.tmp"
mv -T "$ROOT/current.tmp" "$ROOT/current"
rm -f "$PENDING"
systemctl restart crosscode-agent
echo "crosscode-agent revert: the new agent didn't poll in time; back on $(readlink "$ROOT/current")" >&2
+7
View File
@@ -0,0 +1,7 @@
module.exports = {
testEnvironment: "node",
testMatch: ["<rootDir>/tests/**/*.test.ts"],
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
moduleFileExtensions: ["ts", "js", "json"],
modulePathIgnorePatterns: ["<rootDir>/dist/"],
};
+18
View File
@@ -0,0 +1,18 @@
{
"name": "@crosscode/agent",
"version": "1.0.0",
"private": true,
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
"license": "UNLICENSED",
"bin": { "crosscode-agent": "./dist/cli.js" },
"scripts": {
"build": "tsup",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "jest"
},
"dependencies": {
"@crosscode/contracts": "*",
"zod": "^4.6.7"
},
"engines": { "node": ">=24" }
}
+98
View File
@@ -0,0 +1,98 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import { paths } from "./paths";
/**
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
*/
export interface FrpsSettings {
proxyBindAddr: string | null;
allowPorts: string | null;
}
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
export function parseFrpsIni(text: string): FrpsSettings {
let inCommon = false;
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
for (const raw of text.split(/\r?\n/)) {
const line = raw.trim();
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
if (!m) continue;
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
}
return out;
}
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
try {
return parseFrpsIni(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
export function portAllowed(port: number, allowPorts: string | null): boolean {
if (!allowPorts) return true;
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
const [a, b] = range.split("-").map((n) => Number(n.trim()));
if (!Number.isFinite(a)) return false;
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
});
}
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
export function parseSs(text: string): Map<number, string[]> {
const out = new Map<number, string[]>();
for (const line of text.split("\n")) {
const cols = line.trim().split(/\s+/);
const local = cols[3];
if (!local) continue;
const i = local.lastIndexOf(":");
const port = Number(local.slice(i + 1));
const addr = local.slice(0, i).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
if (!Number.isFinite(port)) continue;
out.set(port, [...(out.get(port) ?? []), addr]);
}
return out;
}
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
export interface PortCheck {
port: number;
allowed: boolean;
listening: boolean;
loopbackOnly: boolean;
ok: boolean;
}
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
const warnings: string[] = [];
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
const bind = frps?.proxyBindAddr ?? null;
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
const results = ports.map((port) => {
const addrs = listening.get(port) ?? [];
const allowed = portAllowed(port, frps?.allowPorts ?? null);
const loopbackOnly = addrs.length > 0 && addrs.every((a) => LOOPBACK.has(a));
return { port, allowed, listening: addrs.length > 0, loopbackOnly, ok: allowed && addrs.length > 0 && loopbackOnly };
});
for (const r of results) {
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
}
return { ports: results, proxyBindAddr: bind, warnings };
}
export function listeningNow(): Promise<Map<number, string[]>> {
return new Promise((resolve) => {
execFile("ss", ["-ltnH"], { timeout: 10_000 }, (err, stdout) => resolve(err ? new Map() : parseSs(String(stdout))));
});
}
+87
View File
@@ -0,0 +1,87 @@
import fs from "node:fs";
import os from "node:os";
import { agent } from "@crosscode/contracts";
import { generateEd25519, generateX25519 } from "@crosscode/contracts/signing";
import { configFile, ed25519File, loadConfig, saveConfig, writePrivate, x25519File } from "./config";
import { hubClient, postUnsigned } from "./hub";
import { Agent } from "./loop";
import { AGENT_VERSION } from "./stats";
/**
* crosscode-agent (AGENT-1.0-PLAN §3)
* crosscode-agent join --hub https://hub.crosscode.co.za --token <one-time token> [--central]
* crosscode-agent run what systemd runs (crosscode-agent.service)
* crosscode-agent version
*/
const USAGE = `crosscode-agent ${AGENT_VERSION}
crosscode-agent join --hub <url> --token <token> [--central] [--force]
Join this server to the Hub with a one-time token (Hub → Servers → Add server).
Makes the server's key pairs; the private keys never leave it.
crosscode-agent run poll the Hub for jobs and send stats (run by systemd)
crosscode-agent version
`;
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
}
export async function join(args: string[]): Promise<void> {
const hub = flag(args, "--hub");
const token = flag(args, "--token");
const mode: agent.AgentMode = args.includes("--central") ? "central" : "church";
if (!hub || !/^https?:\/\//.test(hub)) throw new Error("--hub <url> is required (https://hub.crosscode.co.za).");
if (!token) throw new Error("--token <token> is required (Hub → Servers → Add server).");
if (fs.existsSync(configFile()) && !args.includes("--force")) {
throw new Error(`This server has already joined (${configFile()}). Use --force to join again (the Hub then sees a new server).`);
}
const ed = generateEd25519();
const x = generateX25519();
const reply = agent.joinResponseSchema.parse(await postUnsigned(hub, "/api/agent/v1/join", {
agentApiVersion: agent.AGENT_API_VERSION,
token,
mode,
hostname: os.hostname().slice(0, 253),
agentVersion: AGENT_VERSION,
publicKeys: { ed25519: ed.publicKey, x25519: x.publicKey },
}));
writePrivate(ed25519File(), ed.privateKeyPem);
writePrivate(x25519File(), x.privateKeyPem);
saveConfig({ hubUrl: hub, serverId: reply.serverId, mode, hubJobKey: reply.hubJobKey, pollSeconds: reply.pollSeconds, statsSeconds: reply.statsSeconds, joinedAt: new Date().toISOString() });
console.log(`Joined the Hub as ${reply.serverId} (${mode}). Start the agent: systemctl enable --now crosscode-agent`);
}
export async function main(argv = process.argv.slice(2)): Promise<void> {
const [command, ...args] = argv;
switch (command) {
case "version":
case "--version":
console.log(AGENT_VERSION);
return;
case "join":
await join(args);
return;
case "run": {
if (process.getuid && process.getuid() !== 0 && !process.env.CROSSCODE_AGENT_ALLOW_NON_ROOT) {
throw new Error("Run the agent as root (it runs crosscode, which needs root).");
}
const { config, keys } = loadConfig();
const a = new Agent({ config, keys, hub: hubClient(config, keys) });
for (const sig of ["SIGTERM", "SIGINT"] as const) process.on(sig, () => { a.stop(); setTimeout(() => process.exit(0), 1000).unref(); });
await a.start();
return;
}
default:
process.stdout.write(USAGE);
if (command && command !== "help" && command !== "--help") process.exitCode = 1;
}
}
if (require.main === module) {
main().catch((e) => {
console.error(`crosscode-agent: ${(e as Error).message}`);
process.exit(1);
});
}
+58
View File
@@ -0,0 +1,58 @@
import type { agent } from "@crosscode/contracts";
/**
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
* as an array passed straight to the process (never through a shell). Jobs the agent handles
* itself (update-agent, check-ports) have none.
*
* `--config <file>` is added by the runner when the job brings config; `--json` always.
*/
export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string } = {}): string[] | null {
switch (job.type) {
case "install": {
const a = job.args;
if (a.products.length !== 1 || a.products[0] !== "events") throw new Error("This agent can only install Events so far.");
const domain = a.domains.events;
const ports = a.ports.events;
if (!domain || !ports) throw new Error("An Events install needs its domain and ports.");
// The church's address: the Events domain without "events." (crosscode uses it for the
// church.env ADDRESS; the domain itself goes in --events-domain).
const address = domain.startsWith("events.") ? domain.slice("events.".length) : domain;
const out = ["install", a.church, "--products", "events", "--domain", address, "--events-domain", domain,
"--api-port", String(ports.api), "--web-port", String(ports.web), "--frp"];
const v = a.versions?.events;
if (v) out.push("--version", v);
return out;
}
case "add-product":
return ["add", job.args.church, job.args.product];
case "deploy": {
const out = ["deploy", job.args.church, ...job.args.products];
for (const v of job.args.versions ?? []) out.push("--version", v);
if (job.args.check) out.push("--check");
return out;
}
case "adopt": {
const out = ["adopt", job.args.church, "--events-dir", job.args.eventsDir];
if (job.args.version) out.push("--version", job.args.version);
if (job.args.address) out.push("--address", job.args.address);
return out;
}
case "adopt-undo":
return ["adopt", job.args.church, "--undo"];
case "restart":
return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])];
case "export":
if (!opts.exportFile) throw new Error("export needs a file to write");
return ["export", job.args.church, "--out", opts.exportFile];
case "uninstall":
return ["uninstall", job.args.church, "--confirm", job.args.church];
case "purge":
return ["purge", job.args.church, "--confirm", job.args.church];
case "status":
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
case "update-agent":
case "check-ports":
return null;
}
}
+49
View File
@@ -0,0 +1,49 @@
import fs from "node:fs";
import path from "node:path";
import { z } from "zod";
import { agent } from "@crosscode/contracts";
import { publicKeyOf } from "@crosscode/contracts/signing";
import { paths } from "./paths";
/** /etc/crosscode/agent.json, written by `crosscode-agent join`. No secrets: the keys are files next to it. */
export const agentConfigSchema = z.object({
hubUrl: z.url({ protocol: /^https?$/ }),
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
mode: agent.agentModeSchema,
/** The Hub's job-signing key, pinned when joining. */
hubJobKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
pollSeconds: z.int().min(5).max(600).default(30),
statsSeconds: z.int().min(15).max(3600).default(60),
joinedAt: z.string(),
});
export type AgentConfig = z.infer<typeof agentConfigSchema>;
export interface Keys {
ed25519Pem: string;
x25519Pem: string;
}
export const configFile = () => path.join(paths.configDir, "agent.json");
export const ed25519File = () => path.join(paths.configDir, "agent-ed25519.pem");
export const x25519File = () => path.join(paths.configDir, "agent-x25519.pem");
/** Writes a file only root can read, atomically. */
export function writePrivate(file: string, text: string): void {
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
const tmp = `${file}.tmp-${process.pid}`;
fs.writeFileSync(tmp, text, { mode: 0o600 });
fs.renameSync(tmp, file);
}
export function loadConfig(): { config: AgentConfig; keys: Keys } {
const config = agentConfigSchema.parse(JSON.parse(fs.readFileSync(configFile(), "utf8")));
const keys = { ed25519Pem: fs.readFileSync(ed25519File(), "utf8"), x25519Pem: fs.readFileSync(x25519File(), "utf8") };
// A broken pair would sign requests the Hub can't check; better to stop at start.
publicKeyOf(keys.ed25519Pem);
publicKeyOf(keys.x25519Pem);
return { config, keys };
}
export function saveConfig(config: AgentConfig): void {
writePrivate(configFile(), `${JSON.stringify(config, null, 2)}\n`);
}
+75
View File
@@ -0,0 +1,75 @@
import { signAgentRequest } from "@crosscode/contracts/signing";
import type { AgentConfig, Keys } from "./config";
/**
* Requests to the Hub. The agent only ever makes outgoing requests (it listens on nothing,
* AGENT-1.0-PLAN §2 rule 1); every one after joining is signed with the server's Ed25519 key.
*/
export class HubRequestError extends Error {
constructor(message: string, readonly status: number, readonly code: string | null) {
super(message);
}
}
export type Fetch = typeof fetch;
export interface HubClient {
post(path: string, body: unknown): Promise<unknown>;
put(path: string, body: Uint8Array, contentType: string): Promise<unknown>;
}
const TIMEOUT_MS = 30_000;
const UPLOAD_TIMEOUT_MS = 10 * 60_000;
async function send(fetcher: Fetch, url: string, init: RequestInit, timeoutMs: number): Promise<unknown> {
let res: Response;
try {
res = await fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
} catch (e) {
throw new HubRequestError(`The Hub can't be reached: ${(e as Error).message}`, 0, "HUB_UNREACHABLE");
}
if (res.status === 204) return null;
let body: unknown;
try {
body = await res.json();
} catch {
body = null;
}
if (!res.ok) {
const b = (body ?? {}) as { message?: string; code?: string };
throw new HubRequestError(b.message || `The Hub answered ${res.status}`, res.status, b.code ?? null);
}
return body;
}
/** An unsigned request (only `join`, where the one-time token is the proof). */
export function postUnsigned(hubUrl: string, path: string, body: unknown, fetcher: Fetch = fetch): Promise<unknown> {
return send(fetcher, `${hubUrl.replace(/\/$/, "")}${path}`, {
method: "POST",
headers: { "content-type": "application/json", "user-agent": "crosscode-agent" },
body: JSON.stringify(body),
}, TIMEOUT_MS);
}
export function hubClient(config: AgentConfig, keys: Keys, fetcher: Fetch = fetch): HubClient {
const base = config.hubUrl.replace(/\/$/, "");
const signed = (raw: string | Uint8Array) => signAgentRequest({ serverId: config.serverId, privateKeyPem: keys.ed25519Pem, rawBody: raw });
return {
post(path, body) {
const raw = JSON.stringify(body);
return send(fetcher, `${base}${path}`, {
method: "POST",
headers: { "content-type": "application/json", "user-agent": "crosscode-agent", ...signed(raw) },
body: raw,
}, TIMEOUT_MS);
},
put(path, body, contentType) {
return send(fetcher, `${base}${path}`, {
method: "PUT",
headers: { "content-type": contentType, "user-agent": "crosscode-agent", ...signed(body) },
body,
}, UPLOAD_TIMEOUT_MS);
},
};
}
+226
View File
@@ -0,0 +1,226 @@
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { encryptExport } from "@crosscode/contracts/signing";
import { checkPorts, listeningNow, readFrps } from "./central";
import { crosscodeArgs } from "./command";
import type { AgentConfig, Keys } from "./config";
import { type HubClient, HubRequestError } from "./hub";
import { paths } from "./paths";
import { runCrosscode, type RunResult } from "./runner";
import { AGENT_VERSION, collectStats } from "./stats";
import { confirmUpdate, updateAgent } from "./update";
import { checkJob, SeenJobs } from "./verify";
/**
* The agent's life: poll the Hub every 30 s for jobs due, send stats every 60 s, run one job at a
* time and send each result. Reports that can't be sent are kept in an outbox and sent later, so
* a Hub outage never loses a job's result. Nothing here listens: every request goes out.
*/
const log = (...a: unknown[]) => console.log(new Date().toISOString(), ...a);
export interface AgentDeps {
config: AgentConfig;
keys: Keys;
hub: HubClient;
seen?: SeenJobs;
/** For tests: replaces running crosscode and the stats. */
run?: (args: string[], job: agent.AgentJob) => Promise<RunResult>;
stats?: () => Promise<agent.AgentStats>;
now?: () => Date;
}
const outboxDir = () => path.join(paths.stateDir, "outbox");
function report(job: { id: string; type: agent.JobType }, serverId: string, r: Omit<RunResult, "log"> & { log?: string[] }): agent.AgentReport {
return {
schema: "crosscode.agent-report/1",
jobId: job.id,
serverId,
type: job.type,
status: r.status,
startedAt: r.startedAt,
finishedAt: r.finishedAt,
steps: r.steps.slice(0, 200),
result: r.result,
...(r.message ? { message: r.message.slice(0, 2000) } : {}),
log: (r.log ?? []).slice(-200),
};
}
export class Agent {
private seen: SeenJobs;
private stopped = false;
private confirmed = false;
private failures = 0;
constructor(private deps: AgentDeps) {
this.seen = deps.seen ?? new SeenJobs();
}
private now(): Date {
return this.deps.now?.() ?? new Date();
}
/** Sends a report, or keeps it in the outbox to send later. */
async send(r: agent.AgentReport): Promise<void> {
try {
await this.deps.hub.post("/api/agent/v1/report", r);
} catch (e) {
log(`[report] ${r.jobId}: couldn't send (${(e as Error).message}); kept to send later.`);
fs.mkdirSync(outboxDir(), { recursive: true, mode: 0o700 });
fs.writeFileSync(path.join(outboxDir(), `${r.jobId}.json`), JSON.stringify(r), { mode: 0o600 });
}
}
async flushOutbox(): Promise<void> {
let files: string[];
try { files = fs.readdirSync(outboxDir()).filter((f) => f.endsWith(".json")); } catch { return; }
for (const f of files) {
const file = path.join(outboxDir(), f);
try {
await this.deps.hub.post("/api/agent/v1/report", JSON.parse(fs.readFileSync(file, "utf8")));
fs.rmSync(file, { force: true });
} catch (e) {
// A report the Hub refuses outright (4xx) would never go: drop it rather than retry forever.
if (e instanceof HubRequestError && e.status >= 400 && e.status < 500) fs.rmSync(file, { force: true });
return;
}
}
}
/** One poll: fetch the jobs due and run them, one after the other. Returns the next delay (s). */
async pollOnce(): Promise<number> {
const { config } = this.deps;
let reply: { jobs: unknown[]; pollSeconds: number };
try {
reply = agent.pollResponseSchema.parse(await this.deps.hub.post("/api/agent/v1/poll", {
agentApiVersion: agent.AGENT_API_VERSION, agentVersion: AGENT_VERSION, mode: config.mode, runningJobId: null,
}));
} catch (e) {
this.failures++;
const delay = Math.min(300, config.pollSeconds * 2 ** Math.min(this.failures, 4));
log(`[poll] ${(e as Error).message}; next try in ${delay}s.`);
return delay;
}
this.failures = 0;
if (!this.confirmed) {
confirmUpdate();
this.confirmed = true;
}
await this.flushOutbox();
for (const raw of reply.jobs) {
if (this.stopped) break;
await this.handle(raw);
}
return reply.pollSeconds || config.pollSeconds;
}
async handle(raw: unknown): Promise<void> {
const { config } = this.deps;
const verdict = checkJob(raw, config, this.seen, this.now());
const at = this.now().toISOString();
if (!verdict.ok) {
log(`[job] ${verdict.id ?? "(no id)"} ${verdict.status}: ${verdict.message}`);
if (verdict.id && verdict.type && !this.seen.has(verdict.id)) {
this.seen.add(verdict.id);
await this.send(report({ id: verdict.id, type: verdict.type }, config.serverId, { status: verdict.status, steps: [], result: {}, message: verdict.message, startedAt: at, finishedAt: at }));
}
return;
}
const job = verdict.job;
// Seen before it runs, so a crash part-way can never run it twice.
this.seen.add(job.id);
log(`[job] ${job.id} ${job.type} ${JSON.stringify(job.args)}`);
const result = await this.execute(job);
log(`[job] ${job.id} ${result.status}${result.message ? `: ${result.message}` : ""}`);
await this.send(report(job, config.serverId, result));
if ((result as RunResult & { restart?: boolean }).restart) {
log("[agent] Exiting so systemd starts the new version.");
this.stopped = true;
setTimeout(() => process.exit(0), 500);
}
}
private async execute(job: agent.AgentJob): Promise<RunResult & { restart?: boolean }> {
const startedAt = this.now().toISOString();
const limit = agent.JOB_TIME_LIMIT_MINUTES[job.type];
try {
switch (job.type) {
case "update-agent": {
const u = await updateAgent(job.args.version, AGENT_VERSION);
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
}
case "check-ports": {
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
}
case "export":
return await this.runExport(job, limit);
default: {
const args = crosscodeArgs(job);
if (!args) throw new Error(`No command for ${job.type}`);
return await this.run(args, job, limit);
}
}
} catch (e) {
return { status: "failed", steps: [], result: {}, message: (e as Error).message, log: [], startedAt, finishedAt: new Date().toISOString() };
}
}
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
if (this.deps.run) return this.deps.run(args, job);
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
}
/**
* export: crosscode writes the ZIP, the agent encrypts it with a fresh key and uploads it. The
* key goes to the Hub only in this job's report, so it can email the download link; the Hub
* doesn't keep it (AGENT-1.0-PLAN §9).
*/
private async runExport(job: Extract<agent.AgentJob, { type: "export" }>, limit: number): Promise<RunResult> {
const dir = path.join(paths.stateDir, "exports");
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const zip = path.join(dir, `${job.args.exportId}.zip`);
fs.rmSync(zip, { force: true });
try {
const r = await this.run(crosscodeArgs(job, { exportFile: zip })!, job, limit);
if (r.status !== "succeeded") return r;
const { key, file } = encryptExport(fs.readFileSync(zip));
await this.deps.hub.put(`/api/agent/v1/exports/${job.args.exportId}`, file, "application/octet-stream");
return { ...r, result: { ...r.result, file: undefined, encryptedBytes: file.length, key } };
} finally {
fs.rmSync(zip, { force: true });
}
}
async statsOnce(): Promise<void> {
try {
const stats = await (this.deps.stats ?? (() => collectStats(this.deps.config.mode)))();
await this.deps.hub.post("/api/agent/v1/stats", stats);
} catch (e) {
log(`[stats] ${(e as Error).message}`);
}
}
/** Runs until stopped: polls and stats on their own timers, never at the same time as a job. */
async start(): Promise<void> {
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
let nextStats = 0;
while (!this.stopped) {
if (Date.now() >= nextStats) {
await this.statsOnce();
nextStats = Date.now() + this.deps.config.statsSeconds * 1000;
}
const delay = await this.pollOnce();
await new Promise((r) => setTimeout(r, Math.max(5, Math.min(delay, this.deps.config.statsSeconds)) * 1000));
}
}
stop(): void {
this.stopped = true;
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Where the agent keeps things on a server (docs/AGENT-1.0-PLAN.md §3). Each can be moved with an
* environment variable, which the tests use.
*/
const env = (name: string, fallback: string): string => process.env[name] || fallback;
export const paths = {
/** agent.json and the two private keys, root only (mode 600). */
get configDir() { return env("CROSSCODE_AGENT_CONFIG_DIR", "/etc/crosscode"); },
/** Seen job ids (replay protection) and exports waiting to upload. */
get stateDir() { return env("CROSSCODE_AGENT_STATE_DIR", "/var/lib/crosscode-agent"); },
/** A job's opened config, only while the job runs (tmpfs). */
get runDir() { return env("CROSSCODE_AGENT_RUN_DIR", "/run/crosscode-agent"); },
/** The crosscode script (a checkout of the monorepo in /opt/crosscode/tools). */
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
/** frps.ini on the central server. */
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
/** The churches on a church server. */
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
};
+51
View File
@@ -0,0 +1,51 @@
/**
* Log lines are filtered for anything that looks like a secret before they leave the server
* (AGENT-1.0-PLAN §4, rule 7). The crosscode script never prints .env values, but tools it runs
* (npm, Prisma, git) might print a URL with a password or a token in an error.
*/
const RULES: [RegExp, string][] = [
// user:password@ in any URL (postgresql://, https://).
[/([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, "$1***@"],
// KEY=value and KEY: value for keys that hold secrets.
[/\b([A-Z0-9_]*(SECRET|PASSWORD|PASSWD|TOKEN|API_KEY|PRIVATE_KEY|DSN|LICENCE_KEY|LICENSE_KEY)[A-Z0-9_]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/g, "$1$3***"],
// Authorization headers and bearer tokens.
[/\b(authorization\s*:\s*)(bearer|basic)\s+\S+/gi, "$1$2 ***"],
[/\bbearer\s+[A-Za-z0-9._~+/=-]{16,}/gi, "Bearer ***"],
// PEM blocks.
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[private key]"],
// Cross Code licence keys (CEH-7K2M-…).
[/\b(CEH|CCA|CCW|CCP)-[A-Z0-9]{4}(-[A-Z0-9]{4}){3}\b/g, "$1-****"],
// Long random-looking strings (hex or base64 of 32+ characters): likely keys or tokens.
[/\b[A-Fa-f0-9]{40,}\b/g, "***"],
[/\b[A-Za-z0-9+/_-]{48,}={0,2}/g, "***"],
];
export function redact(line: string): string {
let out = line;
for (const [re, to] of RULES) out = out.replace(re, to);
return out.length > 1000 ? `${out.slice(0, 997)}...` : out;
}
/** Keeps the last `max` lines of output, redacted, without holding all of it in memory. */
export class LogTail {
private lines: string[] = [];
private partial = "";
constructor(private max = 200) {}
push(chunk: string): void {
const parts = (this.partial + chunk).split(/\r?\n/);
this.partial = parts.pop() ?? "";
for (const p of parts) this.add(p);
}
private add(line: string): void {
this.lines.push(redact(line));
if (this.lines.length > this.max) this.lines.shift();
}
end(): string[] {
if (this.partial) {
this.add(this.partial);
this.partial = "";
}
return [...this.lines];
}
}
+116
View File
@@ -0,0 +1,116 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { openConfig } from "@crosscode/contracts/signing";
import { paths } from "./paths";
import { LogTail, redact } from "./redact";
/**
* Runs `crosscode … --json` for a job: argument array (no shell), the job's config opened to a
* file only root can read and removed as soon as the job ends, a time limit per type (the whole
* process group is stopped past it), and the last 200 log lines, redacted.
*/
export interface RunResult {
status: agent.JobStatus;
steps: agent.ReportStep[];
result: Record<string, unknown>;
message?: string;
log: string[];
startedAt: string;
finishedAt: string;
}
export interface RunOptions {
args: string[];
sealedConfig?: agent.Sealed | null;
x25519Pem: string;
timeLimitMinutes: number;
/** For tests. */
bin?: string;
}
const iso = (d = new Date()) => d.toISOString();
function writeConfig(sealed: agent.Sealed, x25519Pem: string): string {
const opened = agent.jobConfigSchema.parse(openConfig(sealed, x25519Pem));
fs.mkdirSync(paths.runDir, { recursive: true, mode: 0o700 });
const file = path.join(paths.runDir, `config-${process.pid}-${Date.now()}.json`);
fs.writeFileSync(file, JSON.stringify(opened), { mode: 0o600 });
return file;
}
export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
const startedAt = iso();
let configFile: string | null = null;
try {
if (opts.sealedConfig) {
try {
configFile = writeConfig(opts.sealedConfig, opts.x25519Pem);
} catch (e) {
return { status: "refused", steps: [], result: {}, message: `The job's config couldn't be opened with this server's key: ${(e as Error).message}`, log: [], startedAt, finishedAt: iso() };
}
}
const args = [...opts.args, "--json", ...(configFile ? ["--config", configFile] : [])];
return await new Promise<RunResult>((resolve) => {
const tail = new LogTail(200);
let stdout = "";
const child = spawn(opts.bin ?? paths.crosscode, args, {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
});
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
try { process.kill(-child.pid!, "SIGTERM"); } catch { /* already gone */ }
setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { /* gone */ } }, 10_000).unref();
}, opts.timeLimitMinutes * 60_000);
child.stdout.setEncoding("utf8").on("data", (d: string) => { stdout += d; if (stdout.length > 5_000_000) stdout = stdout.slice(-1_000_000); });
child.stderr.setEncoding("utf8").on("data", (d: string) => tail.push(d));
child.on("error", (e) => {
clearTimeout(timer);
resolve({ status: "failed", steps: [], result: {}, message: `crosscode couldn't be started: ${e.message}`, log: tail.end(), startedAt, finishedAt: iso() });
});
child.on("close", (code) => {
clearTimeout(timer);
const log = tail.end();
const report = parseReport(stdout);
if (timedOut) {
resolve({ status: "failed", steps: report?.steps ?? [], result: report?.result ?? {}, message: `Stopped after the time limit (${opts.timeLimitMinutes} minutes).`, log, startedAt, finishedAt: iso() });
return;
}
if (!report) {
resolve({ status: code === 0 ? "succeeded" : "failed", steps: [], result: {}, message: code === 0 ? undefined : `crosscode ended with code ${code} without a report.`, log, startedAt, finishedAt: iso() });
return;
}
resolve({
status: report.status,
steps: report.steps,
result: report.result,
message: report.message ? redact(report.message) : undefined,
log,
startedAt: report.startedAt,
finishedAt: report.finishedAt,
});
});
});
} finally {
if (configFile) fs.rmSync(configFile, { force: true });
}
}
/** The last line of stdout that's a valid script report. */
export function parseReport(stdout: string): agent.ScriptReport | null {
const lines = stdout.trim().split("\n").reverse();
for (const line of lines) {
try {
const parsed = agent.scriptReportSchema.safeParse(JSON.parse(line));
if (parsed.success) return parsed.data;
} catch {
// not JSON
}
}
return null;
}
+167
View File
@@ -0,0 +1,167 @@
import { execFile, execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { agent } from "@crosscode/contracts";
import { readFrps } from "./central";
import { paths } from "./paths";
/**
* The server's stats every 60 s (AGENT-1.0-PLAN §10, crosscode.agent-stats/1): RAM, CPU, disks,
* uptime, versions, frpc, and each PM2 process with its church and product. Read from /proc and
* the tools that are there; anything missing is null rather than an error.
*/
export const AGENT_VERSION = "1.0.0";
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
return new Promise((resolve) => {
execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 10_000_000 }, (err, stdout) => resolve(err ? null : String(stdout)));
});
}
export function parseMeminfo(text: string): agent.AgentStats["ram"] {
const kb = (key: string) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0) * 1024;
const total = kb("MemTotal");
const available = kb("MemAvailable");
return { totalBytes: total, usedBytes: Math.max(0, total - available), availableBytes: available, swapTotalBytes: kb("SwapTotal"), swapUsedBytes: Math.max(0, kb("SwapTotal") - kb("SwapFree")) };
}
/** CPU busy % between two /proc/stat readings. */
export function cpuPercent(a: string, b: string): number {
const parse = (t: string) => {
const f = (/^cpu\s+(.+)$/m.exec(t)?.[1] ?? "").trim().split(/\s+/).map(Number);
const idle = (f[3] ?? 0) + (f[4] ?? 0);
return { idle, total: f.reduce((s, n) => s + (Number.isFinite(n) ? n : 0), 0) };
};
const x = parse(a), y = parse(b);
const total = y.total - x.total;
if (total <= 0) return 0;
return Math.min(100, Math.max(0, Math.round(((total - (y.idle - x.idle)) / total) * 1000) / 10));
}
async function disks(): Promise<agent.AgentStats["disks"]> {
const out = await run("df", ["-P", "-B1", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs", "-x", "overlay"]);
if (!out) return [];
return out.trim().split("\n").slice(1).map((l) => l.trim().split(/\s+/)).filter((c) => c.length >= 6 && c[5]!.startsWith("/"))
.slice(0, 30).map((c) => ({ mount: c[5]!, totalBytes: Number(c[1]), usedBytes: Number(c[2]), freeBytes: Number(c[3]) }));
}
function osName(): string {
try {
const t = fs.readFileSync("/etc/os-release", "utf8");
return /^PRETTY_NAME="?([^"\n]+)"?/m.exec(t)?.[1] ?? `${os.type()} ${os.release()}`;
} catch {
return `${os.type()} ${os.release()}`;
}
}
const versionIn = (text: string | null) => (text ? /(\d+\.\d+(\.\d+)?)/.exec(text)?.[1] ?? null : null);
/** church.env → { app user → [{ church, product, names }] }, read as data like the script does. */
export function churchProcesses(sitesDir = paths.sites): Map<string, { church: string; product: agent.AgentStats["processes"][number]["product"]; names: string[] }[]> {
const byUser = new Map<string, { church: string; product: "events" | "accounts" | "website" | "app"; names: string[] }[]>();
let entries: string[];
try { entries = fs.readdirSync(sitesDir); } catch { return byUser; }
for (const church of entries) {
if (!/^[a-z][a-z0-9-]{0,39}$/.test(church)) continue;
let text: string;
try { text = fs.readFileSync(path.join(sitesDir, church, "church.env"), "utf8"); } catch { continue; }
const vars = new Map<string, string>();
for (const line of text.split(/\r?\n/)) {
const m = /^([A-Z][A-Z0-9_]*)=("([^"]*)"|'([^']*)'|([^#\s]*))/.exec(line);
if (m) vars.set(m[1]!, m[3] ?? m[4] ?? m[5] ?? "");
}
for (const product of ["accounts", "events", "website", "app"] as const) {
const p = product.toUpperCase();
const user = vars.get(`${p}_USER`);
const names = (vars.get(`${p}_PM2`) ?? "").split(/\s+/).filter(Boolean);
if (!user || !names.length || !/^[a-z_][a-z0-9_-]{0,31}$/.test(user)) continue;
const list = byUser.get(user) ?? [];
list.push({ church, product, names });
byUser.set(user, list);
}
}
return byUser;
}
interface Pm2Proc { name?: string; monit?: { memory?: number; cpu?: number }; pm2_env?: { status?: string; restart_time?: number; pm_uptime?: number } }
function pm2Running(user: string): boolean {
try {
const home = execFileSync("getent", ["passwd", user], { encoding: "utf8" }).split(":")[5];
const pid = Number(fs.readFileSync(`${home}/.pm2/pm2.pid`, "utf8").trim());
if (!pid) return false;
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async function pm2Processes(): Promise<agent.AgentStats["processes"]> {
const out: agent.AgentStats["processes"] = [];
for (const [user, installs] of churchProcesses()) {
// Only ask a daemon that's running: `pm2 jlist` would otherwise start an empty one inside this
// agent's service, which dies with the agent (found in the VM test).
if (!pm2Running(user)) continue;
const json = await run("sudo", ["-n", "-u", user, "-H", "--", "pm2", "jlist"]);
let list: Pm2Proc[];
try { list = JSON.parse(json ?? "[]") as Pm2Proc[]; } catch { list = []; }
for (const p of list) {
const owner = installs.find((i) => i.names.includes(p.name ?? ""));
out.push({
name: String(p.name ?? "?").slice(0, 100),
church: owner?.church ?? null,
product: owner?.product ?? null,
status: String(p.pm2_env?.status ?? "unknown").slice(0, 40),
memoryBytes: Number(p.monit?.memory ?? 0),
cpuPercent: Number(p.monit?.cpu ?? 0),
restarts: Math.max(0, Math.trunc(Number(p.pm2_env?.restart_time ?? 0))),
uptimeSeconds: p.pm2_env?.pm_uptime ? Math.max(0, (Date.now() - p.pm2_env.pm_uptime) / 1000) : 0,
});
}
}
return out.slice(0, 200);
}
/** A systemd unit is active; null when there's no systemctl. (is-active exits non-zero when inactive.) */
function active(unit: string): Promise<boolean | null> {
return new Promise((resolve) => {
execFile("systemctl", ["is-active", unit], { timeout: 10_000 }, (err, stdout) => {
if (err && (err as NodeJS.ErrnoException).code === "ENOENT") resolve(null);
else resolve(String(stdout).trim() === "active");
});
});
}
export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentStats> {
const read = (f: string) => { try { return fs.readFileSync(f, "utf8"); } catch { return ""; } };
const stat1 = read("/proc/stat");
await new Promise((r) => setTimeout(r, 1000));
const stat2 = read("/proc/stat");
const [load1, load5, load15] = os.loadavg();
const [diskList, postgres, frpc, processes, frpcRunning] = await Promise.all([
disks(),
run("psql", ["--version"]),
run("frpc", ["-v"]),
mode === "church" ? pm2Processes() : Promise.resolve([]),
mode === "church" ? active("frpc") : Promise.resolve(null),
]);
const stats: agent.AgentStats = {
schema: "crosscode.agent-stats/1",
at: new Date().toISOString(),
ram: parseMeminfo(read("/proc/meminfo")),
cpu: { percent: cpuPercent(stat1, stat2), load1: load1 ?? 0, load5: load5 ?? 0, load15: load15 ?? 0, cores: Math.max(1, os.cpus().length) },
disks: diskList,
uptimeSeconds: os.uptime(),
versions: { os: osName().slice(0, 200), node: process.versions.node, postgres: versionIn(postgres), frpc: versionIn(frpc), agent: AGENT_VERSION },
frpcRunning,
processes,
};
if (mode === "central") {
const frps = readFrps();
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
}
return stats;
}
+103
View File
@@ -0,0 +1,103 @@
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import type { agent } from "@crosscode/contracts";
import { paths } from "./paths";
/**
* update-agent (AGENT-1.0-PLAN §3): the newest agent@x.y.z is checked out and built next to the
* running copy, `current` is switched to it and the agent exits, so systemd starts the new one.
* A one-shot systemd timer switches back to `previous` unless the new agent clears
* update-pending.json by polling the Hub within 150 seconds.
*
* /opt/crosscode/agent/releases/<version>/ checkouts of the monorepo at agent@<version>
* /opt/crosscode/agent/current, previous symlinks to releases
* /opt/crosscode/agent/revert.sh written by the install script
*/
const REPO = process.env.CROSSCODE_REPO || "https://c-git.crosscode.co.za/joshua/crosscode-platform.git";
const CONFIRM_SECONDS = 150;
const pendingFile = () => path.join(paths.stateDir, "update-pending.json");
function exec(cmd: string, args: string[], cwd?: string, timeoutMs = 15 * 60_000): Promise<string> {
return new Promise((resolve, reject) => {
execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 20_000_000, env: { ...process.env, NODE_ENV: "development" } }, (err, stdout, stderr) => {
if (err) reject(new Error(`${cmd} ${args.join(" ")}: ${String(stderr).trim().split("\n").slice(-3).join(" ") || err.message}`));
else resolve(String(stdout));
});
});
}
export interface UpdateOutcome {
status: agent.JobStatus;
message: string;
steps: agent.ReportStep[];
result: Record<string, unknown>;
/** Exit after reporting, so systemd starts the new version. */
restart: boolean;
}
export async function updateAgent(tag: string, currentVersion: string): Promise<UpdateOutcome> {
const version = tag.replace(/^agent@/, "");
const steps: agent.ReportStep[] = [];
const step = async (name: string, fn: () => Promise<void>) => {
const s: agent.ReportStep = { name, startedAt: new Date().toISOString(), finishedAt: null, outcome: "ok" };
steps.push(s);
try {
await fn();
} catch (e) {
s.outcome = "failed";
s.detail = (e as Error).message.slice(0, 2000);
throw e;
} finally {
s.finishedAt = new Date().toISOString();
}
};
if (version === currentVersion) return { status: "succeeded", message: `Already on ${tag}.`, steps, result: { version }, restart: false };
const root = paths.agentRoot;
const dir = path.join(root, "releases", version);
try {
await step(`Checking out ${tag}`, async () => {
if (!fs.existsSync(path.join(dir, ".git"))) {
fs.mkdirSync(path.dirname(dir), { recursive: true });
await exec("git", ["clone", "--quiet", "--depth", "1", "--branch", tag, REPO, dir]);
}
});
await step("Installing and building", async () => {
await exec("npm", ["ci", "--no-audit", "--no-fund", "--include=dev", "--include-workspace-root", "-w", "packages/contracts", "-w", "apps/agent"], dir);
await exec("npm", ["run", "build", "-w", "packages/contracts"], dir);
await exec("npm", ["run", "build", "-w", "apps/agent"], dir);
});
await step("Checking the new build", async () => {
const out = await exec(process.execPath, [path.join(dir, "apps/agent/dist/cli.js"), "version"], dir, 30_000);
if (out.trim() !== version) throw new Error(`The new build says it's ${out.trim()}, not ${version}.`);
});
await step("Switching over", async () => {
const current = path.join(root, "current");
const previous = path.join(root, "previous");
const old = fs.readlinkSync(current);
fs.writeFileSync(pendingFile(), JSON.stringify({ from: currentVersion, to: version, at: new Date().toISOString() }), { mode: 0o600 });
replaceLink(previous, old);
replaceLink(current, dir);
// If the new agent doesn't poll within CONFIRM_SECONDS, revert.sh puts `previous` back.
await exec("systemd-run", [`--on-active=${CONFIRM_SECONDS}`, `--unit=crosscode-agent-revert-${Date.now()}`, path.join(root, "revert.sh")]);
});
} catch (e) {
return { status: "failed", message: `The agent wasn't updated: ${(e as Error).message}`, steps, result: { from: currentVersion, to: version }, restart: false };
}
return { status: "succeeded", message: `Switching to ${tag}; it confirms by polling within ${CONFIRM_SECONDS} seconds.`, steps, result: { from: currentVersion, to: version }, restart: true };
}
function replaceLink(link: string, target: string): void {
const tmp = `${link}.tmp-${process.pid}`;
fs.rmSync(tmp, { force: true });
fs.symlinkSync(target, tmp);
fs.renameSync(tmp, link);
}
/** Called after the first successful poll: this version works, so it stays. */
export function confirmUpdate(): void {
fs.rmSync(pendingFile(), { force: true });
}
+78
View File
@@ -0,0 +1,78 @@
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { verifyJob } from "@crosscode/contracts/signing";
import type { AgentConfig } from "./config";
import { paths } from "./paths";
/**
* Whether to run a job (AGENT-1.0-PLAN §4). Checked in this order, and a job is refused at the
* first check it fails:
* 1. it's an object with an id and type the agent can report on,
* 2. the signature verifies with the Hub key pinned when the server joined,
* 3. it's for this server,
* 4. it's within notBefore … expiresAt (an expired job is reported as `expired`, never run late),
* 5. its id hasn't been seen in the last 90 days (replays),
* 6. its type is one this agent runs (a central agent only runs check-ports, status, update-agent),
* 7. every argument passes that type's schema (unknown arguments refused).
*/
export type Verdict =
| { ok: true; job: agent.AgentJob }
| { ok: false; status: "refused" | "expired"; message: string; id: string | null; type: agent.JobType | null };
const SEEN_DAYS = 90;
/** Job ids already run or refused, with when (replay protection). */
export class SeenJobs {
private seen = new Map<string, number>();
constructor(private file = path.join(paths.stateDir, "seen-jobs.json")) {
try {
const data = JSON.parse(fs.readFileSync(this.file, "utf8")) as Record<string, number>;
for (const [id, at] of Object.entries(data)) this.seen.set(id, at);
} catch {
// First run, or an unreadable file: start empty (signatures and expiry still apply).
}
}
has(id: string): boolean {
return this.seen.has(id);
}
add(id: string, now = Date.now()): void {
this.seen.set(id, now);
const cutoff = now - SEEN_DAYS * 86_400_000;
for (const [k, at] of this.seen) if (at < cutoff) this.seen.delete(k);
fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
const tmp = `${this.file}.tmp-${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.seen)), { mode: 0o600 });
fs.renameSync(tmp, this.file);
}
}
const typeOf = (v: unknown): agent.JobType | null => (agent.jobTypeSchema.safeParse(v).success ? (v as agent.JobType) : null);
export function checkJob(raw: unknown, config: AgentConfig, seen: SeenJobs, now = new Date()): Verdict {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, status: "refused", message: "Not a job.", id: null, type: null };
const j = raw as Record<string, unknown>;
const id = typeof j.id === "string" && /^job_[A-Za-z0-9_-]{8,64}$/.test(j.id) ? j.id : null;
const type = typeOf(j.type);
const refuse = (message: string): Verdict => ({ ok: false, status: "refused", message, id, type });
if (!id) return refuse("The job has no valid id.");
if (!verifyJob(j, config.hubJobKey)) return refuse("The signature doesn't match the Hub's key.");
if (j.serverId !== config.serverId) return refuse(`The job is for ${String(j.serverId)}, not this server.`);
const notBefore = Date.parse(String(j.notBefore));
const expiresAt = Date.parse(String(j.expiresAt));
if (!Number.isFinite(notBefore) || !Number.isFinite(expiresAt) || expiresAt <= notBefore) return refuse("The job's times aren't valid.");
if (now.getTime() > expiresAt) return { ok: false, status: "expired", message: `The job expired at ${new Date(expiresAt).toISOString()}; it wasn't run.`, id, type };
// A minute's leeway for clocks that differ a little.
if (now.getTime() < notBefore - 60_000) return refuse(`The job isn't due until ${new Date(notBefore).toISOString()}.`);
if (seen.has(id)) return refuse("This job was already received (a replay).");
if (!type) return refuse(`Unknown job type ${JSON.stringify(j.type)}.`);
if (config.mode === "central" && !agent.CENTRAL_JOB_TYPES.includes(type)) return refuse(`A central agent doesn't run ${type} jobs.`);
const parsed = agent.agentJobSchema.safeParse(raw);
if (!parsed.success) {
const issue = parsed.error.issues[0];
return refuse(`The job's ${issue?.path.join(".") || "content"} isn't valid: ${issue?.message ?? "unknown problem"}.`);
}
return { ok: true, job: parsed.data };
}
+36
View File
@@ -0,0 +1,36 @@
import { agent } from "@crosscode/contracts";
import { crosscodeArgs } from "../src/command";
import { job } from "./helpers";
const parsed = (over: Record<string, unknown>) => agent.agentJobSchema.parse(job(over));
describe("crosscode arguments for each job", () => {
it("install: behind frp with the Hub's ports and the release", () => {
expect(crosscodeArgs(parsed({
type: "install",
args: { church: "hope", products: ["events"], versions: { events: "events@2.4.1" }, domains: { events: "events.hope.co.za" }, ports: { events: { web: 20010, api: 20011 } } },
}))).toEqual(["install", "hope", "--products", "events", "--domain", "hope.co.za", "--events-domain", "events.hope.co.za", "--api-port", "20011", "--web-port", "20010", "--frp", "--version", "events@2.4.1"]);
});
it("deploy, adopt, restart, uninstall, purge, status", () => {
expect(crosscodeArgs(parsed({}))).toEqual(["deploy", "hope", "events", "--version", "events@2.4.1"]);
expect(crosscodeArgs(parsed({ args: { church: "hope", products: ["events"], check: true } }))).toEqual(["deploy", "hope", "events", "--check"]);
expect(crosscodeArgs(parsed({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/hope-events", version: "events@2.2.0" } })))
.toEqual(["adopt", "hope", "--events-dir", "/var/www/hope-events", "--version", "events@2.2.0"]);
expect(crosscodeArgs(parsed({ type: "adopt-undo", args: { church: "hope" } }))).toEqual(["adopt", "hope", "--undo"]);
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
});
it("export writes to the file the agent gives", () => {
const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]);
});
it("the agent's own jobs run no crosscode command", () => {
expect(crosscodeArgs(parsed({ type: "check-ports", args: { ports: [20010] } }))).toBeNull();
expect(crosscodeArgs(parsed({ type: "update-agent", args: { version: "agent@1.0.1" } }))).toBeNull();
});
});
+44
View File
@@ -0,0 +1,44 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { generateEd25519, generateX25519, signJob } from "@crosscode/contracts/signing";
import type { AgentConfig } from "../src/config";
export const hubKeys = generateEd25519();
export const serverKeys = { ed25519: generateEd25519(), x25519: generateX25519() };
export const config: AgentConfig = {
hubUrl: "https://hub.test",
serverId: "srv_test00001",
mode: "church",
hubJobKey: hubKeys.publicKey,
pollSeconds: 30,
statsSeconds: 60,
joinedAt: "2026-11-20T00:00:00.000Z",
};
export const NOW = new Date("2026-11-20T12:05:00.000Z");
let n = 0;
export function job(over: Record<string, unknown> = {}, key = hubKeys.privateKeyPem) {
n++;
return signJob({
schema: "crosscode.agent-job/1",
id: `job_test${String(n).padStart(6, "0")}`,
serverId: config.serverId,
type: "deploy",
args: { church: "hope", products: ["events"], versions: ["events@2.4.1"] },
config: null,
notBefore: "2026-11-20T12:00:00.000Z",
expiresAt: "2026-11-20T12:15:00.000Z",
...over,
}, key);
}
/** A temporary state folder per test file. */
export function tempState(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-test-"));
process.env.CROSSCODE_AGENT_STATE_DIR = dir;
process.env.CROSSCODE_AGENT_RUN_DIR = path.join(dir, "run");
return dir;
}
+112
View File
@@ -0,0 +1,112 @@
import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { decryptExport } from "@crosscode/contracts/signing";
import { HubRequestError, type HubClient } from "../src/hub";
import { Agent } from "../src/loop";
import type { RunResult } from "../src/runner";
import { SeenJobs } from "../src/verify";
import { config, job, NOW, serverKeys, tempState } from "./helpers";
const state = tempState();
function fakeHub(jobs: unknown[]) {
const posts: { path: string; body: unknown }[] = [];
const puts: { path: string; body: Uint8Array }[] = [];
let down = false;
const hub: HubClient = {
async post(p, body) {
if (down) throw new HubRequestError("down", 0, "HUB_UNREACHABLE");
posts.push({ path: p, body });
if (p === "/api/agent/v1/poll") return { jobs: jobs.splice(0), pollSeconds: 30 };
return null;
},
async put(p, body) {
puts.push({ path: p, body });
return null;
},
};
return { hub, posts, puts, setDown: (v: boolean) => { down = v; } };
}
const ok = (over: Partial<RunResult> = {}): RunResult => ({ status: "succeeded", steps: [{ name: "x", startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: "ok" }], result: {}, log: ["==> done"], startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), ...over });
type Run = (args: string[], job: agent.AgentJob) => Promise<RunResult>;
function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>> = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok())) {
const h = fakeHub(jobs);
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, now: () => NOW });
return { a, run, ...h };
}
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
describe("the agent loop", () => {
it("runs a valid job once and reports it", async () => {
const j = job();
const { a, run, posts } = make([j, j]);
await a.pollOnce();
expect(run).toHaveBeenCalledTimes(1);
expect(run.mock.calls[0]).toEqual([["deploy", "hope", "events", "--version", "events@2.4.1"], expect.objectContaining({ id: j.id })]);
// The second copy is a replay: refused quietly (the first one's report already went).
const rs = reports(posts);
expect(rs.map((r) => [r.jobId, r.status])).toEqual([[j.id, "succeeded"]]);
expect(agent.agentReportSchema.safeParse(rs[0]).success).toBe(true);
});
it("reports refused and expired jobs without running them", async () => {
const forged = { ...job(), signature: "A".repeat(86) };
const late = job({ expiresAt: "2026-11-20T12:01:00.000Z", notBefore: "2026-11-20T11:00:00.000Z" });
const { a, run, posts } = make([forged, late]);
await a.pollOnce();
expect(run).not.toHaveBeenCalled();
expect(reports(posts).map((r) => r.status)).toEqual(["refused", "expired"]);
});
it("keeps a report it can't send and sends it on the next poll", async () => {
const j = job();
let setDownLater: (v: boolean) => void = () => {};
const { a, posts, setDown } = make([j], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { setDownLater(true); return ok(); }));
setDownLater = setDown;
await a.pollOnce();
expect(reports(posts)).toEqual([]);
expect(fs.readdirSync(path.join(state, "outbox"))).toContain(`${j.id}.json`);
setDown(false);
await a.pollOnce();
expect(reports(posts).map((r) => r.jobId)).toEqual([j.id]);
expect(fs.readdirSync(path.join(state, "outbox"))).toEqual([]);
});
it("backs off while the Hub is unreachable", async () => {
const { a, setDown } = make([]);
setDown(true);
expect(await a.pollOnce()).toBe(60);
expect(await a.pollOnce()).toBe(120);
setDown(false);
expect(await a.pollOnce()).toBe(30);
});
it("export: encrypts the ZIP, uploads it, and only the report carries the key", async () => {
const j = job({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async (args: string[]) => {
fs.writeFileSync(args[3]!, "PK zip bytes");
return ok({ result: { file: args[3], bytes: 12 } });
});
const { a, puts, posts } = make([j], run);
await a.pollOnce();
expect(puts).toHaveLength(1);
expect(puts[0]!.path).toBe("/api/agent/v1/exports/exp_abcdefgh");
const r = reports(posts)[0]!;
expect(r.status).toBe("succeeded");
const key = r.result.key as string;
expect(decryptExport(puts[0]!.body, key).toString()).toBe("PK zip bytes");
expect(Buffer.from(puts[0]!.body).includes(Buffer.from("PK zip"))).toBe(false);
expect(fs.readdirSync(path.join(state, "exports"))).toEqual([]);
});
it("a job that throws is reported as failed", async () => {
const { a, posts } = make([job()], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { throw new Error("boom"); }));
await a.pollOnce();
expect(reports(posts)[0]).toMatchObject({ status: "failed", message: "boom" });
});
});
@@ -0,0 +1,72 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { config, serverKeys } from "./helpers";
/**
* AGENT-1.0-PLAN §2 rule 1: the agent listens on nothing. Starts the built agent (dist/cli.js)
* against a fake Hub served by this test, lets it poll, then compares the agent's open sockets
* with every listening TCP socket the kernel knows (/proc/net/tcp, tcp6). Linux only (the
* servers); run `npm run build -w apps/agent` first.
*/
const cli = path.join(__dirname, "..", "dist", "cli.js");
const linux = process.platform === "linux" && fs.existsSync(cli);
const maybe = linux ? it : it.skip;
function listeningInodes(): Set<string> {
const out = new Set<string>();
for (const f of ["/proc/net/tcp", "/proc/net/tcp6"]) {
let text: string;
try { text = fs.readFileSync(f, "utf8"); } catch { continue; }
for (const line of text.split("\n").slice(1)) {
const cols = line.trim().split(/\s+/);
if (cols[3] === "0A") out.add(cols[9]!); // 0A = LISTEN
}
}
return out;
}
function socketInodes(pid: number): Set<string> {
const out = new Set<string>();
for (const fd of fs.readdirSync(`/proc/${pid}/fd`)) {
try {
const m = /^socket:\[(\d+)\]$/.exec(fs.readlinkSync(`/proc/${pid}/fd/${fd}`));
if (m) out.add(m[1]!);
} catch { /* closed meanwhile */ }
}
return out;
}
describe("the running agent", () => {
maybe("has no listening socket", async () => {
let polls = 0;
const hub = http.createServer((req, res) => {
if (req.url === "/api/agent/v1/poll") polls++;
res.setHeader("content-type", "application/json");
res.end(req.url === "/api/agent/v1/poll" ? JSON.stringify({ jobs: [], pollSeconds: 5 }) : "{}");
});
await new Promise<void>((r) => hub.listen(0, "127.0.0.1", r));
const port = (hub.address() as { port: number }).port;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-nolisten-"));
fs.writeFileSync(path.join(dir, "agent.json"), JSON.stringify({ ...config, hubUrl: `http://127.0.0.1:${port}`, pollSeconds: 5, statsSeconds: 15 }));
fs.writeFileSync(path.join(dir, "agent-ed25519.pem"), serverKeys.ed25519.privateKeyPem);
fs.writeFileSync(path.join(dir, "agent-x25519.pem"), serverKeys.x25519.privateKeyPem);
const child = spawn(process.execPath, [cli, "run"], {
env: { ...process.env, CROSSCODE_AGENT_CONFIG_DIR: dir, CROSSCODE_AGENT_STATE_DIR: path.join(dir, "state"), CROSSCODE_AGENT_ALLOW_NON_ROOT: "1", CROSSCODE_SITES: path.join(dir, "sites") },
stdio: "ignore",
});
try {
for (let i = 0; i < 40 && polls === 0; i++) await new Promise((r) => setTimeout(r, 250));
expect(polls).toBeGreaterThan(0);
const listening = listeningInodes();
const mine = [...socketInodes(child.pid!)].filter((inode) => listening.has(inode));
expect(mine).toEqual([]);
} finally {
child.kill("SIGTERM");
hub.close();
}
}, 30_000);
});
+79
View File
@@ -0,0 +1,79 @@
import { checkPorts, parseFrpsIni, parseSs, portAllowed } from "../src/central";
import { LogTail, redact } from "../src/redact";
import { churchProcesses, cpuPercent, parseMeminfo } from "../src/stats";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
describe("log lines are redacted before they leave the server", () => {
it.each([
["Error: connect postgresql://hope_events:Zx81kLmQ@localhost:5432/hope_events", "postgresql://hope_events:***@localhost"],
["JWT_SECRET=abcdefghijklmnop", "JWT_SECRET=***"],
['DB_PASSWORD: "hunter2 x"', "DB_PASSWORD: ***"],
["Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig", "Authorization: Bearer ***"],
["licence CEH-7K2M-9QXA-P4RT-WD8C refused", "CEH-****"],
["token a3f9c1d27b8e4f60a3f9c1d27b8e4f60a3f9c1d2", "token ***"],
])("%s", (line, expected) => {
const out = redact(line);
expect(out).toContain(expected);
});
it("keeps ordinary lines", () => {
expect(redact("==> events: migrations")).toBe("==> events: migrations");
});
it("keeps only the last lines", () => {
const t = new LogTail(3);
t.push("1\n2\n3\n4");
t.push("\n5\n");
expect(t.end()).toEqual(["3", "4", "5"]);
});
});
describe("central server checks", () => {
const ini = "[common]\nbind_port = 7000\nproxy_bind_addr = 127.0.0.1\nallow_ports = 20000-29999,3000\n\n[web]\nproxy_bind_addr = 0.0.0.0\n";
it("reads [common] only", () => {
expect(parseFrpsIni(ini)).toEqual({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3000" });
});
it("allow_ports ranges", () => {
expect(portAllowed(20010, "20000-29999,3000")).toBe(true);
expect(portAllowed(3000, "20000-29999,3000")).toBe(true);
expect(portAllowed(5000, "20000-29999,3000")).toBe(false);
expect(portAllowed(5000, null)).toBe(true);
});
it("ports must be allowed, open and bound to 127.0.0.1 only", () => {
const ss = "LISTEN 0 4096 127.0.0.1:20010 0.0.0.0:*\nLISTEN 0 4096 0.0.0.0:20011 0.0.0.0:*\nLISTEN 0 4096 [::1]:20012 [::]:*\n";
const res = checkPorts([20010, 20011, 20012, 20013], parseFrpsIni(ini), parseSs(ss));
expect(res.ports.map((p) => [p.port, p.ok])).toEqual([[20010, true], [20011, false], [20012, true], [20013, false]]);
expect(res.warnings.join(" ")).toMatch(/20011 is open on more than 127.0.0.1/);
expect(res.warnings.join(" ")).toMatch(/20013 isn't open/);
});
it("warns when proxy_bind_addr is missing", () => {
const res = checkPorts([20010], parseFrpsIni("[common]\nbind_port = 7000\n"), parseSs("LISTEN 0 1 127.0.0.1:20010 0.0.0.0:*"));
expect(res.warnings.join(" ")).toMatch(/proxy_bind_addr is not set/);
});
});
describe("stats", () => {
it("RAM from /proc/meminfo", () => {
const r = parseMeminfo("MemTotal: 4000000 kB\nMemFree: 100 kB\nMemAvailable: 1000000 kB\nSwapTotal: 2000 kB\nSwapFree: 500 kB\n");
expect(r).toEqual({ totalBytes: 4096000000, usedBytes: 3072000000, availableBytes: 1024000000, swapTotalBytes: 2048000, swapUsedBytes: 1536000 });
});
it("CPU % between two readings", () => {
expect(cpuPercent("cpu 100 0 100 700 100 0 0 0", "cpu 150 0 150 750 150 0 0 0")).toBe(50);
});
it("PM2 processes are matched to churches through church.env", () => {
const sites = fs.mkdtempSync(path.join(os.tmpdir(), "sites-"));
fs.mkdirSync(path.join(sites, "hope"));
fs.writeFileSync(path.join(sites, "hope", "church.env"), 'CHURCH=hope\nEVENTS_USER=cc-hope\nEVENTS_PM2="hope-events-backend hope-events-frontend"\n');
fs.mkdirSync(path.join(sites, "Bad Name"));
const map = churchProcesses(sites);
expect([...map.entries()]).toEqual([["cc-hope", [{ church: "hope", product: "events", names: ["hope-events-backend", "hope-events-frontend"] }]]]);
});
});
+61
View File
@@ -0,0 +1,61 @@
import path from "node:path";
import { generateEd25519 } from "@crosscode/contracts/signing";
import { checkJob, SeenJobs } from "../src/verify";
import { config, job, NOW, tempState } from "./helpers";
const dir = tempState();
const fresh = () => new SeenJobs(path.join(dir, `seen-${Math.random()}.json`));
describe("checking a job (AGENT-1.0-PLAN §4)", () => {
it("accepts a signed job for this server, in its window", () => {
expect(checkJob(job(), config, fresh(), NOW)).toMatchObject({ ok: true });
});
it("refuses a job signed with another key", () => {
expect(checkJob(job({}, generateEd25519().privateKeyPem), config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused", message: expect.stringContaining("signature") });
});
it("refuses a job whose content was changed after signing", () => {
const j = job();
expect(checkJob({ ...j, args: { ...j.args, church: "other" } }, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
});
it("refuses a job for another server", () => {
expect(checkJob(job({ serverId: "srv_other0001" }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("not this server") });
});
it("reports an expired job as expired, and never runs it", () => {
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T12:16:00.000Z"))).toMatchObject({ ok: false, status: "expired" });
});
it("refuses a job that isn't due yet (beyond a minute of clock difference)", () => {
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:58:00.000Z"))).toMatchObject({ ok: false, status: "refused" });
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:59:30.000Z"))).toMatchObject({ ok: true });
});
it("refuses a replayed job, also after a restart", () => {
const file = path.join(dir, "seen-replay.json");
const seen = new SeenJobs(file);
const j = job();
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: true });
seen.add(j.id);
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
expect(checkJob(j, config, new SeenJobs(file), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
});
it("refuses an unknown type, and arguments with shell characters", () => {
expect(checkJob(job({ type: "shell", args: { command: "id" } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("Unknown job type") });
expect(checkJob(job({ args: { church: "hope;reboot", products: ["events"] } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("isn't valid") });
expect(checkJob(job({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/$(id)" } }), config, fresh(), NOW)).toMatchObject({ ok: false });
});
it("a central agent only runs check-ports, status and update-agent", () => {
const central = { ...config, mode: "central" as const };
expect(checkJob(job(), central, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("central") });
expect(checkJob(job({ type: "check-ports", args: { ports: [20010, 20011] } }), central, fresh(), NOW)).toMatchObject({ ok: true });
});
it("refuses things that aren't jobs", () => {
for (const raw of [null, "job", [], { id: "nope" }]) expect(checkJob(raw, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"types": ["node", "jest"],
"declaration": false
},
"include": ["src", "tests", "tsup.config.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "tsup";
// One self-contained file (contracts and zod bundled in), so a server needs no node_modules to run
// the agent: /opt/crosscode/agent/current/apps/agent/dist/cli.js.
export default defineConfig({
entry: ["src/cli.ts"],
format: ["cjs"],
platform: "node",
target: "node24",
noExternal: [/.*/],
clean: true,
sourcemap: true,
banner: { js: "#!/usr/bin/env node" },
});
+50
View File
@@ -0,0 +1,50 @@
# dependencies
node_modules/
# env files (never commit real secrets — .env.example files are fine)
.env
.env.*
!.env.example
# IDE
.idea/
.vscode/
# next.js
.next/
out/
# build output
dist/
build/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
*.log
# typescript
*.tsbuildinfo
# OS
.DS_Store
Thumbs.db
# this install's PM2 config (made from ecosystem.config.example.js; deploys never touch it)
/ecosystem.config.js
# misc scratch / generated files
temp/
backend/public/uploads/
backend/backups/
hope-events-deployment-setup.txt
# runtime data stores (mutated by the running app, not source)
backend/data/scheduled-emails.json
backend/data/banner.json
# end-to-end tests
e2e/.data/
e2e/report/
e2e/test-results/
frontend/.next-e2e/
File diff suppressed because it is too large Load Diff
+382
View File
@@ -0,0 +1,382 @@
# Deploying Cross Events behind frp
This guide is for a server that is **not reachable from the internet directly**: it runs
`frpc`, which opens a tunnel to `frps` on a public server (the "VPS"). Visitors reach the VPS,
and frp carries the traffic through to this server. The frp client config lives at
**`/etc/frp/frpc.ini`**.
For a server with a public IP, `scripts/install.sh` does everything (see the README). Behind frp
it needs a few changes, because:
- **HTTPS can't be set up by the installer.** DNS points at the VPS, not at this server, so
`certbot --nginx` can't work the usual way. HTTPS ends either on the VPS or in `frpc`.
- **There are more proxies in the way.** The app must be told which of them to trust, or it sees
every visitor as `127.0.0.1` (rate limiting then treats everyone as one person, and PayFast
payment notifications fail their IP check).
- **The app must know the site is HTTPS** even though nginx on this server only speaks HTTP;
otherwise it builds `http://` links (event images, payment return URLs).
## 1. How the traffic flows
Pick the setup that matches how your other frp sites get HTTPS.
**A. HTTPS ends on the VPS** (nginx/Caddy on the VPS holds the certificate) — recommended if the
VPS already does this for other sites:
```
visitor ──https──▶ VPS nginx/Caddy ──http──▶ frps (vhost_http_port) ══tunnel══▶ frpc ──▶ nginx :80 ──▶ app
```
**B. HTTPS ends in frpc** (the VPS only runs frps; the certificate lives on this server and
frpc's `https2http` plugin uses it):
```
visitor ──https──▶ frps (vhost_https_port) ══tunnel══▶ frpc https2http ──▶ nginx 127.0.0.1:8080 ──▶ app
visitor ──http───▶ frps (vhost_http_port) ══tunnel══▶ frpc ──▶ nginx :80 (certificate check + redirect to https)
```
On this server, nginx sends `/api`, `/uploads`, `/health` and `/docs` to the backend (port 5000)
and everything else to the Next.js site (port 3000), the same as a normal install.
### One address, one rule (2.2.0 and later)
From 2.2.0 everything the backend serves is under **`/api`**: the API (`/api/v2`), the status page
(`/api`), health (`/api/health`), the API reference (`/api/docs/v2`) and uploaded files
(`/api/uploads/…`). So the site and its API share one address (`events.yourchurch.org`, no
separate `events-api.` record), and a web server or panel such as FastPanel needs a single
rule:
| Path | Goes to |
|------|---------|
| `/api` and everything under it | the backend, `http://127.0.0.1:5000` |
| everything else | the frontend, `http://127.0.0.1:3000` |
Set `BACKEND_URL` (backend `.env`) and `NEXT_PUBLIC_API_URL` (frontend `.env.production`) to the
same `https://` address as `FRONTEND_URL`, then rebuild the frontend. The old paths (`/health`,
`/docs/v2`, `/uploads/…`) still answer on the backend's port, so a site with a separate API
address keeps working unchanged. With only `/api` routed, links made before 2.2.0 that point at
`https://<site>/uploads/…` stop working (they aren't stored that way, but could be in an old
email); keep the four-path rule above if that matters. Pictures, logos and attachments are all
given out as `/api/uploads/…` from 2.2.0.
## 2. Before you start
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
a systemd service, usually `frpc.service`).
- The site's DNS record (e.g. `events.yourchurch.org`) points at the **VPS**.
- On the VPS, `frps.ini` has `vhost_http_port` set (and `vhost_https_port` for setup B). Note
the values; you need them below.
- The licence key for this site from the Cross Events Hub.
## 3. Install the app
On this server, as root, run the installer **without** its certificate step:
```bash
curl -fsSLO https://c-git.crosscode.co.za/joshua/hope-events/raw/branch/main/scripts/install.sh
sudo bash install.sh --domain events.yourchurch.org --no-ssl --version v1.41.2
```
It installs Node 24 LTS, PostgreSQL, PM2 and nginx, creates the database, writes the config, builds
and starts the app (in `/opt/hope-events`, run by the `hopeevents` user). Use `--name`, `--dir`,
`--web-port` and `--api-port` if other apps already use those names or ports; adjust the ports
below to match.
### Switch the URLs to https
With `--no-ssl` the installer writes `http://` addresses. Change them to `https://`:
```bash
cd /opt/hope-events
sudo sed -i 's#=http://#=https://#' backend/.env frontend/.env.production
grep -E 'URL=' backend/.env frontend/.env.production # all should now start with https://
```
While `backend/.env` is open, set which proxies to trust (all of them run on loopback in both
setups; see [step 7](#7-check-that-visitor-addresses-come-through) to confirm):
```bash
sudo sed -i 's#^TRUST_PROXY=.*#TRUST_PROXY=loopback#' backend/.env
```
`NEXT_PUBLIC_API_URL` is baked in when the site is built, so rebuild the frontend and restart:
```bash
sudo -u hopeevents -H bash -lc 'cd /opt/hope-events/frontend && npm run build'
sudo -u hopeevents -H bash -lc 'cd /opt/hope-events && pm2 reload ecosystem.config.js --update-env'
```
Keep `JWT_SECRET` in `backend/.env` as it is: it also encrypts the secrets stored in the
database (SMTP, payment keys).
## 4. nginx on this server
The installer wrote `/etc/nginx/sites-available/hope-events`. Replace it with the version for
your setup, changing the domain (and the ports if you changed them).
### Setup A (HTTPS on the VPS)
```nginx
# Shows the forwarded-for chain in the access log (see step 7). Safe to keep.
log_format hope_proxy '$remote_addr xff="$http_x_forwarded_for" "$request" $status';
server {
listen 80;
server_name events.yourchurch.org;
client_max_body_size 25m;
access_log /var/log/nginx/hope-events.access.log hope_proxy;
# Visitors only reach this through the VPS over HTTPS, so tell the app so.
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
```
The VPS nginx/Caddy must redirect plain HTTP to HTTPS and pass the `Host` header through to frps
unchanged (frps picks the site by its host name). For nginx on the VPS, roughly:
```nginx
server {
listen 443 ssl;
server_name events.yourchurch.org;
# ssl_certificate / ssl_certificate_key from certbot on the VPS
client_max_body_size 25m;
location / {
proxy_pass http://127.0.0.1:8080; # frps vhost_http_port
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
```
### Setup B (HTTPS in frpc)
Port 80 only answers certificate checks and redirects everything else; the real site is on
`127.0.0.1:8080`, which only frpc's `https2http` plugin reaches.
```nginx
log_format hope_proxy '$remote_addr xff="$http_x_forwarded_for" "$request" $status';
server {
listen 80;
server_name events.yourchurch.org;
location /.well-known/acme-challenge/ { root /var/www/certbot; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 127.0.0.1:8080;
server_name events.yourchurch.org;
client_max_body_size 25m;
access_log /var/log/nginx/hope-events.access.log hope_proxy;
location ~ ^/(api|uploads|health|docs)(/|$) {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
```
Then, for either setup:
```bash
sudo mkdir -p /var/www/certbot # setup B only
sudo nginx -t && sudo systemctl reload nginx
```
## 5. frpc: `/etc/frp/frpc.ini`
Back it up first, then **add** a section for the site below the existing ones. Leave `[common]`
(server address, port, token) and the other sections as they are. Section names must be unique
across everything connected to your frps.
```bash
sudo cp /etc/frp/frpc.ini /etc/frp/frpc.ini.bak-$(date +%F)
sudo nano /etc/frp/frpc.ini
```
### Setup A
```ini
[hope-events-http]
type = http
local_ip = 127.0.0.1
local_port = 80
custom_domains = events.yourchurch.org
```
### Setup B
```ini
# Plain HTTP: certificate checks and the redirect to https
[hope-events-http]
type = http
local_ip = 127.0.0.1
local_port = 80
custom_domains = events.yourchurch.org
# HTTPS: frpc holds the certificate and passes plain HTTP to nginx on 127.0.0.1:8080
[hope-events-https]
type = https
custom_domains = events.yourchurch.org
plugin = https2http
plugin_local_addr = 127.0.0.1:8080
plugin_crt_path = /etc/letsencrypt/live/events.yourchurch.org/fullchain.pem
plugin_key_path = /etc/letsencrypt/live/events.yourchurch.org/privkey.pem
plugin_header_X-Forwarded-Proto = https
```
Restart frpc and check it registered the new sections without errors:
```bash
sudo systemctl restart frpc
sudo journalctl -u frpc -n 30 --no-pager # look for "start proxy success" for each section
```
> Newer frp releases (0.52+) prefer `frpc.toml`, but still read `.ini`. Don't mix the two: if
> your service already uses `frpc.ini`, keep adding to it.
### Certificate (setup B only)
Request it through the tunnel with the webroot method (not `--nginx`, which would rewrite the
nginx config), then have renewals restart frpc so it loads the new certificate:
```bash
sudo apt-get install -y certbot
sudo certbot certonly --webroot -w /var/www/certbot -d events.yourchurch.org \
-m you@yourchurch.org --agree-tos --non-interactive
echo 'systemctl restart frpc' | sudo tee /etc/letsencrypt/renewal-hooks/deploy/restart-frpc.sh
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/restart-frpc.sh
sudo systemctl restart frpc
```
frpc needs to be able to read the certificate files (it does when it runs as root, the usual
setup). If the `[hope-events-https]` section fails to start, check `journalctl -u frpc`.
## 6. Finish in the browser
1. Open `https://events.yourchurch.org/api/health` (`/health` before 2.2.0) — it should answer with the version.
2. Open `https://events.yourchurch.org/setup`: create the admin account.
3. **Site settings → Licence**: enter the licence key to connect to the Hub. The site checks in
every 15 minutes from then on (outgoing HTTPS to `events-hub.crosscode.co.za`, which frp
doesn't affect).
4. Configure SMTP, payments (Yoco/PayFast webhooks use the `https://` `BACKEND_URL`), branding,
etc. in Site settings.
## 7. Check that visitor addresses come through
Open the site from your phone (on mobile data, so it isn't your own network), then on the
server:
```bash
sudo tail -n 5 /var/log/nginx/hope-events.access.log
```
The `xff="…"` part is what the app sees, with nginx's own entry added at the end:
- `xff="<your phone's IP>, 127.0.0.1"` (only `127.0.0.1` after the real address): good,
`TRUST_PROXY=loopback` is right.
- `xff="<your phone's IP>, 203.0.113.10"` (a non-local address after it, e.g. the VPS's): add
that address: `TRUST_PROXY=loopback,203.0.113.10`, then
`pm2 reload ecosystem.config.js --update-env`.
- Your phone's IP doesn't appear at all: frp isn't passing the visitor's address on (can happen
with setup B on some frp versions). Rate limiting and the PayFast IP check will then misbehave.
Fix it by moving TLS to the VPS (setup A), or with frp's `proxy_protocol_version = v2` on the
frpc section plus nginx's `listen … proxy_protocol` and `set_real_ip_from 127.0.0.1;
real_ip_header proxy_protocol;`.
The backend logs the setting it uses at startup: `pm2 logs hope-events-backend | grep trust`.
## 8. Updating
Nothing about frp changes for updates. On the server:
```bash
cd /opt/hope-events
sudo -u hopeevents -H bash scripts/deploy.sh v1.41.2 # or no tag for the latest main
```
It backs up the database, checks out the release, installs, migrates, builds (the backend too,
since 1.51.0) and reloads PM2,
and goes back to the previous version if anything fails first. `backend/.env`,
`frontend/.env.production`, `ecosystem.config.js` and the nginx/frpc configs are not in git, so
updates keep your changes from this guide.
Since 1.52.2 it first checks for files in the install folder that were changed or added by hand
(e.g. by a setup wizard run on the server) and stops, listing them, before it backs anything up
or checks anything out: they would be built into the release, or block the checkout. Move added
files out of the folder and put changed ones back with `git checkout -- <file>`, or deploy anyway
with `ALLOW_LOCAL_CHANGES=1`. To check without deploying:
```bash
sudo -u hopeevents -H bash scripts/deploy.sh --check
```
An install still on an older release can run the new check without updating anything — fetch the
script on its own and run it from the install folder:
```bash
git fetch -q origin && git show origin/main:scripts/deploy.sh > /tmp/deploy.sh
bash /tmp/deploy.sh --check
```
### Upgrading Node
Node 20 stopped getting security fixes in April 2026; Cross Events runs on Node 24 LTS (supported
until April 2028). `deploy.sh` warns when a server is still on an older Node. To upgrade:
```bash
node -v # what you have now
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo bash -
sudo apt-get install -y nodejs # replaces the old Node
sudo npm install -g pm2 # PM2 for the new Node
cd /opt/hope-events
sudo -u hopeevents -H pm2 update # restart PM2's daemon on the new Node
sudo -u hopeevents -H bash scripts/deploy.sh v1.51.4 # reinstall packages and rebuild for Node 24
```
Use the version you're on (or a newer one) in the last line — the deploy reinstalls every package
and rebuilds, which a Node upgrade needs.
## Troubleshooting
| Symptom | Likely cause |
| --- | --- |
| frps shows "404 Not Found" page | The `custom_domains` value doesn't match the address typed, or frpc didn't start that section (`journalctl -u frpc`). |
| 502 Bad Gateway | nginx is up but the app isn't: `sudo -u hopeevents pm2 ls` and `pm2 logs`. |
| Site loads but login/API calls fail (CORS) | `FRONTEND_URL` in `backend/.env` is still `http://`, or the frontend wasn't rebuilt after changing `NEXT_PUBLIC_API_URL`. |
| Images or links use `http://` (browser "mixed content" warnings) | nginx isn't sending `X-Forwarded-Proto https`, or `TRUST_PROXY` isn't set. |
| "Too many requests" for everyone at once | All visitors look like one address: see step 7. |
| PayFast payments stay pending | Same as above: the PayFast notification's IP check sees the proxy, not PayFast. |
| Uploads over ~1 MB fail | `client_max_body_size` missing on this server's nginx or the VPS's. |
| Redirect loop (setup B) | The site's `server` block is on port 80 instead of `127.0.0.1:8080`, or `plugin_local_addr` points at port 80. |
+962
View File
@@ -0,0 +1,962 @@
# Cross Events — Feature Overview
A complete map of what the platform does, grouped by who uses it. For setup and
deployment see [README.md](./README.md); for the API see
[backend/API_DOCUMENTATION.md](./backend/API_DOCUMENTATION.md); for setting
defaults see [SETTINGS.md](./SETTINGS.md); for history see
[CHANGELOG.md](./CHANGELOG.md).
**Stack:** Next.js (React, Tailwind, shadcn/ui) frontend · Express + Prisma +
PostgreSQL backend · Yoco for card payments · SMTP for email · WAWP for
WhatsApp · PM2 for process management · optional Sentry for error monitoring.
---
## Contents
1. [Roles](#roles)
2. [Public site](#public-site)
3. [Events](#events)
4. [Registration](#registration)
5. [Payments, donations & refunds](#payments-donations--refunds)
6. [Tickets & check-in](#tickets--check-in)
7. [Attendee forms](#attendee-forms)
8. [Messaging & notifications](#messaging--notifications)
9. [User dashboard (My Events)](#user-dashboard-my-events)
10. [Staff tools](#staff-tools)
11. [Supervisor tools](#supervisor-tools)
12. [Admin tools](#admin-tools)
13. [Cashup & event costs](#cashup--event-costs)
14. [Reports](#reports)
15. [Site settings & setup wizard](#site-settings--setup-wizard)
16. [Event series](#event-series)
17. [Multi-campus](#multi-campus)
18. [Kids check-in](#kids-check-in)
19. [Volunteer rosters](#volunteer-rosters)
20. [Accounts & security](#accounts--security)
21. [Privacy (POPIA)](#privacy-popia)
22. [Accessibility](#accessibility)
23. [Help system](#help-system)
24. [Background jobs](#background-jobs)
25. [Operations](#operations)
26. [Page map](#page-map)
---
## Roles
Four roles, each including everything the roles below it can do:
| Role | Can do |
|------|--------|
| **User** | Browse events, register, pay, donate, view tickets, fill in forms, manage their own profile |
| **Staff** | Scan tickets, view/print event tickets, view registrations and form responses |
| **Supervisor** | Create and manage events, record payments/refunds, assign donations, at-the-door desk, manual registration, bulk email/WhatsApp, reports, site banner, self-service kiosk |
| **Admin** | Manage users and roles, all registrations, event costs and cashup (close/reopen events), audit log, site settings, WhatsApp connection, backups |
---
## Public site
- **Home page** — hero section with the organisation's name and branding, upcoming
and in-progress events, and a "Join Us" button (becomes "My Dashboard" when
logged in).
- **Events list** (`/events`) — event cards with picture, dates, location,
price, and a Register / Sold Out / Contact us button. A diagonal "Early bird"
ribbon in the top-right corner while an early-bird tier is running and
registration is open.
- **Event detail** (`/events/[id]`) — description, ticket options with
variant and early-bird pricing, low-stock and sold-out badges, downloadable
attachments, embedded Google Map with "Directions" link, and an
**Add to calendar** (`.ics`) button.
- **Short links** — events can have an alias (e.g. `/camp-2025`) that redirects
to the event. Only plausible aliases hit the database, so bot probes are
rejected cheaply.
- **Contact page** (`/contact`) — organisation email, phone, address and map.
- **Legal pages** — Terms of Use and Privacy Policy, filled from Site Settings.
- **Site banner** — a site-wide announcement bar set by supervisors.
- **Lockdown rules** (`/lockdown-rules`) — static rules page for the youth
lockdown event.
- **SEO** — `sitemap.xml` (every public page and event), `robots.txt`, and
Open Graph/Twitter link-preview metadata.
- **Theming** — brand colours, logo and favicon come from Site Settings.
---
## Events
Created and edited by supervisors through a 9-step wizard: **Basic Details →
Items & Pricing → Sections → Form → Visibility → Notifications → Attachments →
Feedback → Attendance**.
- **Basic details** — title, description, start/end dates, registration
deadline, picture (upload or URL), location (defaults to the org's address),
contact person.
- **Copy an event** — "Copy" on an event card opens the editor filled in from that
event (details, campus, sessions, options, variants, early birds, sections, form,
notification recipients, feedback questions, certificates, reminders). Setting
the **New start** moves every date with it (end, sessions, registration deadline,
early-bird deadlines, feedback date). Allocation groups are copied on save, and
for admins the planned costs (matched to options by name). Not copied:
registrations, coupons, attachments, the short link, the go-live time, kids
check-in and volunteer roles.
- **Contact-only events** — for things like baptisms: shown publicly with a
"Contact us" popup instead of registration, with no tickets.
- **Multi-day events (sessions)** — one event on several dates, e.g. every
Wednesday 18:30–20:30 for 5 weeks. A repeat pattern (daily/weekly, every N,
chosen weekdays, a number of sessions or an end date) creates the sessions,
which can then be edited one by one (label, times, location), added to, or
cancelled (kept for history; one with check-ins can't be deleted). People
register and pay once and get one ticket. The event page shows the schedule
with the next session highlighted; cards show "5 sessions · Wed 4 Nov – Wed
2 Dec" and stay listed until the last session. Calendar files get one entry
per session. Saving moved or cancelled sessions offers to message attendees.
- **Pick sessions** (multi-day) — instead of the whole course, people can choose
which sessions to come to (day passes, drop-in classes). Tickets set to "Pick
sessions" are priced and bought per session — one line and one ticket per session,
bookable until the session starts (staff: until it ends) — alongside optional
whole-course tickets. Sessions can have a capacity (picked places plus whole-course
tickets); a per-session ticket's stock limit is places per session. Picked tickets
only scan on their own session; reminders, the register and certificates follow
the sessions each person booked. "All sessions" tickets on such an event also show
the sessions: people tick the ones they'll come to and pay the ticket's one price; the
ticket scans, reminds and counts towards capacity for those sessions only. The waitlist
works per session (a full session shows "Join waitlist"). Bookable from the registration page, Manual registration,
At the door (today's session is preselected) and the kiosk. Not available on youth
events.
- **Late joining** (multi-day) — registration closes when the first session
starts, or later (until session N) with late joining on. Late joiners pay
full price, a pro-rata price for the sessions left (rounded to the nearest
R10), or a fixed late price — main tickets only.
- **Completion certificates** — optional per event: four designs (Classic,
Modern, Church, Kids), custom wording with placeholders, signature name/role/
image, and a completion rule (every session, at least N sessions, or N%).
Issued automatically when the event ends; each has a code and QR code checked
on a public verify page.
- **Ticket options** — multiple options per event (e.g. Adult, Child, Dinner,
T-shirt), each with a price and optional **stock limit**. One option is marked
as the main ticket, which is what gets checked in at the door.
- **Variants** — sub-types of an option (sizes, colours, Adult/Child/VIP), each
with an optional price override and its own stock limit.
- **Early-bird tiers** — deadline- and/or stock-limited cheaper prices per
option or variant. Prices are locked in per purchase ("tranches"), so buying
more later doesn't re-price what was already bought.
- **Sections** — named scan points (e.g. "Main hall", "Dinner") limited to
certain ticket options, so a scanner at that point only accepts those tickets.
- **Visibility** — active/inactive, hidden (reachable only by link), scheduled
go-live date, require login vs. allow guest registration, or no registration
at all.
- **Attachments** — downloadable files (maps, schedules, waivers) shown on the
event page.
- **Notify recipients** — choose which staff get registration/payment alerts and
the daily summary for the event.
- **Sold-out handling** — an event is sold out when every stock-limited option
is exhausted. "X remaining" badges appear at a threshold that scales with
capacity.
---
## Registration
- **Online registration** (`/register/[eventId]`) — pick options, variants and
quantities; see early-bird prices and stock warnings; fill in the event form.
- **Guest registration** — when an event doesn't require login, an inactive
account is created and an activation link is sent by email or WhatsApp.
- **Statuses** — Pending, Confirmed, Partially Paid, Paid, Cancelled.
- **Edit options** — users can add or change items on their registration
(not for past or closed events).
- **Self-cancellation** — allowed only before any payment; admins can cancel
any time.
- **Pricing refresh** — when an unpaid registration is viewed or paid, expired
early-bird prices are re-evaluated, and the user is warned if the total
changed.
- **Manual registration** (supervisor) — register someone on their behalf,
creating an account if needed. Includes a "Record Payment" tab.
- **Duplicate-account protection** — if an email and phone belong to two
different accounts, the registration is blocked instead of merging them.
- **Group tickets** — on events with "Named attendees" turned on, someone booking
several places can name each person (with optional email/phone). Each named person
gets their own ticket and their own attendee form; unnamed places share one ticket.
Tickets go all to the payer, or each to the person (falling back to the payer).
Attendees matching an existing account see their ticket in My Events. Names can be
added or changed later from My Events, and attendees can be sent a link to fill in
their own form. Available on the registration page, manual registration, At the
door and the kiosk.
- **Waitlist** — on events with a waitlist, sold-out tickets show "Join waitlist"
(on the event page, the register page and the event list). When places free up — a
cancellation, a smaller booking or a higher stock limit — the next person is
emailed/WhatsApped a claim link and the places are held for them (24 hours by
default) so nobody else can buy them. Unclaimed offers expire and move on; people
who asked for more than came free can be offered what's free or skipped. Claiming
works without logging in. People can leave from My Events. On pick-sessions events
people wait for a particular session; offers never run past the session's start.
- **Parental consent (youth events)** — on events that require it, every attendee
gives a date of birth; for anyone under 18, a parent or guardian gets an email and
a WhatsApp with a consent link. They read the event's consent text, optionally give
medical info, an emergency contact and photo consent, type their name to sign, and
give or decline. Tickets are issued but can't be checked in until consent is given
(supervisors can override, audited). Reminders go after 2 days, then every 3 days.
Medical details are encrypted and deleted a set number of days after the event.
- **Coupon codes** — percentage, fixed-amount or free (comp) codes, entered under
"Have a code?" on the registration page, in My Events (for unpaid registrations),
manual registration, At the door and the kiosk. Codes can be limited to events,
ticket options or variants, dates, total and per-person uses, a minimum quantity,
and specific people, roles or an email domain (restricted codes need a login).
Early-bird prices either stack or the better price wins. The discount is locked in
when applied and shows on invoices, receipts, emails and the Yoco checkout;
cancelling frees the use. Managed from Supervisor → Coupon codes.
- **Staff price** — a ticket option or variant can have a staff price that Staff and
above get automatically, without a code.
---
## Payments, donations & refunds
- **Online card payments via Yoco** — checkout for the full outstanding balance,
confirmed by a signed webhook. Keys and the webhook are set up from
Site Settings → Payments, where providers are switched on or off and put in order
(the first one is the default). Online payments are at least R15; payments are
recorded at the full amount and provider fees are dealt with at cashup.
- **PayFast** — the second online provider (card, instant EFT…), with sandbox and live
modes. When several providers are on, payers choose on the "Pay online" page; a
payment of a different amount from the checkout is held for review instead of being
recorded. When no provider is on (or the amount is under R15), nothing offers to pay
online.
- **Payment status checks** — if a provider's notification never arrives, Payments →
Reconcile → "Waiting for payment" checks with the provider (PayFast; Yoco's API can't be
asked) and records what it finds. A job checks recent PayFast checkouts every 15 minutes.
- **Payment links** — supervisors can generate and send a Yoco link for any
amount (including partial).
- **Manual payments** — cash, card, EFT, voucher or other, recorded by staff.
Each payment records **who recorded it** as well as who it's for.
- **Refunds** — negative payments against an original payment, netted against
the original method.
- **Impersonate user** (Admin → Manage users) — an admin with 2FA can view the site as a
user, to debug problems.
- It needs a reason, lasts at most 30 minutes, and shows a bright "Viewing as" banner
on every page.
- It is strictly read-only. A server-side guard refuses every write made with the
impersonation token before it reaches any route, and pages don't even refresh
prices while viewing.
- Admins can't be impersonated.
- The start, end, reason and every page and API call are in the audit log, with each
session's trail.
- Optional email to the user (`notify_user_on_impersonation`).
- **Registration funnel stats** — first-party and consent-based, with no third-party analytics.
- A cookie notice asks once. Only visitors who allow it get a random visit id.
- We record event page views and registration starts. Submits and payments come
from the registration itself.
- Each record holds only the stage, the traffic source (utm_source, or the short-link
alias, which short links now pass as `?src=`) and the device type.
- The Registration funnel report shows counts and conversion per stage over a date
range, a daily trend, and breakdowns by source, device and ticket option.
- A "Conversion (past month)" tile on the supervisor/admin dashboards covers live
events.
- Raw rows are rolled up into daily totals after 90 days.
- **Post-event feedback** — a Feedback step in the event wizard.
- Questions use the form builder, with new **star rating (1–5)** and **multiple
choice** types (also available on attendee forms).
- The form goes out at a chosen time to everyone who checked in, or to everyone
registered, each with a personal link (`/feedback/<token>`). One reminder goes
3 days later to anyone who hasn't answered.
- Answers can be anonymous or named. "Send now" is available, and the questions
lock once people have answered.
- **Feedback page** (Supervisor → Feedback, supervisors and admins): every event's form
with answered of asked, response rate, average rating and last reminder; per event the
results per question (and the AI summary), each response, and on named forms who was
asked and who has answered. **Remind** sends everyone who hasn't answered a fresh link
(and the form to anyone eligible who hasn't had it), or one person on a named form;
nobody gets the form or a reminder twice within 24 hours. Anonymous forms show no names
and no list of who has answered. Opening a named form's answers goes in the access log.
- **Sponsor a spot** — per-event setting. A "Sponsor a spot" button on the event page
lets anyone, including guests, pay for one or more spots (at the main ticket price)
or any amount through Yoco. They can give anonymously or add a name and a message.
The money is a donation tagged to the event and goes into its sponsorship pool, which
supervisors assign to registrations with the usual donation flow.
- An optional public progress bar ("12 of 20 spots sponsored") with an optional goal.
- Sponsors get a thank-you receipt, and an Automations thank-you can go to all of an
event's sponsors.
- The Donations breakdown report shows each pool: received, assigned and remaining.
- Who is helped is never shown.
- **Donations** — users can donate from their dashboard (`/dashboard/user/donate`).
Supervisors can **assign** a donation (fully or partly) to someone's
registration and **unassign** it later. Assignments are kept as separate
records, so the original donation never changes.
- **Online payment reconciliation** — provider (Yoco) transactions can be matched to a
registration, recorded as a donation (optionally choosing the donor), or
ignored.
- **Invoices & receipts** — branded PDFs: an invoice (itemised, early-bird
discount, balance due, pay-now link and QR code) and a payment receipt. Sent
automatically and re-sendable on demand by email or WhatsApp.
- **Method normalisation** — Apple Pay / Google Pay / checkout payments count as
"Card" in reports and user views.
---
## Tickets & check-in
- **Automatic tickets** — QR-coded tickets are generated when a registration is
fully paid (or free), and sent as a PDF by email and/or WhatsApp.
- **Quantity tickets** — one ticket can cover several people and be redeemed
partially (e.g. check in 2 of 3).
- **Named tickets** — group bookings can give each person their own ticket, shown
with their name on the PDF, the scanner and the staff ticket list.
- **QR scanner** — works in any mobile browser. A preview checks the ticket is
for the selected event/section, then a confirmation screen shows holder, type
and remaining quantity.
- **Check-in confirmation** — holders get an email/WhatsApp saying how many were
checked in and how many remain.
- **Per-session check-in** — multi-day tickets are checked in once per session.
The scanner uses today's session (or one picked from a list). Check-in is open
the whole day of a session, or only from 2 hours before it until it ends, per
event. Optional reminders (1 h / 3 h / 1 day before each session) by email
and/or WhatsApp.
- **Attendance register** — attendees × sessions with ticks, totals per session,
completion, filters (completed, missed the last two), Excel/PDF export.
Supervisors can tick someone present or absent (audit-logged), and issue,
send, download or revoke certificates.
- **Scan stats** — recent scans and per-event scan counts.
- **Offline scanning** — while online, a staff member locks an event section (or the
whole event) to their device and downloads its tickets. They can then keep scanning
with no connection; scans are queued on the device and sync automatically when it's
back online (never redeeming more than is left). Only one device can hold a section,
and while it's locked nobody else can scan it, online or offline. Problems found
while syncing go into a report for a supervisor. Supervisors can force-release a
lost device. The scanner can be added to the home screen (PWA) and opens offline.
- **Printing** — A4 sheets (8 tickets per page) and A6 single tickets.
- **Resend** — send tickets to a different email/phone at the door.
---
## Attendee forms
- **Form builder** per event — field types: Yes/No, Text, Paragraph, Number,
Date, plus Statement and Heading blocks; required/optional, help text,
reordering. The whole form can be marked required.
- **Drafts** — partially filled forms are auto-saved.
- **Required forms and tickets** — a required form (with at least one question)
holds a registration's tickets back until a form is in for each person (a
picked-session booking counts each person once). At the door and in Manual
registration the form pops up to fill in with the attendee; **Fill in later**
(any staff) issues the tickets anyway once it's paid and sends the payer a link
to the form. The kiosk asks the visitor for exactly the forms still missing.
- **Responses** — view, filter (event, user, past/inactive) and print one
response per A4 page. Supervisors can edit responses.
---
## Messaging & notifications
Every user picks a **notification preference**: Email, WhatsApp, or Both.
**Automatic notifications**
| Trigger | Goes to |
|---------|---------|
| Registration created / updated | Registrant (with invoice if unpaid) + event notify recipients |
| Payment recorded / donation applied / unassigned | Registrant (with receipt) + admins |
| Refund processed | Registrant + admins |
| Tickets generated | Registrant (ticket PDF) |
| Ticket checked in | Ticket holder |
| Daily summary, 07:00, for each live event that hasn't started yet | Registrations inbox + event notify recipients |
| Account registered, activation, login, password changed/reset, account closed | The account holder |
**Bulk messaging** (supervisor)
- **Email attendees** and **WhatsApp attendees** — filter by status or pick
specific attendees, preview, send now or schedule for later.
- **Placeholders** — `{{name}}`, `{{event.title}}`, `{{event.link}}`,
`{{event.start}}`, `{{balance}}`, and `{{payment.link}}` (a live Yoco link for each recipient's
outstanding balance).
- **Broadcasts** — ad-hoc email/WhatsApp to any users or addresses, not tied to
one event.
- **Message type** — Event update or News & announcements; news only reaches people
who opted in (see [Privacy](#privacy-popia)).
- **Automations** — schedule a sequence of lifecycle emails for an event
(pre-event, final reminder, thank-you, promo for another event).
- **Manage scheduled** — view, edit or delete queued jobs per channel. Sends
run in the background and are purged 24 h after sending.
**WhatsApp** is connected through the WAWP API: an admin links a number in
Site Settings → WhatsApp (QR code or pairing code), with status, restart and
logout controls. Disconnected sessions are recovered automatically.
---
## User dashboard (My Events)
- Registrations with status badges, event thumbnails, and Closed/Past/Inactive
tags. Past and closed events are hidden by default.
- Registration detail: itemised bill (early-bird lines grouped), payments,
**Invoice** and **Receipt** buttons, edit, cancel, **Make payment**.
- Upcoming events and tickets side by side, with bulk ticket email/WhatsApp.
- **Ticket transfer** — offer a ticket to someone else before the event by typing
their name and email/phone (no user search, and nothing reveals whether they have an
account). They get a link to accept or decline; the ticket only moves once they
accept, and the sender can cancel until then (offers expire after 7 days or at the
event start). On accepting they get a new ticket and QR code, and an inactive account
with an activation link if they're new. The old code stops working, and scanning it says it
was transferred, both online and in offline-mode sync reports. One place can be split
off a ticket covering several people. Billing stays with the payer. It's not allowed
once a ticket has been scanned, and it can be turned off per event (supervisors can
always transfer, from At the door → Tickets). On youth events the new holder needs
their own parental consent, and the previous holder's form answers are removed.
Every transfer is in the audit log.
- **Payment history** (`/dashboard/user/payments`) — paginated, with filters by
date, method and payment/refund.
- **Donate** page.
- **Forms** — complete outstanding attendee forms.
- **Profile & Security** — edit details and notification preference, change
password, see recent account activity (logins, password changes, device),
sign out everywhere, deactivate or delete my data.
---
## Staff tools
- **Staff dashboard** — scan stats and quick actions.
- **Ticket scanning** (`/dashboard/staff/ticket-scanning`) — camera QR scanner
with event and section filters.
- **Event tickets & printing** (`/dashboard/staff/event-tickets`) — list, search
and print an event's tickets.
- **Kids check-in** (`/dashboard/staff/kids`) and the **room screen**
(`/dashboard/staff/kids/rooms`) — see [Kids check-in](#kids-check-in).
- **Volunteers** (`/dashboard/staff/volunteers`) — today's roster, ticking volunteers in and the
check-in QR code — see [Volunteer rosters](#volunteer-rosters).
---
## Supervisor tools
- **Choosing an event** (staff and supervisor pages: scanner, event tickets, at the door, payments,
manual registration, email and WhatsApp, forms, attendance, consent, waitlist, allocations,
bundles, offline scans, kids and volunteer set-up, manage registrations, kiosk): a searchable
picker instead of a long dropdown. It opens on upcoming events, soonest first; **Show past
events** lists past ones (latest first), and typing searches every event by name, campus or date.
Arrow keys, Enter and Escape work. `components/shared/EventPicker.tsx`.
- **Dashboard** — **Today** (each event or session on today: checked in so far
against places, children in now, volunteers here; money in today and this
week) and **Waiting for you** (unpaid registrations for the next two weeks,
parental consent outstanding, waitlists, cover requests, roster gaps; for
admins also cashups due, payments to reconcile, privacy requests, failed
webhooks — each links to where it's dealt with); then KPIs (active events,
revenue, donations, registrations, tickets sold, each vs. the previous month),
revenue trend chart, top events, and recent scans. Staff see Today too.
- **Command palette (Ctrl K / ⌘K)** — anywhere in the dashboard: pages, settings
and reports for the role, actions ("New event", "Scan tickets"…), and search:
events; payments by amount ("R450") for supervisors; people and registrations
for admins. Follows campus scoping.
- **Manage events** — the 9-step event wizard, ticket options, variants,
sections, form and attachments.
- **At the door** — search by name/phone/ticket ID, walk-in registration,
payments, a **Check-In** tab for redeeming main tickets by quantity, and
ticket printing/resending.
- **Self-service kiosk** (`/self-service`) — a touchscreen page a supervisor
unlocks for an event, where visitors register themselves. Existing accounts
are matched by email/phone, and any change to their details needs
confirmation.
- **Manual registration** — register someone on their behalf and record their
payment.
- **Payments** — tabs for Payment, Refund, Donations (assign/unassign),
Reconcile (Yoco transactions), and Payment Link.
- **Coupon codes** (`/dashboard/supervisor/coupons`) — create, edit and turn off
discount codes, and see who used each one.
- **Rooms & groups** (`/dashboard/supervisor/allocations`):
- Per event, allocation sets such as "Rooms", "Small groups" or "Buses". Each set
has groups with an optional capacity, gender restriction and leader (staff).
- A drag-and-drop board, plus auto-allocate: fill evenly, respecting capacity and
gender, keeping bookings together or splitting them.
- Printable per-group and master lists. On youth events they can include medical
details, and viewing those is audited.
- The group can show on tickets and in My Events.
- Email and WhatsApp attendees can be filtered to one group.
- Leaders see their people under Staff → **My groups**.
- Works on named attendees. Events can ask each person's gender.
- **Offline scanning** (`/dashboard/supervisor/offline-scans`) — devices holding
offline locks (with force release) and sync reports to review.
- **Waitlist** (`/dashboard/supervisor/waitlist`) — the queue per event: offer a
place now, move people up or down, or remove them.
- **Parental consent** (`/dashboard/supervisor/consent`) — consent status per
attendee on youth events, resend (one or all pending), re-request after the
consent text changes, and a printable medical & emergency list (audited).
- **Email attendees / WhatsApp attendees** — bulk and scheduled messaging.
- **Forms** — view, filter, edit and print form responses.
- **Reports** — see [Reports](#reports).
- **Site banner** (`/set-banner`) — set the announcement bar.
---
## Admin tools
- **Admin dashboard** — same KPIs as supervisor, plus admin quick actions.
- **Manage users** — server-side search and filters (role, active), paging,
edit role and notification preference, revoke sessions, delete or
**anonymise** personal data.
- **Data requests** — POPIA correction and deletion requests (see
[Privacy](#privacy-popia)).
- **Registrations** — all registrations, with filters (event, status, text),
status counts, revenue and outstanding totals, and per-registration options,
form answers and payments (with who recorded each one). **Bulk actions** on
ticked registrations (or all shown): message (email/WhatsApp), mark paid
(records the balance by method), move to another ticket (same tickets and QR
codes, repriced), put in a room or group, export to Excel, cancel — each
through the same rules as one at a time, with a result per registration.
- **Saved filters** — on Manage registrations, Users, Events and Reports: name the
current filters, apply one with a click, star one as the default for the page
(not applied over a deep link). Per person, on the server.
- **Cashup** — see below.
- **Corrections** (`/dashboard/admin/corrections`, admins only) — for any event,
past and closed ones too: registrations missing tickets, with forms to fill in,
or owing money. **Issue all missing tickets** at once (forms left for later),
fill in a form, **issue tickets — pay later** (balance still owed), **make it
free** (the balance written off as a complimentary discount, so income stays
what was paid; not on closed events), and **check people in (or undo) after the
event** for any session. Optionally send the tickets. Every correction is in
the audit log with the reason given.
- **Audit log** (`/dashboard/admin/audit-log`) — who did what and when for
refunds, donation assign/unassign, manual registrations, staff
cancellations, event create/update/delete, settings changes, and coupon codes
(created, edited, turned off, applied or removed by staff), and every later feature's admin
actions. Search by person, target or IP; filter by action, role and dates; 50 a page.
- **Site settings** — see below.
---
## Cashup & event costs
- **Event costs** — once-off or per-item costs (optionally linked to a ticket
option), with a "paid from takings" method so cash on hand is correct.
- **Expected vs. actual** — expected takings per method (cash/card/EFT/other)
compared with actual amounts, with variance shown.
- **Cash denomination counts** — entered per staff member, at any time. The
event's actual cash is the sum of these counts.
- **Payment accountability by staff member** — what each person recorded, by
method, with live cash variance.
- **Close / quick close / reopen** an event — closing locks it from further
edits and hides it from the kiosk and user actions. Drafts are saved as you
go.
- **Report tab** — a read-only cashup summary, shown automatically once the
event is closed.
- **Cashup audit trail** — every close/reopen with totals and who did it.
---
## Reports
A full-width workspace with shared filters (events, searchable, with "Select these N" for the matches; date range with presets,
include past/inactive/closed) and a searchable grid of reports, each opening in
a viewer with its own filters, stat tiles and bar charts.
| Category | Reports |
|----------|---------|
| Financial | Payments between dates · Revenue summary (by method) · Revenue detailed · Finance report (revenue & costs, after discounts) · Profit report · Discounts (coupon codes) |
| Registration | Registration funnel (views → started → submitted → paid, daily trend, by source / device / ticket option) · Attendees per event (grouped by option) · Registration type counts · Master orders breakdown · Registration status breakdown (count by registration or ticket quantity) · Parental consent status · Medical & emergency list · Feedback summary (response rate, average ratings, choice breakdowns, comments; compare events) |
| Ticketing | Ticket usage summary |
| Donations | Donations breakdown (used / unused per event, plus the sponsorship pool) |
| Cashup | Cashup reconciliation · Cashup audit trail |
| Other | Series: year on year (a series' events side by side — registrations, tickets, income, checked in, attendance rate, change from the one before) |
**Export:** Print, branded PDF download, styled Excel (`.xlsx`) workbook,
Email (to yourself), or WhatsApp (the PDF to your own number). Dashboard tiles
deep-link into reports with `?report=&range=`.
---
## Site settings & setup wizard
**Setup wizard** (`/setup`) — on a fresh database, walks through organisation
details, the first admin account and branding. No manual seeding needed.
**Site Settings** (`/dashboard/admin/settings`) — stored in the database and
applied without a restart. Secrets are encrypted with AES-256-GCM.
| Tab | Contains |
|-----|----------|
| Organisation | Name, tagline, contact email/phone, address (with map link) |
| Campuses | Off by default. Turn on, then add, order, archive or delete campuses (name, web address, address, contact, colour, logo, default event location, daily-summary recipients) |
| Branding | Primary/secondary/accent colours (with a readability warning and a darker shade offered when the primary is too light), logo, favicon, colours suggested from the logo, live website/email preview on desktop and mobile |
| Notifications | Registrations inbox and admin notification emails |
| Email | SMTP host/port/TLS/user/password/from, with a "Test connection" button |
| Legal | Operator, Information Officer, website, effective date for the Terms/Privacy pages |
| WhatsApp | WAWP credentials, connect a number, status/restart/logout |
| Payments | Online payment providers: Enabled toggle and order; PayFast merchant ID/key, passphrase and sandbox/live; Yoco's secret key (masked, test/live), webhook secret (generate by registering with Yoco, or enter), list/delete the account's webhooks |
| Backups | List, run now, download database backups |
See [SETTINGS.md](./SETTINGS.md) for the default of every setting.
---
## Event series
Separate events grouped on one page — every year's camp, the monthly men's breakfast (each event
keeps its own registrations; for one event on several dates see multi-day events).
- **Event series** page (supervisors): name, web address (`/series/<slug>`), description, picture;
each series lists its events (campus-scoped supervisors see only their campuses' events in it)
and its number of followers. Admins can delete a series (its events stay).
- **Series box** in the event editor's Basic details. A copied event keeps its series. A series can
have events at several campuses.
- **Public series page**: upcoming events as cards, then past events. Event pages in a series show
"Part of …" and **Next in this series** (the next public event in it).
- **Follow a series**: signed-in people follow on the series page; when a new event in it goes live
(before it starts) they get one email, sent as News & announcements (opted-in only, with an
unsubscribe link). The `series` job runs every 15 minutes.
- **Year on year**: Reports → Series: year on year (or **Compare** on the Event series page)
compares the series' events — registrations, tickets, income, checked in (average per session on
multi-session events), attendance rate — each against the one before.
- **Season passes**: on the Event series page, a pass gives a ticket (and variant) at each event
ticked, at one price (optional sale end; stops when its first event starts; no youth events,
staff-only or per-session tickets). Buyers choose how many on the series page and are registered at
every event at once with one payment (or tickets at once when free; "Pay now" later if online
payment isn't possible). The price is split over the events in proportion to their normal prices;
each event gets its own registration line and payment for its share, so cashups stay per event.
Pass registrations aren't repriced, take no codes and can't be edited. Events and price lock once
sold.
## Multi-campus
For a church with several campuses in one install (Site settings → Campuses, off by
default — single-campus churches never see campus fields).
- **Events** belong to one campus or to **All campuses** (church-wide). Choosing a campus fills in
its default location. Moving an event to another campus is in the audit log.
- **Public site:** a campus filter on the events page, remembered per visitor and starting on their
home campus; a campus shows its own events plus church-wide ones. The campus shows on event cards,
the event page and ticket PDFs. Each campus has a page at `/campus/<slug>` (also in the sitemap).
- **People** choose a home campus on their profile.
- **Reports and dashboards:** a campus filter on Reports (every report and the funnel) and on the
admin/supervisor dashboards' month-over-month tiles, with a church-wide total.
- **Messages:** "Everyone at a campus" in Email and WhatsApp broadcasts — home campus, plus (ticked)
people who registered for its events in the last 12 months. News consent still applies.
- **Daily summary:** campus recipients get the summary of their campus's events.
- **Turning it off** hides everything campus-related; nothing is deleted. A campus with events can't
be deleted, only archived.
- **Staff for some campuses** (Admin → Users → "Limit to campuses"): a supervisor or staff member
sees only their campuses' events plus events for all campuses — every list, report, dashboard
and scanner follows it. For church-wide events they can scan, register people and take payments
at the door, but not change, cash up or refund them. The site banner, payment reconciliation and
donations not linked to an event are for admins and unscoped supervisors; broadcasts only reach
people at their campuses or their events' attendees; coupons only for their campuses' events.
Another campus's records answer "not found"; the scanner says which campus a ticket is for.
Admins are never limited; limits are ignored while campuses are off.
---
## Kids check-in
Secure check-in and pickup for children's ministry, run from a staff desk and fully digital — no
label printers.
- **Setup** (Supervisor → Kids check-in setup, `/dashboard/supervisor/kids`): per event, a
**kids ticket** (a main ticket covering the whole event — "Add a free Kids check-in ticket"
makes one) and **rooms** (an allocation set; each room has an age range, capacity and children
per leader), then switch it on. Weekly kids church = one event with a session per Sunday.
- **Families** are kept between events: parents add their children under My account → **Kids**
(`/dashboard/user/kids`) — date of birth, allergies, medical and custody notes — and their
**authorised adults** (name, phone, relationship; no account needed). The page shows a family QR
code for the desk.
- **Desk** (`/dashboard/staff/kids`): find the family (name, phone or family QR) or add one, tick
the children (room suggested from the age: the narrowest range that isn't full), check in. The
family gets a **4-character pickup code** for the day or session (no 0/O/1/I), sent to the parents
by WhatsApp/email and shown on their Kids page with a QR code; it can also go to an authorised
adult. A **"write on the sticker"** panel shows first name, room, code and ALLERGY/MEDICAL in
large print to copy onto a blank sticker.
- **Check-out:** type or scan the code, see the children on it, the parents, the authorised adults
and any custody notes, record who collected. Anyone with the code can collect. A **wrong code**
is refused, raises an alert on the room screens and is audited; **without the code** needs who
and why (audited).
- **Room screen** (`/dashboard/staff/kids/rooms`): live cards per room — code, allergies, medical
and custody notes, parents and authorised adults — "I'm on duty", counts and full/over-ratio
warnings, **Call parent** (WhatsApp/email, shown on the parent's page), move to another room,
check out without code, wrong-code alerts.
- **Offline desk:** "Get ready for offline" downloads the families and 20 pickup codes reserved for
the device. Offline, the desk checks in (no messages) and checks out children it checked in
itself; "Sync" uploads everything and says if a family got another code elsewhere.
- **Attendance:** each child gets a free place on the kids ticket under the parent the first time
(registration, attendee, ticket), and each check-in is a ticket usage — so the attendance
register, reports and campus scoping include them.
- **Privacy:** allergies, medical and custody notes encrypted, never in messages; custody notes
changed only by parents, supervisors and admins (audited); opening the desk/room screens and
offline downloads are in the access log; a child's profile is deleted after **6 months** without
a check-in (Admin → Privacy → Retention).
- **Volunteers in kids rooms:** a serving role linked to a room puts its volunteers on duty there
when they check in; the room screen lists who is rostered but not in yet.
- The kids ticket is never offered publicly (left out of public event pages, refused on public
registration).
---
## Volunteer rosters
Who serves where, for an event or each session.
- **Roles** (Supervisor → Volunteer rosters, `/dashboard/supervisor/volunteers`): name, people
needed, optional shift times (default: the session's or event's times), description, and
optionally a kids room. On a multi-session event each role is for one session. A role can't be
deleted once someone has checked in for it.
- **Volunteering** (My account → Serving, `/dashboard/user/serving`): anyone with an account signs
up for a role that isn't full; supervisors can also put people on (beyond the number needed).
Nobody can be in two roles whose shifts overlap. `?event=<id>` opens one event (the sign-up link
supervisors share, also for hidden events). Volunteers are told when they're put on, taken off,
or a role is deleted, and get a **reminder the day before**.
- **Swaps:** "Can't make it" asks for cover — the event's other volunteers are told and the request
shows on everyone's Serving page; the first to accept takes the place at once (no approval). The
event's notification recipients (or its creator) are emailed about every swap and withdrawal.
- **Check-in:** volunteers scan the event's **check-in QR code** (Check-in QR tab, or Staff →
Volunteers) with their phone camera → `/serve/check-in` → every shift of theirs on that day is
checked in. Staff can tick people in by hand (and undo). Check-in opens on the day of the shift
and closes when it ends.
- **Kids rooms:** checking in for a role linked to a kids room puts the volunteer on duty in that
room (counted for the ratio, like "I'm on duty"); undoing the check-in takes them off.
- **Volunteer ticket** (off by default): choose a main ticket of the event, or add a free
"Volunteer" ticket. Volunteers without a ticket get a free place on it (in My Events); it's
cancelled when they leave the roster (unless it was scanned), moves with a swap, and is never
offered publicly.
- **Reports:** roster sheet (phone numbers, check-in time and how), printable; fill rate per event;
**hours served** per person (checked-in shifts × shift length) over all events or one.
- **Read-only licence:** new roles and sign-ups are blocked; check-ins, swaps and withdrawals keep
working.
---
## Accounts & security
- Register, log in, forgot/reset password, activate account (for accounts
created on someone's behalf).
- JWT authentication (HS256 pinned) with **session revocation** (token
versioning) — users can sign out everywhere, and admins can do it for any user.
- **Two-factor authentication** — a 6-digit login code by email or WhatsApp
(10-minute expiry, 5 attempts, resend), with "Trust this device for 30 days".
**Required for Admins and Supervisors**: their next login sends a code that turns
it on, and they can change the channel but not turn it off (skipped only when no
email or WhatsApp channel can deliver a code; `TWO_FACTOR_REQUIRED_ROLES=false`
is the emergency switch). Optional for everyone else from Profile & Security.
Admins can reset it for a locked-out user, and the kiosk asks for the code at
setup.
- **Login lockout** after repeated failed attempts, plus login rate limiting
(`TRUST_PROXY` to read real IPs behind a proxy).
- **Security event log** — logins, password changes and resets, with device
and IP.
- **Account closure** — deactivate, or close and ask for the personal data to be
deleted (see [Privacy](#privacy-popia)).
- **Upload hardening** — server-generated filenames, and uploads served with a
sandbox CSP and `nosniff`.
---
## Privacy (POPIA)
Tools that help a church handle personal information the way POPIA expects. They
support compliance; wording and retention choices are for the church's Information
Officer.
**For everyone** — the **Privacy** page (`/dashboard/user/privacy`):
- **News & announcements** opt-in per channel (email, WhatsApp), with the history of
every choice: when, and how (sign-up, privacy page, unsubscribe link, STOP reply…).
Sign-up has an unticked opt-in box; accounts that never answered are asked once
after logging in.
- **Download my data** — readable PDF, or the complete copy as JSON.
- **Correct my data** — profile fields directly; anything else as a correction request.
- **Delete my account** — closes the account at once and files a deletion request.
**Bulk messages** are either an **Event update** (about an event the recipients
registered for; always sent) or **News & announcements** (only to people who opted in
on that channel and haven't unsubscribed). News emails carry an unsubscribe link and
one-click `List-Unsubscribe` headers; news WhatsApps end with "Reply STOP" and a link.
Event updates say why they were sent and link to the preferences. A STOP reply on
WhatsApp turns off WhatsApp news (through WAWP's `message` webhook, checked against a
secret in the webhook URL).
**Privacy notice** (`/legal/privacy`) — edited in **Admin → Privacy (POPIA)**
(`/dashboard/admin/privacy`): sections start from the built-in text; drafts, preview,
and published, numbered versions (earlier ones stay readable with `?version=N`).
Placeholders (`{org}`, `{ioName}`, `{ioEmail}`, `{website}`, `{orgEmail}`,
`{medicalRetentionDays}`, `{operators}`) are filled in from Site settings and the
operator register. A version marked as a significant change is accepted once by everyone
after their next login. People agree to the notice at sign-up and when they activate an account
made for them; anyone who never has is asked once after login. When the built-in text changes
in an update, a site with its own published version sees what changed in the editor, with each
changed section marked (**Use the new text**, **Use all the new text**, **Add** missing sections,
**Done — hide this**). The "Change my cookie choice" button shows above the cookie section. The
contact page shows the Information Officer.
**Registers and logs** (same admin page):
- **Operators** — the services that process personal information (payment, WhatsApp,
email, hosting, maps, error monitoring), what each receives and where; those in use
are listed in the notice.
- **Consent log** — news opt-ins/opt-outs, privacy notice acceptances and parental consent
answers, searchable.
- **Access log** — every bulk export or view of personal information (reports, attendance
registers, certificates, group lists, form answers, consent and medical lists, backups)
and every "view as" session, with the number of records. Children's and medical
information is flagged (medical lists, and anything about a youth event).
- **Retention** — how long each kind of personal information is kept, applied by a nightly
job: inactive accounts anonymised after 5 years (warning 30 days before; never staff
roles or people with an upcoming registration), form answers deleted 12 months after
the event, login history kept 24 months, payer details in payment notifications removed
after 24 months, audit/access logs kept 5 years. The notice's `{retention}` placeholder
lists them.
- **Breaches** — the register of security compromises, with when the Information Regulator
and the people affected were told, and drafts of both notifications.
- **Readiness** — a scored checklist of what's set up, each item linking to its fix.
**For admins** — **Data requests** (`/dashboard/admin/data-requests`, searchable, closed ones paged): correction and
deletion requests with a 30-day due date, emailed to the Information Officer and
admins, reminded daily when due within a week. Completing a deletion anonymises the
person: name, contact details, the people they registered, form answers, consent
details, sponsor names, login history and payer details in provider notifications are
removed; payments, registrations, tickets and check-ins stay as "Deleted User". It
waits while they have a registration for an upcoming event. Everything is in the audit
log.
---
## Accessibility
Built to WCAG 2.2 AA on the public pages, sign-in, registration, payment, My Events and the
self-service kiosk (1.50.0): "Skip to main content" link, visible keyboard focus, labelled fields,
named buttons (ticket quantities say "Add one …"), errors announced as they appear, popups that
trap focus and close with Escape, readable contrast with underlined in-text links, and "reduce
motion" respected. Branding warns when the primary colour is too light for white text and
suggests a darker shade. axe-core checks and keyboard tests in the e2e suite
(`e2e/accessibility.spec.ts`) keep it that way.
---
## Help system
A floating **"Need help?"** button on every page opens a page-specific guide
(tabs, quick links). Every page has dedicated content (`frontend/src/content/help/`),
falling back to a general guide.
---
## Outbound webhooks
Site settings → **Webhooks** (admins): send what happens to other systems as it happens.
- **Endpoints**: name, https address, and the event types to send — registration created / paid /
cancelled, payment received / refunded, ticket checked in, account created, event published.
Switch off, edit, delete, **Send test**, **New secret**.
- **Messages**: JSON `{ id, type, createdAt, data }` (registration with items and totals, payment,
check-in with session, person, event); headers `X-CrossEvents-Event`, `X-CrossEvents-Delivery` and
`X-CrossEvents-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "<t>.<body>">` with the endpoint's secret.
- **Delivery log** per endpoint (30 days): status, tries, response code or error, the full message,
**Resend**; filter by status and **Load older**. Retries after 1 min, 5 min, 30 min, 2 h, 12 h, then failed.
- Every path that registers, pays, cancels, refunds or checks in is covered (Prisma client
extension); rolled-back changes send nothing. Kids check-in and volunteer tickets are never sent.
- https and public addresses only (DNS checked at each send, redirects not followed). Each endpoint
is added to the operator register; deliveries are deleted after 30 days and with an account.
- **How webhooks work** (1.50.2), a guide on the tab (open until the first webhook is added): the
envelope and headers, retries and duplicates, checking the signature (Node.js and PHP examples),
Zapier/Make set-up, and a copyable example message for every event type. The examples come from
`EVENT_TYPES[].example` in `utils/webhooks.js`; a test keeps them the same shape as what is sent.
## Background jobs
Timed jobs run on a job queue in Postgres (pg-boss, `backend/src/jobs/index.js`): each
runs once per schedule even with several server processes, every run is recorded,
failed runs are retried twice, and a slow run never overlaps the next. Admin → Site
Settings → Background jobs shows each job's schedule, next run and last 10 runs, with
"Run now". Times are in `APP_TIMEZONE` (default Africa/Johannesburg). Change a schedule
with `JOB_SCHEDULE_<NAME>` (cron); `JOBS_ENABLED=false` turns them all off. If the queue
can't start, the same jobs run on in-process timers.
| Job | Schedule |
|-----|----------|
| Scheduled email/WhatsApp worker | Polls every 30 s (`SCHEDULED_EMAILS_INTERVAL_MS`) and purges sent jobs after 24 h (not on the queue) |
| `daily-summary` — daily event summary email | 07:00 daily (`DAILY_SUMMARY_ENABLED=false` to disable) |
| `waitlist` — expire unclaimed offers, offer freed places | Every 10 minutes (`WAITLIST_JOB_ENABLED=false`) |
| `payment-status` — look up PayFast checkouts (10 min – 3 days old) whose notification never arrived, and record them | Every 15 minutes (`PAYMENT_STATUS_JOB_ENABLED=false`) |
| `feedback` — post-event feedback forms and their 3-day reminder | Every 15 minutes (`FEEDBACK_JOB_ENABLED=false`) |
| `sessions` — session reminders, and certificates for events that ended in the last 14 days | Every 5 minutes (`SESSION_JOBS_ENABLED=false`) |
| `volunteers` — volunteer reminders the day before a shift | Every 15 minutes (`VOLUNTEER_JOBS_ENABLED=false`) |
| `series` — email a series' followers when a new event in it goes live | Every 15 minutes (`SERIES_JOBS_ENABLED=false`) |
| `webhooks` — send webhook deliveries that are due, retry failures, delete deliveries after 30 days | Every minute (`WEBHOOKS_JOBS_ENABLED=false`) |
| `consent` — parental consent reminders, and deleting medical details after events | 09:00 daily (`CONSENT_JOBS_ENABLED=false`) |
| `privacy` — remind admins of privacy requests due within a week or overdue | 08:00 daily (`PRIVACY_JOBS_ENABLED=false`) |
| `retention` — delete/anonymise personal information past its retention period (Admin → Privacy → Retention) | 03:30 daily (`RETENTION_JOBS_ENABLED=false`) |
| `hub-heartbeat` — check in with the Cross Events Hub and pick up licence changes (only once connected) | Every 15 minutes (`HUB_HEARTBEAT_ENABLED=false`) |
| `analytics-rollup` — roll raw visit rows older than 90 days into daily totals | 04:15 daily (`ANALYTICS_ROLLUP_ENABLED=false`) |
| `backup` — database backup (`pg_dump`, gzipped, 14-day retention) | 02:00 daily (`BACKUP_ENABLED=false`) |
| `temp-cleanup` — temp files older than 7 days in `/temp` | 03:00 daily |
---
## Operations
- **Install script** (`scripts/install.sh`) — a fresh Ubuntu server to a running site: Node 20,
PostgreSQL, PM2, nginx, HTTPS, configuration, migrations and build; then `/setup`.
- **Cross Events Hub** — every install connects with a licence key (`/setup`, or Site settings →
Licence) and checks in every 15 minutes with its version, health and totals (no personal
information; income as a range). Licences are signed tokens checked on the site, so a Hub outage
never switches it off: past the end date there's a grace period (banner for site admins only),
then — or when suspended, revoked or not licensed — the site is read-only (events can't be
created or edited; no new registrations or payments; tickets still scan, data can be exported).
The site checks in 30 seconds after starting and after a licence key is connected. Admins see when an update is available, with
**what's new** in each version, and press **Request update**, which tells the provider through the Hub (the site never updates
itself). A request can be **withdrawn**; when a newer version comes out after asking, the page shows
the version asked for and **Ask for … instead** moves the request on to the newer one. **Not now** hides the update banner until the next version; urgent updates (security or
serious bug fixes) can't be put off and show a red banner.
- **Notices from the provider** — maintenance and other messages the provider posts in the Hub show as a banner on the dashboard
for site admins and supervisors, in their time window; each can be closed (per browser) and stays listed on Site settings →
Licence. The provider can email them to the church too.
See `docs/hub-protocol.md`.
- **`/health`** — status, version, database, background jobs and last backup.
- **PM2** (`ecosystem.config.js`) runs backend and frontend, restarting either
one above 500 MB of memory.
- **Sentry** error monitoring when `SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN` are
set.
- Unhandled promise rejections are logged and don't crash the server.
- Backend status page (`/`); **API v2** (`/api/v2`, 1.51.0 — the only API since 2.0, which removed
v1; `/docs` redirects to `/docs/v2`) with one error shape, paged lists and an OpenAPI 3.1 reference at `/docs/v2` (admins). Public
events, my account and registrations, registering, cancelling and paying online (1.51.1),
signing up, logging in (with the 2FA step), changing my details and checking tickets in (1.51.2;
the scanner and at-the-door use it from 1.51.3); the frontend's v2 calls are typed from the
OpenAPI document. v1 endpoints with a v2 replacement send `Deprecation` and a `successor-version`
link (1.51.3).
- **TypeScript backend** (1.51.0): `.ts` files are checked strictly, `.js` compiles as it is;
deploys build `dist/`, which `src/index.js` runs.
- **Command palette** (Ctrl+K): every page, settings tab, report and quick action for your role.
- **Tests** — Jest unit tests in `backend/tests` (`npm test`), and Playwright
end-to-end tests in `e2e/` (`npm run test:e2e`) that start their own backend and
frontend against a separate, freshly seeded database: public pages, free and paid
registration through to check-in and cashup, multi-day check-in, the attendance
register and certificates, the event wizard, the kiosk, and the admin jobs page.
- **Deploy script** — `scripts/deploy.sh [tag]`, run on the server, backs up the
database, checks out the release, migrates, builds and reloads PM2, and goes back to
the previous version if a step fails before the reload.
- Versioning via git tags and [CHANGELOG.md](./CHANGELOG.md).
---
## Page map
| Path | Who | What |
|------|-----|------|
| `/` | Public | Home |
| `/events`, `/events/[id]` | Public | Event list and detail |
| `/campus/[slug]` | Public | A campus's page and its events (while campuses are on) |
| `/series/[slug]` | Public | A series' page: upcoming and past events, Follow |
| `/[alias]` | Public | Event short link |
| `/register/[eventId]` | Public / User | Registration |
| `/registration/success` | Public / User | Confirmation, form and pay |
| `/pay/[id]` | Public | Pay online: choose a provider, or go on to PayFast |
| `/payment/success`, `/payment/failure`, `/payment/cancel` | Public | Return pages after paying online |
| `/forms` | Public / User | Attendee forms |
| `/contact`, `/legal/terms`, `/legal/privacy`, `/lockdown-rules` | Public | Info pages |
| `/login`, `/register`, `/forgot-password`, `/reset-password`, `/activate-account` | Public | Accounts |
| `/setup` | First run | Setup wizard |
| `/consent/[token]` | Parent/guardian | Give or decline parental consent |
| `/waitlist/claim/[token]` | Public | Claim a waitlist place |
| `/certificates/verify/[code]` | Public | Check a completion certificate |
| `/unsubscribe?t=…` | Public | Unsubscribe from news (link in news emails/WhatsApps) |
| `/serve/check-in?code=…` | User (logs in first) | Volunteer check-in (where the event's check-in QR code leads) |
| `/self-service` | Supervisor-unlocked | Kiosk |
| `/set-banner` | Supervisor | Site banner |
| `/dashboard/user` (+ `/payments`, `/donate`, `/forms`, `/profile`, `/privacy`, `/kids`, `/serving`, `/reset-password`) | User | My Events |
| `/dashboard/staff` (+ `/ticket-scanning`, `/event-tickets`, `/my-groups`, `/kids`, `/kids/rooms`, `/volunteers`) | Staff | Staff tools |
| `/dashboard/supervisor` (+ `/events`, `/event-options`, `/at-the-door`, `/manual`, `/manual-registration`, `/payments`, `/coupons`, `/waitlist`, `/attendance`, `/consent`, `/offline-scans`, `/allocations`, `/kids`, `/volunteers`, `/email-attendees`, `/whatsapp-attendees`, `/forms`, `/reports`) | Supervisor | Supervisor tools |
| `/dashboard/admin` (+ `/users`, `/registrations`, `/forms`, `/cashup`, `/cashup/[id]`, `/corrections`, `/audit-log`, `/data-requests`, `/privacy`, `/settings`) | Admin | Admin tools |
+408
View File
@@ -0,0 +1,408 @@
# Moving to Cross Events 2.0
Cross Events 2.0 removes version 1 of the API (`/api/…`). Everything the app does has been on
version 2 (`/api/v2/…`) since 1.51.16, so **a church that only uses the app has nothing to do** —
the update looks the same as any other. This guide is for anyone with their own integration (a
script, a website plug-in, a spreadsheet import) that calls the API directly, and for whoever runs
the server.
## What still works without changes
- **Payment and WhatsApp webhooks.** Yoco, PayFast and WAWP keep posting to the addresses they were
registered with: `/api/webhooks/yoco`, `/api/webhooks/payfast`, `/api/webhooks/whatsapp` and the
oldest WAWP address, `/api/whatsapp/webhook`. New registrations use `/api/v2/webhooks/…`.
- **Links in messages already sent.** "Add to calendar" links (`/api/events/{id}/ics`) and one-click
unsubscribe links (`/api/privacy/unsubscribe/{token}/one-click`) answer `308` with their v2
address; a mail app's one-click `POST` to the old address is still handled.
- **Outbound webhooks** (Site settings → Webhooks) send the same events and payloads as before.
- **Pages people open** — event pages, consent forms, ticket transfers, waitlist offers — are app
pages, not API addresses, so they were never affected.
Any other `/api/…` address now answers **`410 Gone`**:
```json
{ "code": "API_V1_REMOVED", "message": "API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2." }
```
`/docs` (the v1 reference) redirects to `/docs/v2`.
## How v2 differs
The full reference is at `/docs/v2` on your site (sign in as an admin), generated from the code so
it is always current. The OpenAPI 3.1 document is `GET /api/v2/openapi.json`.
| | v1 | v2 |
|---|---|---|
| Answers | whatever each endpoint returned | always `{ "data": … }` |
| Lists | plain arrays, some paged | `{ "data": [ … ], "meta": { "page", "limit", "total", "pages" } }`, `?page=` and `?limit=` (most lists up to 100) |
| Errors | `{ "message", "code"? }`, often `400` | `{ "error": { "code", "message", "reason"?, "fields"? } }` — `code` is one of a fixed set (`VALIDATION_FAILED`, `UNAUTHENTICATED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`, `READ_ONLY`, `RATE_LIMITED`, `UNAVAILABLE`, `INTERNAL`); v1's `code` is now `reason` |
| Input | anything | checked against the documented schema; mistakes are `VALIDATION_FAILED` with `fields` |
| Changing a record | mostly `PUT` | `PATCH` for partial changes (events, ticket options, variants, series, users, coupons…) |
| Dates | mixed | ISO 8601, UTC |
Things that behave differently, not just live at a new address:
- **Signing in:** `POST /api/v2/auth/login` takes `{ identifier, password }` (an email or phone
number). If two-step sign-in is on, the answer is `status: "code_sent"` with a `challengeId`;
finish with `POST /api/v2/auth/login/code`.
- **Signing up:** `POST /api/v2/auth/signup` needs `acceptTerms: true`; the phone number is
`phone`. The answer's `data` holds `token` and `user`.
- **Checking a ticket in:** `POST /api/v2/checkin/{qrCode}` with `{ people? }` (was `qty`). Every
normal result is a `200` with an `outcome` — `checked_in`, `already_used`, `consent_required`,
`wrong_event`, … — where v1 used `403`s. Look a ticket up first with `GET /api/v2/checkin/{qrCode}`.
- **Paying online:** `POST /api/v2/registrations/{id}/checkout` (the registration is in the path,
not the body).
- **Cancelling a registration:** `POST /api/v2/registrations/{id}/cancel` (was `DELETE`).
- **Staff lists of registrations** are paged (up to 200 a page).
- **A suspended or unlicensed site** refuses new events, registrations and payments with
`READ_ONLY` / reason `LICENCE_READ_ONLY`.
## For whoever runs the server
1. Deploy as usual: `bash scripts/deploy.sh v2.0.0` (it backs up, migrates, builds and rolls back
on failure). Run `bash scripts/deploy.sh --check` first if anyone may have changed files by hand.
2. Two migrations run: `20261030120000_ai_helpers` (the AI call log) and anything newer listed in the
CHANGELOG.
3. **AI helpers** need the site connected to the Hub (Site settings → Licence) and a monthly AI cap
above R0 on the licence. The Hub must run 1.6.0 or later. With no cap the AI buttons don't show
and nothing else changes.
4. If something outside Cross Events still calls `/api/…`, it will get `410` after the update — look
for those in the nginx access log before updating (`grep -v '/api/v2/' access.log | grep ' /api/'`,
leaving out the webhook and link addresses above).
5. Passwords are re-hashed with a stronger method the next time each person signs in; nothing to do.
## Every v1 address and its v2 replacement
`{id}` is the record's id. `{a|b}` means either. Methods that changed are shown in the v2 column.
| v1 | v2 |
|---|---|
| `GET /api/events` | `GET /api/v2/events` |
| `GET /api/events/{id}` | `GET /api/v2/events/{id}/full` |
| `GET /api/events/{id}/ics` | `GET /api/v2/events/{id}/calendar.ics` |
| `GET /api/events/by-alias/{id}` | `GET /api/v2/events/by-alias/{id}` |
| `POST /api/events/{id}/options` | `POST /api/v2/events/{id}/ticket-options` |
| `PUT /api/events/options/{id}` | `PATCH /api/v2/ticket-options/{id}` |
| `DELETE /api/events/options/{id}` | `DELETE /api/v2/ticket-options/{id}` |
| `POST /api/events/options/{id}/variants` | `POST /api/v2/ticket-options/{id}/variants` |
| `PUT /api/events/variants/{id}` | `PATCH /api/v2/variants/{id}` |
| `DELETE /api/events/variants/{id}` | `DELETE /api/v2/variants/{id}` |
| `GET /api/events/attachments/status` | `GET /api/v2/attachments/status` |
| `POST /api/events/attachments/sync` | `POST /api/v2/attachments/sync` |
| `GET /api/events/{id}/attachments` | `GET /api/v2/events/{id}/attachments` |
| `POST /api/events/{id}/attachments` | `POST /api/v2/events/{id}/attachments` |
| `DELETE /api/events/{id}/attachments/{id2}` | `DELETE /api/v2/events/{id}/attachments/{id2}` |
| `GET /api/sections` | `GET /api/v2/sections` |
| `POST /api/sections` | `POST /api/v2/sections` |
| `PUT /api/sections/{id}` | `PATCH /api/v2/sections/{id}` |
| `DELETE /api/sections/{id}` | `DELETE /api/v2/sections/{id}` |
| `GET /api/events/{id}/costs` | `GET /api/v2/events/{id}/costs` |
| `POST /api/events/{id}/costs` | `POST /api/v2/events/{id}/costs` |
| `PUT /api/costs/{id}` | `PATCH /api/v2/costs/{id}` |
| `DELETE /api/costs/{id}` | `DELETE /api/v2/costs/{id}` |
| `POST /api/uploads/{event-image|logo|favicon}` | `POST /api/v2/uploads/{event-image|logo|favicon}` |
| `GET /api/events/all` | `GET /api/v2/events/manage` |
| `POST /api/events` | `POST /api/v2/events` |
| `PUT /api/events/{id}` | `PATCH /api/v2/events/{id}` |
| `DELETE /api/events/{id}` | `DELETE /api/v2/events/{id}` |
| `POST /api/events/{id}/copy-from` | `POST /api/v2/events/{id}/copy-from` |
| `GET /api/events/{id}/notify-recipients` | `GET /api/v2/events/{id}/notify-recipients` |
| `PUT /api/events/{id}/notify-recipients` | `PUT /api/v2/events/{id}/notify-recipients` |
| `POST /api/webhooks/{yoco|payfast|whatsapp}` | `POST /api/v2/webhooks/{yoco|payfast|whatsapp}` |
| `POST /api/whatsapp/webhook` | `POST /api/v2/webhooks/whatsapp` |
| `POST /api/privacy/unsubscribe/{id}/one-click` | `POST /api/v2/unsubscribe/{id}/one-click` |
| `GET /api/privacy/me` | `GET /api/v2/me/privacy` |
| `PUT /api/privacy/me/news` | `PUT /api/v2/me/privacy/news` |
| `GET /api/privacy/me/export` | `GET /api/v2/me/privacy/export` |
| `POST /api/privacy/me/requests` | `POST /api/v2/me/privacy/requests` |
| `POST /api/privacy/me/notice/accept` | `POST /api/v2/me/privacy/notice/accept` |
| `GET /api/privacy/notice` | `GET /api/v2/privacy/notice` |
| `GET /api/privacy/unsubscribe/{id}` | `GET /api/v2/unsubscribe/{id}` |
| `POST /api/privacy/unsubscribe/{id}` | `POST /api/v2/unsubscribe/{id}` |
| `GET /api/privacy/requests` | `GET /api/v2/privacy/requests` |
| `POST /api/privacy/requests/{id}/{complete|reject}` | `POST /api/v2/privacy/requests/{id}/{complete|reject}` |
| `GET /api/privacy/notice/draft` | `GET /api/v2/privacy/notice/draft` |
| `PUT /api/privacy/notice/draft` | `PUT /api/v2/privacy/notice/draft` |
| `DELETE /api/privacy/notice/draft` | `DELETE /api/v2/privacy/notice/draft` |
| `POST /api/privacy/notice/{publish|builtin-reviewed}` | `POST /api/v2/privacy/notice/{publish|builtin-reviewed}` |
| `GET /api/privacy/operators` | `GET /api/v2/privacy/operators` |
| `POST /api/privacy/operators` | `POST /api/v2/privacy/operators` |
| `PUT /api/privacy/operators/{id}` | `PUT /api/v2/privacy/operators/{id}` |
| `DELETE /api/privacy/operators/{id}` | `DELETE /api/v2/privacy/operators/{id}` |
| `GET /api/privacy/{consent-log|access-log|readiness|retention|breaches}` | `GET /api/v2/privacy/{consent-log|access-log|readiness|retention|breaches}` |
| `PUT /api/privacy/retention` | `PUT /api/v2/privacy/retention` |
| `POST /api/privacy/retention/run` | `POST /api/v2/privacy/retention/run` |
| `POST /api/privacy/breaches` | `POST /api/v2/privacy/breaches` |
| `PUT /api/privacy/breaches/{id}` | `PUT /api/v2/privacy/breaches/{id}` |
| `GET /api/admin/{audit-log|jobs|impersonation-sessions}` | `GET /api/v2/admin/{audit-log|jobs|impersonation-sessions}` |
| `POST /api/admin/jobs/{id}/run` | `POST /api/v2/admin/jobs/{id}/run` |
| `POST /api/admin/impersonate/{end|log}` | `POST /api/v2/me/impersonation/{end|log}` |
| `GET /api/admin/impersonate/current` | `GET /api/v2/me/impersonation` |
| `POST /api/admin/impersonate/{id}` | `POST /api/v2/admin/impersonate/{id}` |
| `GET /api/settings/needs-setup` | `GET /api/v2/setup/needed` |
| `GET /api/settings/all` | `GET /api/v2/settings/all` |
| `GET /api/settings` | `GET /api/v2/settings` |
| `PUT /api/settings` | `PUT /api/v2/settings` |
| `POST /api/settings/test-smtp` | `POST /api/v2/settings/test-smtp` |
| `POST /api/setup/register` | `POST /api/v2/setup/register` |
| `POST /api/setup` | `POST /api/v2/setup` |
| `GET /api/hub/{status|notices}` | `GET /api/v2/hub/{status|notices}` |
| `POST /api/hub/{connect|heartbeat|update-request|update-snooze}` | `POST /api/v2/hub/{connect|heartbeat|update-request|update-snooze}` |
| `POST /api/hub/update-request/cancel` | `POST /api/v2/hub/update-request/cancel` |
| `GET /api/outbound-webhooks` | `GET /api/v2/outbound-webhooks` |
| `POST /api/outbound-webhooks` | `POST /api/v2/outbound-webhooks` |
| `POST /api/outbound-webhooks/deliveries/{id}/resend` | `POST /api/v2/outbound-webhook-deliveries/{id}/resend` |
| `PUT /api/outbound-webhooks/{id}` | `PATCH /api/v2/outbound-webhooks/{id}` |
| `DELETE /api/outbound-webhooks/{id}` | `DELETE /api/v2/outbound-webhooks/{id}` |
| `POST /api/outbound-webhooks/{id}/{rotate-secret|test}` | `POST /api/v2/outbound-webhooks/{id}/{rotate-secret|test}` |
| `GET /api/outbound-webhooks/{id}/deliveries` | `GET /api/v2/outbound-webhooks/{id}/deliveries` |
| `GET /api/backups` | `GET /api/v2/backups` |
| `POST /api/backups/run` | `POST /api/v2/backups/run` |
| `GET /api/backups/{id}/download` | `GET /api/v2/backups/{id}/download` |
| `GET /api/{yoco|payfast}/config` | `GET /api/v2/payments/{yoco|payfast}/config` |
| `PUT /api/{yoco|payfast}/config` | `PUT /api/v2/payments/{yoco|payfast}/config` |
| `GET /api/yoco/webhooks` | `GET /api/v2/payments/yoco/webhooks` |
| `POST /api/yoco/webhooks` | `POST /api/v2/payments/yoco/webhooks` |
| `DELETE /api/yoco/webhooks/{id}` | `DELETE /api/v2/payments/yoco/webhooks/{id}` |
| `POST /api/payfast/test` | `POST /api/v2/payments/payfast/test` |
| `POST /api/users/login/2fa/resend` | `POST /api/v2/auth/login/code/resend` |
| `POST /api/users/forgot` | `POST /api/v2/auth/password/forgot` |
| `POST /api/users/reset` | `POST /api/v2/auth/password/reset` |
| `POST /api/users/activate` | `POST /api/v2/auth/activate` |
| `POST /api/users/revoke-sessions` | `POST /api/v2/me/sessions/revoke` |
| `POST /api/users/close-account` | `POST /api/v2/me/close` |
| `GET /api/users/activity` | `GET /api/v2/me/activity` |
| `POST /api/users/verify-password` | `POST /api/v2/me/verify-password` |
| `POST /api/users/2fa/{enable|confirm|disable}` | `POST /api/v2/me/two-factor/{enable|confirm|disable}` |
| `GET /api/users/check-exists` | `GET /api/v2/users/exists` |
| `POST /api/users/{id}/revoke-sessions` | `POST /api/v2/users/{id}/sessions/revoke` |
| `POST /api/users/{id}/anonymize` | `POST /api/v2/users/{id}/anonymize` |
| `GET /api/users` | `GET /api/v2/users` |
| `GET /api/users/{?!profile$}{id}` | `GET /api/v2/users/{?!profile$}` |
| `PUT /api/users/{?!profile$}{id}` | `PATCH /api/v2/users/{?!profile$}` |
| `DELETE /api/users/{id}` | `DELETE /api/v2/users/{id}` |
| `GET /api/events/admin/all` | `GET /api/v2/admin/events` |
| `POST /api/events/{id}/{email|whatsapp}-attendees` | `POST /api/v2/events/{id}/{email|whatsapp}-attendees` |
| `POST /api/events/{id}/{email|whatsapp}-attendees/schedule` | `POST /api/v2/events/{id}/{email|whatsapp}-attendees/schedule` |
| `POST /api/broadcasts/{preview|send|schedule}` | `POST /api/v2/broadcasts/email/{preview|send|schedule}` |
| `POST /api/whatsapp-broadcasts/{preview|send|schedule}` | `POST /api/v2/broadcasts/whatsapp/{preview|send|schedule}` |
| `GET /api/scheduled-emails` | `GET /api/v2/scheduled-messages` |
| `PATCH /api/scheduled-emails/{id}` | `PATCH /api/v2/scheduled-messages/{id}` |
| `DELETE /api/scheduled-emails/{id}` | `DELETE /api/v2/scheduled-messages/{id}` |
| `POST /api/automations/schedule` | `POST /api/v2/automations/schedule` |
| `GET /api/whatsapp/{config|status|qr}` | `GET /api/v2/whatsapp/{config|status|qr}` |
| `POST /api/whatsapp/config` | `GET/PUT /api/v2/whatsapp/config` |
| `POST /api/whatsapp/create-instance` | `POST /api/v2/whatsapp/instance` |
| `POST /api/whatsapp/delete-instance` | `POST /api/v2/whatsapp/instance` |
| `POST /api/whatsapp/{request-code|logout|start|restart}` | `POST /api/v2/whatsapp/{request-code|logout|start|restart}` |
| `GET /api/banner` | `GET /api/v2/banner` |
| `POST /api/banner` | `GET/PUT /api/v2/banner` |
| `GET /api/saved-filters` | `GET /api/v2/saved-filters` |
| `POST /api/saved-filters` | `POST /api/v2/saved-filters` |
| `PUT /api/saved-filters/{id}` | `PUT /api/v2/saved-filters/{id}` |
| `DELETE /api/saved-filters/{id}` | `DELETE /api/v2/saved-filters/{id}` |
| `GET /api/dashboard/{today|search}` | `GET /api/v2/dashboard/{today|search}` |
| `GET /api/stats/{staff|supervisor|admin|overview}` | `GET /api/v2/stats/{staff|supervisor|admin|overview}` |
| `POST /api/analytics/track` | `POST /api/v2/analytics/track` |
| `GET /api/analytics/funnel` | `GET /api/v2/analytics/funnel` |
| `POST /api/reports/{pdf|excel|email|whatsapp}` | `POST /api/v2/reports/{pdf|excel|email|whatsapp}` |
| `GET /api/kids/me` | `GET /api/v2/me/family` |
| `POST /api/kids/me` | `POST /api/v2/me/family` |
| `PUT /api/kids/me` | `PATCH /api/v2/me/family` |
| `DELETE /api/kids/me` | `DELETE /api/v2/me/family` |
| `POST /api/kids/me/{children|adults}` | `POST /api/v2/me/family/{children|adults}` |
| `PUT /api/kids/me/{children|adults}/{id}` | `PUT /api/v2/me/family/{children|adults}/{id}` |
| `DELETE /api/kids/me/{children|adults}/{id}` | `DELETE /api/v2/me/family/{children|adults}/{id}` |
| `GET /api/kids/setup-events` | `GET /api/v2/kids/setup-events` |
| `GET /api/kids/events` | `GET /api/v2/kids/events` |
| `GET /api/kids/events/{id}/{settings|board|families|offline}` | `GET /api/v2/events/{id}/kids/{settings|board|families|offline}` |
| `PUT /api/kids/events/{id}/settings` | `PUT /api/v2/events/{id}/kids/settings` |
| `POST /api/kids/events/{id}/{families|check-in|check-out|duty|sync}` | `POST /api/v2/events/{id}/kids/{families|check-in|check-out|duty|sync}` |
| `GET /api/kids/events/{id}/families/qr/{id2}` | `GET /api/v2/events/{id}/kids/families/qr/{id2}` |
| `GET /api/kids/events/{id}/families/{id2}` | `GET /api/v2/events/{id}/kids/families/{id2}` |
| `POST /api/kids/events/{id}/families/{id2}/{parents|children|adults}` | `POST /api/v2/events/{id}/kids/families/{id2}/{parents|children|adults}` |
| `PUT /api/kids/events/{id}/families/{id2}/children/{id3}` | `PUT /api/v2/events/{id}/kids/families/{id2}/children/{id3}` |
| `GET /api/kids/events/{id}/code/{id2}` | `GET /api/v2/events/{id}/kids/code/{id2}` |
| `POST /api/kids/check-ins/{id}/{override|page}` | `POST /api/v2/kids/check-ins/{id}/{override|page}` |
| `PUT /api/kids/check-ins/{id}/room` | `PUT /api/v2/kids/check-ins/{id}/room` |
| `POST /api/kids/alerts/{id}/resolve` | `POST /api/v2/kids/alerts/{id}/resolve` |
| `GET /api/volunteers/me` | `GET /api/v2/me/volunteering` |
| `GET /api/volunteers/events/{id}` | `GET /api/v2/events/{id}/volunteer-roles` |
| `POST /api/volunteers/roles/{id}/sign-up` | `POST /api/v2/volunteer-roles/{id}/sign-up` |
| `DELETE /api/volunteers/slots/{id}` | `DELETE /api/v2/volunteer-slots/{id}` |
| `POST /api/volunteers/slots/{id}/swap` | `POST /api/v2/volunteer-slots/{id}/swap` |
| `DELETE /api/volunteers/swaps/{id}` | `DELETE /api/v2/volunteer-swaps/{id}` |
| `POST /api/volunteers/swaps/{id}/accept` | `POST /api/v2/volunteer-swaps/{id}/accept` |
| `POST /api/volunteers/check-in` | `POST /api/v2/volunteering/check-in` |
| `GET /api/volunteers/manage/events` | `GET /api/v2/volunteering/events` |
| `GET /api/volunteers/manage/hours` | `GET /api/v2/volunteering/hours` |
| `GET /api/volunteers/manage/events/{id}` | `GET /api/v2/events/{id}/volunteers` |
| `GET /api/volunteers/manage/events/{id}/{qr|settings}` | `GET /api/v2/events/{id}/volunteers/{qr|settings}` |
| `PUT /api/volunteers/manage/events/{id}/settings` | `PUT /api/v2/events/{id}/volunteers/settings` |
| `POST /api/volunteers/manage/events/{id}/roles` | `POST /api/v2/events/{id}/volunteer-roles` |
| `PUT /api/volunteers/manage/roles/{id}` | `PATCH /api/v2/volunteer-roles/{id}` |
| `DELETE /api/volunteers/manage/roles/{id}` | `DELETE /api/v2/volunteer-roles/{id}` |
| `POST /api/volunteers/manage/roles/{id}/assign` | `POST /api/v2/volunteer-roles/{id}/assign` |
| `POST /api/volunteers/manage/slots/{id}/check-in` | `POST /api/v2/volunteer-slots/{id}/check-in` |
| `DELETE /api/volunteers/manage/slots/{id}` | `POST /api/v2/volunteer-slots/{id}/remove` |
| `GET /api/tickets/mytickets` | `GET /api/v2/me/tickets` |
| `POST /api/tickets/email` | `POST /api/v2/me/tickets/email` |
| `GET /api/tickets/scans/recent` | `GET /api/v2/tickets/scans/recent` |
| `GET /api/tickets/scans/stats` | `GET /api/v2/tickets/scans/stats` |
| `POST /api/tickets/send-to` | `POST /api/v2/tickets/send` |
| `POST /api/tickets/generate` | `POST /api/v2/tickets/generate` |
| `PUT /api/tickets/email-sent` | `POST /api/v2/tickets/email-sent` |
| `GET /api/tickets/qr/{id}` | `GET /api/v2/tickets/qr/{id}` |
| `GET /api/tickets/event/{id}` | `GET /api/v2/events/{id}/tickets` |
| `GET /api/tickets/transfer-offer/{id}` | `GET /api/v2/ticket-transfers/{id}` |
| `POST /api/tickets/transfer-offer/{id}/{accept|decline}` | `POST /api/v2/ticket-transfers/{id}/{accept|decline}` |
| `GET /api/tickets` | `GET /api/v2/tickets` |
| `GET /api/tickets/{id}/transfers` | `GET /api/v2/tickets/{id}/transfers` |
| `POST /api/tickets/{id}/transfer` | `POST /api/v2/tickets/{id}/transfer` |
| `DELETE /api/tickets/{id}/transfer` | `DELETE /api/v2/tickets/{id}/transfer` |
| `GET /api/tickets/{id}` | `GET /api/v2/tickets/{id}` |
| `GET /api/scan-locks` | `GET /api/v2/scan-locks` |
| `POST /api/scan-locks` | `POST /api/v2/scan-locks` |
| `GET /api/scan-locks/reports` | `GET /api/v2/scan-locks/reports` |
| `POST /api/scan-locks/reports/{id}/review` | `POST /api/v2/scan-locks/reports/{id}/review` |
| `GET /api/scan-locks/{id}/snapshot` | `GET /api/v2/scan-locks/{id}/snapshot` |
| `POST /api/scan-locks/{id}/{sync|force-release}` | `POST /api/v2/scan-locks/{id}/{sync|force-release}` |
| `DELETE /api/scan-locks/{id}` | `DELETE /api/v2/scan-locks/{id}` |
| `GET /api/attendance/certificates/verify/{id}` | `GET /api/v2/certificates/verify/{id}` |
| `GET /api/attendance/certificates/mine` | `GET /api/v2/me/certificates` |
| `POST /api/attendance/certificates/preview` | `POST /api/v2/certificates/preview` |
| `GET /api/attendance/certificates/{id}/pdf` | `GET /api/v2/certificates/{id}/pdf` |
| `POST /api/attendance/certificates/{id}/revoke` | `POST /api/v2/certificates/{id}/revoke` |
| `GET /api/attendance/{id}/export` | `GET /api/v2/events/{id}/attendance/export` |
| `POST /api/attendance/{id}/mark` | `POST /api/v2/events/{id}/attendance` |
| `POST /api/attendance/{id}/certificates` | `POST /api/v2/events/{id}/certificates` |
| `POST /api/attendance/{id}/certificates/send` | `POST /api/v2/events/{id}/certificates/send` |
| `GET /api/attendance/{id}/certificates.pdf` | `GET /api/v2/events/{id}/certificates.pdf` |
| `GET /api/attendance/{id}` | `GET /api/v2/events/{id}/attendance` |
| `GET /api/allocations/my-groups` | `GET /api/v2/me/allocation-groups` |
| `GET /api/allocations/event/{id}` | `GET /api/v2/events/{id}/allocations` |
| `POST /api/allocations/sets` | `POST /api/v2/allocation-sets` |
| `PUT /api/allocations/sets/{id}` | `PATCH /api/v2/allocation-sets/{id}` |
| `DELETE /api/allocations/sets/{id}` | `DELETE /api/v2/allocation-sets/{id}` |
| `GET /api/allocations/sets/{id}/lists` | `GET /api/v2/allocation-sets/{id}/lists` |
| `POST /api/allocations/sets/{id}/{groups|auto}` | `POST /api/v2/allocation-sets/{id}/{groups|auto}` |
| `PUT /api/allocations/sets/{id}/assignments` | `PUT /api/v2/allocation-sets/{id}/assignments` |
| `DELETE /api/allocations/sets/{id}/assignments` | `DELETE /api/v2/allocation-sets/{id}/assignments` |
| `PUT /api/allocations/groups/{id}` | `PATCH /api/v2/allocation-groups/{id}` |
| `DELETE /api/allocations/groups/{id}` | `DELETE /api/v2/allocation-groups/{id}` |
| `GET /api/payments/providers` | `GET /api/v2/payments/providers` |
| `GET /api/payments/providers/settings` | `GET /api/v2/payments/providers/settings` |
| `PUT /api/payments/providers/settings` | `PUT /api/v2/payments/providers/settings` |
| `GET /api/payments/pay/{id}` | `GET /api/v2/payment-links/{id}` |
| `POST /api/payments/pay/{id}` | `POST /api/v2/payment-links/{id}` |
| `GET /api/payments/checkouts/open` | `GET /api/v2/payments/open-checkouts` |
| `POST /api/payments/checkouts/check` | `POST /api/v2/payments/open-checkouts/check` |
| `POST /api/payments/[yoco-]checkout/send` | `POST /api/v2/registrations/{id}/payment-link` |
| `GET /api/payments/mypayments` | `GET /api/v2/me/payments` |
| `GET /api/payments/admin/stats` | `GET /api/v2/payments/stats` |
| `GET /api/payments/registration/{id}` | `GET /api/v2/registrations/{id}/payments` |
| `GET /api/payments/event/{id}` | `GET /api/v2/events/{id}/payments` |
| `PUT /api/payments/assign-donation` | `POST /api/v2/payments/donations/assign` |
| `POST /api/payments/unassign-donation` | `POST /api/v2/payments/donations/unassign` |
| `POST /api/payments/refund` | `POST /api/v2/payments/refunds` |
| `POST /api/payments/{id}/send-receipt` | `POST /api/v2/payments/{id}/receipt` |
| `GET /api/payments` | `GET /api/v2/payments` |
| `POST /api/payments` | `POST /api/v2/payments` |
| `GET /api/payments/{id}` | `GET /api/v2/payments/{id}` |
| `GET /api/cashups/audit` | `GET /api/v2/cashups/audit` |
| `GET /api/cashups/event/{id}` | `GET /api/v2/events/{id}/cashup` |
| `GET /api/cashups/event/{id}/cash-by-user` | `GET /api/v2/events/{id}/cashup/cash-by-user` |
| `PUT /api/cashups/event/{id}/person-cash/{id2}` | `PUT /api/v2/events/{id}/cashup/person-cash/{id2}` |
| `PUT /api/cashups/event/{id}/draft` | `PUT /api/v2/events/{id}/cashup/draft` |
| `POST /api/cashups/event/{id}/close` | `POST /api/v2/events/{id}/cashup/close` |
| `POST /api/cashups/event/{id}/reopen` | `POST /api/v2/events/{id}/cashup/reopen` |
| `POST /api/cashups/lines/{id}/pending` | `POST /api/v2/cashup-lines/{id}/pending` |
| `GET /api/{provider|yoco}-transactions` | `GET /api/v2/provider-transactions` |
| `GET /api/{provider|yoco}-transactions/unreconciled` | `GET /api/v2/provider-transactions/unreconciled` |
| `POST /api/{?:provider|yoco}-transactions/{id}/reconcile` | `POST /api/v2/provider-transactions/{?:provider|yoco}/reconcile` |
| `POST /api/{?:provider|yoco}-transactions/{id}/ignore` | `POST /api/v2/provider-transactions/{?:provider|yoco}/ignore` |
| `POST /api/waitlist` | `POST /api/v2/waitlist` |
| `GET /api/waitlist/mine` | `GET /api/v2/me/waitlist` |
| `GET /api/waitlist/claim/{id}` | `GET /api/v2/waitlist/claims/{id}` |
| `GET /api/waitlist/events/{id}` | `GET /api/v2/events/{id}/waitlist` |
| `POST /api/waitlist/{id}/{offer|move|remove}` | `POST /api/v2/waitlist/{id}/{offer|move|remove}` |
| `DELETE /api/waitlist/{id}` | `DELETE /api/v2/waitlist/{id}` |
| `GET /api/sponsorships/event/{id}` | `GET /api/v2/events/{id}/sponsorship` |
| `GET /api/sponsorships/event/{id}/pool` | `GET /api/v2/events/{id}/sponsorship/pool` |
| `POST /api/sponsorships/checkout` | `POST /api/v2/sponsorships/checkout` |
| `GET /api/consent/events/{id}` | `GET /api/v2/events/{id}/consent` |
| `GET /api/consent/events/{id}/medical` | `GET /api/v2/events/{id}/consent/medical` |
| `POST /api/consent/events/{id}/{resend-pending|rerequest}` | `POST /api/v2/events/{id}/consent/{resend-pending|rerequest}` |
| `POST /api/consent/requests/{id}/resend` | `POST /api/v2/consent-requests/{id}/resend` |
| `GET /api/consent/{id}` | `GET /api/v2/consent/{id}` |
| `POST /api/consent/{id}` | `POST /api/v2/consent/{id}` |
| `GET /api/forms/responses` | `GET /api/v2/form-responses` |
| `GET /api/feedback/summary` | `GET /api/v2/feedback/summary` |
| `GET /api/feedback/public/{id}` | `GET /api/v2/feedback-forms/{id}` |
| `POST /api/feedback/public/{id}` | `POST /api/v2/feedback-forms/{id}` |
| `GET /api/feedback/event/{id}` | `GET /api/v2/events/{id}/feedback` |
| `PUT /api/feedback/event/{id}` | `PUT /api/v2/events/{id}/feedback` |
| `DELETE /api/feedback/event/{id}` | `DELETE /api/v2/events/{id}/feedback` |
| `POST /api/feedback/event/{id}/send-now` | `POST /api/v2/events/{id}/feedback/send-now` |
| `GET /api/registrations` | `GET /api/v2/registrations` |
| `GET /api/registrations/myregistrations` | `GET /api/v2/me/registrations/full` |
| `GET /api/registrations/event/{id}` | `GET /api/v2/events/{id}/registrations` |
| `POST /api/registrations/manual` | `GET /api/v2/registrations/manual` |
| `POST /api/registrations/bulk` | `GET /api/v2/registrations/bulk` |
| `PUT /api/registrations/{id}/options` | `PUT /api/v2/registrations/{id}/items` |
| `POST /api/registrations/{id}/send-invoice` | `POST /api/v2/registrations/{id}/invoice` |
| `POST /api/registrations/{id}/coupon` | `POST /api/v2/registrations/{id}/coupon` |
| `DELETE /api/registrations/{id}/coupon` | `DELETE /api/v2/registrations/{id}/coupon` |
| `PUT /api/registrations/{id}/attendees` | `PUT /api/v2/registrations/{id}/attendees` |
| `POST /api/registrations/{id}/attendees/{id2}/send-form-link` | `POST /api/v2/registrations/{id}/attendees/{id2}/form-link` |
| `GET /api/registrations/{id}/forms/draft` | `GET /api/v2/registrations/{id}/form-draft` |
| `PUT /api/registrations/{id}/forms/draft` | `PUT /api/v2/registrations/{id}/form-draft` |
| `POST /api/registrations/{id}/forms/responses` | `POST /api/v2/registrations/{id}/form-responses` |
| `PUT /api/registrations/{id}/forms/responses` | `PUT /api/v2/registrations/{id}/form-responses` |
| `GET /api/registrations/{id}` | `GET /api/v2/registrations/{id}/full` |
| `PUT /api/registrations/{id}` | `PATCH /api/v2/registrations/{id}/status` |
| `GET /api/series` | `GET /api/v2/series` |
| `POST /api/series` | `POST /api/v2/series` |
| `GET /api/series/by-slug/{id}` | `GET /api/v2/series/by-slug/{id}` |
| `GET /api/series/{id}/compare` | `GET /api/v2/series/{id}/compare` |
| `POST /api/series/{id}/follow` | `PUT/DELETE /api/v2/series/{id}/follow` |
| `DELETE /api/series/{id}/follow` | `DELETE /api/v2/series/{id}/follow` |
| `PUT /api/series/{id}` | `PATCH /api/v2/series/{id}` |
| `DELETE /api/series/{id}` | `DELETE /api/v2/series/{id}` |
| `GET /api/season-passes/mine` | `GET /api/v2/me/season-passes` |
| `POST /api/season-passes/purchases/{id}/checkout` | `POST /api/v2/season-pass-purchases/{id}/checkout` |
| `POST /api/season-passes/{id}/buy` | `POST /api/v2/season-passes/{id}/buy` |
| `GET /api/season-passes` | `GET /api/v2/season-passes` |
| `POST /api/season-passes` | `POST /api/v2/season-passes` |
| `PUT /api/season-passes/{id}` | `PATCH /api/v2/season-passes/{id}` |
| `DELETE /api/season-passes/{id}` | `DELETE /api/v2/season-passes/{id}` |
| `POST /api/bundles/quote` | `PATCH/DELETE /api/v2/bundles/quote` |
| `GET /api/bundles/event/{id}` | `GET /api/v2/events/{id}/bundles` |
| `POST /api/bundles/event/{id}` | `POST /api/v2/events/{id}/bundles` |
| `PUT /api/bundles/{id}` | `PATCH /api/v2/bundles/{id}` |
| `DELETE /api/bundles/{id}` | `DELETE /api/v2/bundles/{id}` |
| `POST /api/coupons/validate` | `GET/PATCH /api/v2/coupons/check` |
| `GET /api/coupons/redemptions` | `GET /api/v2/coupons/redemptions` |
| `GET /api/coupons` | `GET /api/v2/coupons` |
| `POST /api/coupons` | `POST /api/v2/coupons` |
| `GET /api/coupons/{id}` | `GET /api/v2/coupons/{id}` |
| `PUT /api/coupons/{id}` | `PATCH /api/v2/coupons/{id}` |
| `GET /api/campuses` | `GET /api/v2/campuses` |
| `GET /api/campuses/admin` | `GET /api/v2/campuses/admin` |
| `GET /api/campuses/by-slug/{id}` | `GET /api/v2/campuses/by-slug/{id}` |
| `PUT /api/campuses/settings` | `PUT /api/v2/campuses/enabled` |
| `PUT /api/campuses/order` | `PUT /api/v2/campuses/order` |
| `POST /api/campuses` | `POST /api/v2/campuses` |
| `GET /api/campuses/{id}/audience` | `GET /api/v2/campuses/{id}/audience` |
| `PUT /api/campuses/{id}` | `PATCH /api/v2/campuses/{id}` |
| `DELETE /api/campuses/{id}` | `DELETE /api/v2/campuses/{id}` |
| `GET /api/users/profile` | `GET /api/v2/me` |
| `PUT /api/users/profile` | `PATCH /api/v2/me` |
| `POST /api/users` | `POST /api/v2/auth/signup` |
| `POST /api/users/login` | `POST /api/v2/auth/login` |
| `POST /api/users/login/2fa` | `POST /api/v2/auth/login/code` |
| `POST /api/registrations` | `POST /api/v2/registrations` |
| `DELETE /api/registrations/{id}` | `POST /api/v2/registrations/{id}/cancel` |
| `POST /api/payments/checkout` | `POST /api/v2/registrations/{id}/checkout` |
| `GET /api/tickets/scan-preview/{id}` | `GET /api/v2/checkin/{id}` |
| `POST /api/tickets/scan/{id}` | `POST /api/v2/checkin/{id}` |
+252
View File
@@ -0,0 +1,252 @@
# Cross Events Platform
Cross Events is a full-stack event management platform that allows users to browse events, register for them, make payments, and manage their tickets.
## Project Structure
The project is divided into two main parts:
- Backend: Node.js + Express + Prisma + PostgreSQL
- Frontend: Next.js (React) + Tailwind CSS
### Backend
The backend provides a RESTful API for managing users, events, registrations, payments, uploads, and tickets. It includes:
- JWT-based authentication and role-based authorization
- Event and registration management
- Payment integration with Yoco (checkout + webhooks)
- Ticket generation (PDF + QR) and email delivery
- Static uploads for event images
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
- Backend README: ./backend/README.md
### Frontend
The frontend is a Next.js app that provides:
- User authentication (login, register)
- Browse/search events and view details
- Register for events and pay via Yoco
- Manage and view tickets
Documentation: see Frontend README for environment and scripts.
- Frontend README: ./frontend/README.md
## Getting Started (Local Development)
### Prerequisites
- Node.js 18+ (recommended)
- npm or yarn
- PostgreSQL database
### 1) Install dependencies
- Backend
- cd backend
- npm install
- Frontend
- cd ../frontend
- npm install
### 2) Configure environment variables
- Backend: create backend/.env and set required variables (see backend/README.md). At minimum:
- DATABASE_URL
- JWT_SECRET
- PORT (optional; defaults to 3000 if not set)
- EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS, EMAIL_FROM (for ticket emails)
- FRONTEND_URL or APP_BASE_URL (used in email links)
- Frontend: create frontend/.env.local and set
- NEXT_PUBLIC_API_URL=http://localhost:<backend-port>
Example for default backend: NEXT_PUBLIC_API_URL=http://localhost:5000
- Organisation name, logo, brand colour, and notification emails are configured via the admin panel (Admin → Site Settings) and do not need to be set in .env files.
- Yoco payments are set up in Admin → Site Settings → Payments: paste the secret key, then generate the webhook (or enter its secret). YOCO_SECRET_KEY / YOCO_WEBHOOK_SECRET in backend/.env still work as fallbacks.
### 3) Run the apps
- Start backend (development):
- cd backend
- npm run dev
- By default runs at http://localhost:3000 (or the PORT you set)
- Start frontend (development):
- cd ../frontend
- npm run dev
- Next.js dev server runs at http://localhost:3000 by default; if it conflicts with backend, it will pick another port (e.g., 3001). Ensure NEXT_PUBLIC_API_URL points to the backend port.
## Tests
- Backend unit tests: `cd backend && npm test`
- End-to-end tests (Playwright), from the repo root:
- once: `npm install` and `npx playwright install chromium`
- `npm run test:e2e`
- They start their own backend (port 5100) and frontend (port 3100) against a separate
database — `backend/.env`'s `DATABASE_URL` with `_e2e` added to the name, or
`E2E_DATABASE_URL` — which is dropped, recreated and seeded on every run. Your own dev
servers and database aren't touched. The database user needs permission to create
databases.
- There's no CI: run these yourself, plus `npx eslint .` in `frontend/`, before tagging a
release (the deploy's `next build` fails on any lint error). Releases are deployed by hand
with `scripts/deploy.sh` (see [DEPLOYMENT.md](./DEPLOYMENT.md)).
## Deployment
### A new install
On a fresh Ubuntu 22.04/24.04 server, with the domain's DNS already pointing at it:
```bash
curl -fsSLO https://c-git.crosscode.co.za/joshua/hope-events/raw/branch/main/scripts/install.sh
sudo bash install.sh --domain events.yourchurch.org --email you@yourchurch.org [--version v1.41.0]
```
It installs Node 24 LTS, PostgreSQL (with its own database and a random password), PM2, nginx (the
API, uploads, `/health` and `/docs` to the backend, everything else to the site) and an HTTPS
certificate, writes `backend/.env` and `frontend/.env.production`, migrates, builds and starts the
app. Then open `https://<domain>/setup`: create the admin account and enter the **licence key**
to connect the site to the Cross Events Hub. Several installs can share a server with different
`--name`, `--dir`, `--web-port` and `--api-port`. Run `--help` for all options.
Behind an frp tunnel (no public IP on the server)? See [DEPLOYMENT.md](DEPLOYMENT.md).
### Updating
To update a running install, on the server in the repo folder:
- `bash scripts/deploy.sh` — the latest `main`
- `bash scripts/deploy.sh v1.37.4` — a tagged release
It backs up the database, checks the version out, installs, migrates, builds and reloads PM2.
If anything fails before the reload, it goes back to the previous version (the running app
isn't touched).
PM2 uses the install's own `ecosystem.config.js` (app names, frontend port). It isn't in git,
so deploys never change it; the first deploy creates it from `ecosystem.config.example.js` —
set names that match your PM2 apps (`pm2 ls`) and the port you use.
### Backend Deployment
1. Provision a PostgreSQL database and set DATABASE_URL.
2. Set all required environment variables (see backend/README.md).
3. Run Prisma migrations (if applicable).
4. Start the server with: npm start (or a process manager like PM2).
5. Expose the webhook endpoint /api/v2/webhooks/yoco publicly and register it with Yoco (Site settings → Payments → Yoco → Generate does this).
6. Ensure the uploads directory public/uploads exists and is writable.
### Frontend Deployment
1. Build the frontend:
- cd frontend
- npm run build
2. Run with npm start (Next.js) on your server, or deploy to a platform like Vercel.
3. Ensure NEXT_PUBLIC_API_URL points to the public URL of your backend (including port if not 80/443).
### Ports and URLs
- Backend default port is 3000 unless overridden by PORT.
- Frontend dev server commonly uses 3000; set NEXT_PUBLIC_API_URL to avoid clashes (e.g., backend 3000, frontend 3001).
## Useful Links
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
- Backend README: ./backend/README.md
- Frontend README: ./frontend/README.md
- Site Settings — defaults reference: ./SETTINGS.md
- Feature overview: ./FEATURES.md
## Recent Changes
> Older notes, kept for history. The `/api/…` paths they mention are API v1, removed in 2.0 —
> MIGRATING-TO-2.md lists each one's v2 replacement. Since 1.33 the changes are in CHANGELOG.md.
### Sold-out handling, tiered stock warnings & UI polish
**Backend**
- `GET /api/events` now computes and returns `isSoldOut: boolean` per event — true when every option with a stock limit (`stockLimit > 0`) is fully sold out. Events with only unlimited options are never sold out.
- `POST /api/settings/test-smtp` error responses now include a `raw` field (the original error message) alongside the human-readable `message`. Error code 530 (Microsoft "Client not authenticated to send mail") is now correctly mapped to the authentication-failure message.
**Frontend**
- **Event listing** (`/events`): `EventCard` shows a disabled "Sold Out" button (red tint) when `isSoldOut` is true, replacing the Register button. Free events now show "Register" without the "- R0.00" suffix.
- **Event detail page** (`/events/[id]`): computes sold-out state from returned option `availableCount`; shows a disabled "Sold Out" button instead of the Register link. Options with price `0` display "Free" instead of "R0.00".
- **Registration page** (`/register/[eventId]`): shows a red "This event is sold out" banner and replaces the Register button with a disabled "Sold Out" button when all limited options are exhausted.
- **Tiered low-stock threshold**: the "X remaining" badge now uses capacity-based percentages — ≤ 50 tickets: 20 %; 51–200: 15 %; 201–1,000: 10 %; 1,000+: 5 %. Changed from `Math.ceil` to `Math.round` to prevent rounding-up inflation of the threshold. Fixed a React rendering bug where `stockLimit && stockLimit > 0 && ...` evaluated to the number `0` (which React renders as visible text) instead of a boolean — this caused "00" to appear next to options with unlimited stock (`stockLimit = 0`).
- **Event image upload**: the EventForm (used in the create modal) now shows a file upload button with inline preview alongside the URL input field. Files are uploaded to `POST /api/uploads/event-image` and the returned URL is set automatically.
- **Attachments during event creation**: step 6 ("Attachments") of the supervisor create-event wizard now lets you stage files. They are uploaded to `POST /api/events/:id/attachments` immediately after the event record is created, so attachments no longer require a separate edit session.
- **SMTP test details**: on failure the "Test connection" result now shows a collapsible "Show technical details" section exposing the raw SMTP error alongside the friendly message. `ApiError` in `src/lib/api.ts` now carries a `data` field with the full JSON response body.
### Variants, stock limits, early-bird pricing & cancellation guard
**Backend**
- **`OptionVariant` model**: event options can now have sub-variants (sizes, colours, ticket types — e.g. Adult/Child/VIP under a single "Ticket" option). Variants have an optional `price` override and their own `stockLimit`.
- **Stock limits**: `stockLimit` added to `EventOption` and `EarlyBirdTier`. A value of `0` means unlimited. All stock counts exclude cancelled registrations.
- **Early-bird concurrency handling**: once a Yoco checkout has been issued at an early-bird price, that price is honoured even if another user simultaneously exhausts the tier's stock. Stock-based forfeiture only applies at registration time (via `resolveOptionPrice`). Deadline expiry at payment time forfeits the price; stock races after the checkout is issued do not.
- **Early-bird stock forfeiture**: if a tier's deadline passes after registration but before payment, `refreshPricingForRegistration` (called before every Yoco checkout) re-evaluates the tier and updates `priceSnapshot`. If prices changed, `POST /api/payments/checkout` returns `{ priceUpdated: true, newTotal }` (HTTP 200) so the frontend can show a warning before retrying.
- **`priceSnapshot` / `appliedTierId`** on `RegistrationOption`: price and tier are snapshotted at registration creation. `computeRegistrationTotalDue` uses `priceSnapshot` as authoritative when present (legacy rows without a snapshot fall back to deadline-only re-evaluation).
- **Cancelled registration tickets**: `GET /api/tickets/mytickets` now excludes tickets from cancelled registrations at the database level.
- **Cancellation payment guard**: `DELETE /api/registrations/:id` blocks non-admins from cancelling a registration that has positive payments. Admins can cancel at any time.
- **Variant CRUD**: `POST /api/events/options/:id/variants`, `PUT /api/events/variants/:id`, `DELETE /api/events/variants/:id`.
- **Testing mode** (`NODE_ENV=testing`): behaves like development (permissive CORS, all debug routes) but validates required env vars (`DATABASE_URL`, `JWT_SECRET`) at startup and enables rate limiting.
**Frontend**
- **Register page** (`/register/[eventId]`): variant picker — when an option has variants, shows each variant with its own qty control, stock badge (sold out / X remaining at ≤ 15 %), and price. Submission payload includes `variantId`. Early-bird notice shown when any active tier is present.
- **Event detail page** (`/events/[id]`): ticket section shows variant breakdown with "From R…" pricing, early-bird strikethrough, and sold-out/nearly-out badges.
- **User dashboard**: "Cancel registration" button appears in the registration modal when no payments have been made. Inline confirmation before the API call.
- **Pay page**: if the backend returns `priceUpdated: true`, an amber warning banner shows the new total and a dismiss button before the user can retry.
- **Supervisor events page** (`/dashboard/supervisor/events`): 6-step create/edit modal — "Basic Details", "Items & Pricing", "Sections", "Form", "Visibility", "Attachments". In create mode, step tabs are not clickable (linear navigation only); in edit mode any step can be jumped to. Options in "Items & Pricing" are collapsible cards; Variants and Early-bird tiers are expandable sub-sections within each option. `/dashboard/supervisor/sections` now redirects to the Events page.
- **Legal pages**: Terms of Use updated with early-bird pricing terms, partial payment terms, and self-cancellation policy. Privacy Policy updated with data anonymisation details.
### Site settings & first-time setup wizard
- **Admin → Site Settings** (`/dashboard/admin/settings`): organisation details, branding (colour + logo), notification emails, **SMTP email delivery**, and **legal page content** are stored in the database and editable at runtime.
- **Setup wizard** (`/setup`): on a fresh deployment (empty database) the platform automatically shows a wizard — organisation details, admin account creation, and branding. No manual DB seeding required.
- **`/api/settings`** (public): exposes public settings (org details, legal keys) for navbar and legal pages.
- **`/api/setup`** (public, one-time): creates the first admin account; blocked once any user exists.
- **Settings cache** (`settingsCache.js`): in-process 60-second cache with transparent AES-256-GCM decryption for sensitive keys.
- **SMTP via admin panel**: host, port, TLS, from address, username, and password are all configurable without touching `.env`. Password is stored AES-256-GCM encrypted (key derived from `JWT_SECRET`).
- **Legal pages dynamic**: Terms of Use and Privacy Policy populate org name, contact email, website URL, operator name, Information Officer details, and effective date from the settings DB.
- **`ORG_NAME`, `ORG_TAGLINE`, `EMAIL_HEADER_COLOR`, `REGISTRATIONS_EMAIL`, SMTP vars** no longer required in `.env` — all managed via the admin panel (env vars still work as fallbacks).
### Admin dashboard improvements
- **User management** (`/dashboard/admin/users`): filtering (role, active status, text search) is now server-side so page size is always consistent; per-page selector (10/25/50/100); "Delete data" button anonymises a user's personal information via `POST /api/users/:id/anonymize`.
- **Registrations** (`/dashboard/admin/registrations`): event dropdown, status, and fuzzy text filters; expandable rows showing ticket options and form responses loaded on demand.
### Forms page (`/dashboard/supervisor/forms`, `/dashboard/admin/forms`)
- **Print** opens a clean popup window (no site chrome) with one form response per A4 page — event name, attendee details, registration ID, and answers in a two-column grid.
- **User filter** replaced raw "User ID" text input with a searchable name/email/phone dropdown.
- **Event filter** includes "Include past events" and "Include inactive events" checkboxes.
- Filters in a responsive grid; dropdowns constrained to `max-w-xs`.
### Ticket printing
- **At-the-door individual print**: individual ticket print now generates a proper A6 ticket with QR code, event title, date, type, holder name, and ID — no longer just a UUID.
- **Staff event-tickets page**: A4 print layout matches at-the-door (2 columns × 4 rows, 8 tickets per page).
### Form builder & events
- **Form builder**: up/down reorder buttons; type badge (Text/Number/Date/etc.); separate quick-add buttons for Statement and Heading fields.
- **Early-bird tiers**: no manual order number — tiers ordered by list position; labelled Deadline and Price inputs.
### Bulk messaging dropdowns
- Attendee selection dropdown constrained to `max-w-xs` / `w-64` panel on email-attendees and whatsapp-attendees pages.
### Backend
- `GET /api/users` supports server-side `?search=`, `?role=`, `?isActive=` filtering.
- `POST /api/users/:id/anonymize` — erases personal data (admin only).
- `GET|PUT /api/settings`, `GET /api/settings/needs-setup`, `POST /api/setup` — settings and setup endpoints.
- `POST /api/uploads/logo` — logo upload (admin, or unauthenticated during first-time setup).
- `backend/src/utils/encryption.js` — AES-256-GCM encrypt/decrypt; key derived from `JWT_SECRET` via scrypt.
- SMTP transporter rebuilt dynamically when settings cache detects a config change — no restart required after updating SMTP settings.
## License
This project is licensed under the MIT License.
+140
View File
@@ -0,0 +1,140 @@
# Site Settings — Defaults Reference
Every setting below is stored as a row in the `AppSetting` key-value table and
is editable at runtime via **Admin → Site Settings** (or, for the first few,
the `/setup` wizard on a fresh install). None of them are required — this
page documents exactly what happens when a given key has never been saved.
Settings changes take effect within 60 seconds everywhere (the backend's
in-process settings cache TTL) without a server restart.
## Organisation
| Setting | Default when unset | Notes |
|---|---|---|
| `org_name` | `"Cross Code"` | Falls back to `ORG_NAME` env var first, then this hardcoded default (the platform vendor's name, used as a neutral placeholder — `org_name` is a required field in the setup wizard, so this fallback is practically unreachable once a site has been set up). Shown in the navbar, email headers/subjects, and WhatsApp messages. |
| `org_tagline` | `"Connecting community through events"` | Falls back to `ORG_TAGLINE` env var first. Shown under the org name in the email header. |
| `org_email` | *(blank)* | No fallback in most places. **Exception:** the Terms of Use / Privacy Policy pages default to `privacy@example.com` (an obvious placeholder) if unset — see the Legal section below. |
| `org_phone` / `org_address` | *(blank)* | No fallback — simply omitted wherever shown if unset. |
| `app_base_url` | `APP_BASE_URL` or `FRONTEND_URL` env var, else `http://localhost:3001` | Used to build links in emails (password reset, ticket delivery, etc.). Should always be set in production. |
| `APP_TIMEZONE` (env) | `Africa/Johannesburg` | The site's time zone (an IANA name, e.g. `Europe/London`): background job schedules (e.g. the 07:00 daily summary), session dates and printed times. Also sent to the Hub in the heartbeat. Needs a backend restart. |
## Branding
| Setting | Default when unset | Notes |
|---|---|---|
| `primary_color` | Legacy `accent_color` value if present, else `#4F46E5` (indigo) on the website / `#1e3a5f` (navy) in emails | See [Two different fallbacks](#two-different-fallbacks-for-primary_color) below — this is the one setting with a genuine inconsistency worth knowing about. Drives buttons, links, nav highlights, and the email header/CTA. The Branding tab warns when it is under 4.5:1 against white (too light for white text and links) and offers a darker shade (1.50.0). |
| `secondary_color` | `210 40% 96.1%` background / near-black text (light gray "wash", shadcn's stock theme) | The Branding tab's color picker *pre-fills* `#8B5CF6` as a suggested starting point, but that's only a UI default — if you never hit Save, the actual site uses the light-gray fallback, not violet. |
| `accent_color` | `210 40% 96.1%` background / near-black text (same light gray as Secondary) | Same story as Secondary — the picker pre-fills `#EC4899` (pink) as a suggestion only. |
| `logo_url` | Bundled logo (`frontend/src/app/church_logo.jpg`) | Shown in the navbar. This is still the original Hope Family Church artwork checked into the repo — swap the file (or upload a real logo via the Branding tab) before deploying for a different organisation. |
| `favicon_url` | `frontend/public/favicon.ico` (the site's original generic favicon) | Shown in the browser tab. |
### Two different fallbacks for `primary_color`
If `primary_color` has *never* been saved (no admin has ever used the new
3-color Branding tab) **and** there's no legacy `accent_color` value either,
the website and outgoing emails currently disagree on what "no color" means:
- **Website** (`globals.css` / `tailwind.config.js` static defaults): `#4F46E5`, a bright indigo.
- **Emails** (`backend/src/utils/email.js` `getOrg()`): `#1e3a5f`, a dark navy — unless overridden by the `EMAIL_HEADER_COLOR` env var.
In practice this only matters on a brand-new install before the setup wizard
or Branding tab has been saved even once — the wizard always writes
`primary_color`, so this gap closes itself the moment setup completes.
## Notifications
| Setting | Default when unset | Notes |
|---|---|---|
| `reg_notification_emails` | `REGISTRATIONS_EMAIL` env var, else *(blank)* | If truly blank, no internal notification email is sent for new registrations/payments/donations — it's silently skipped, not an error. |
## Email delivery (SMTP)
| Setting | Default when unset | Notes |
|---|---|---|
| `smtp_host` | `SMTP_HOST`/`EMAIL_HOST` env var, else *(blank)* | If blank, the app **does not send real email** — it uses nodemailer's `jsonTransport`, which just logs the would-be email to the console. This is the single biggest "nothing is configured" gotcha — ticket/payment/password-reset emails silently don't go anywhere until SMTP is set up. |
| `smtp_port` | `587` | |
| `smtp_secure` | `false` | |
| `smtp_user` / `smtp_pass` | *(blank)* | Stored AES-256-GCM encrypted (key derived from `JWT_SECRET`). |
| `smtp_from` | *(blank)* | If blank, outgoing mail's `From:` address falls back to the literal `no-reply@crosscode.local`. |
## Payments
Managed in the Payments tab (through `/api/v2/payments/providers/settings` and `/api/v2/payments/yoco/config`, not the generic settings endpoints).
| Setting | Default when unset | Notes |
|---|---|---|
| `payfast_merchant_id` / `payfast_merchant_key` | `PAYFAST_MERCHANT_ID` / `PAYFAST_MERCHANT_KEY` env vars, else *(blank)* | From the PayFast (or Sandbox) dashboard. Both are needed before PayFast can take payments. The key isn't secret (it's in the payment form), so it's shown in full. Managed through `/api/payfast`. |
| `payfast_passphrase` | `PAYFAST_PASSPHRASE` env var, else *(blank)* | Stored encrypted. Must match the dashboard's salt passphrase exactly, or PayFast refuses payments ("signature does not match"). |
| `payfast_mode` | `PAYFAST_MODE` env var, else `sandbox` | `sandbox` or `live`: where payers are sent and where notifications are confirmed. |
| `payment_providers` | Yoco enabled | JSON `{ order: [...], enabled: { yoco: true } }`: which online payment providers are on, and their order (the first one enabled and set up is the default). Providers not listed yet come last, switched off (Yoco on, as it was the only provider). If none is on and set up, online payments are off. |
| `yoco_secret_key` | `YOCO_SECRET_KEY` env var, else *(blank)* | Stored AES-256-GCM encrypted. If blank, online checkouts and sponsorships fail with "online payments are not configured". |
| `yoco_webhook_secret` | `YOCO_WEBHOOK_SECRET` env var, else *(blank)* | Stored encrypted. If blank, Yoco webhooks are rejected, so payments aren't confirmed automatically. |
| `yoco_webhook_id` | *(blank)* | The Yoco webhook whose secret is stored, set when it's generated from the tab. Used to mark it "Active" and to clear the secret when it's deleted. |
## Legal (Terms of Use / Privacy Policy)
| Setting | Default when unset | Notes |
|---|---|---|
| `legal_operator_name` | `"[operator details not yet configured]"` | Deliberately a generic, obviously-incomplete placeholder rather than any real person's or organisation's name. Unlike `org_name`, these legal fields are optional and can realistically stay unset on a live site — defaulting them to Cross Code's (or anyone else's) real identity would misrepresent who's legally responsible for that deployment. |
| `legal_io_name` | `"[not yet configured]"` | Same reasoning as `legal_operator_name`. |
| `legal_io_email` | `"io@example.com"` | Rendered as a `mailto:` link, so the placeholder stays a syntactically valid address on the IANA-reserved `example.com` domain rather than a bracketed non-email string that would break the link. |
| `legal_website_url` | `"example.com"` | Same reasoning — used to build an `https://` link. |
| `legal_effective_date` | `"[not yet set]"` | Plain text only, no link — a bracketed placeholder is fine here. Only used by the built-in privacy notice: once a version is published in Admin → Privacy, its publish date is the effective date. |
| `notify_user_on_impersonation` | `"false"` | When `"true"`, a user is emailed (with the reason) whenever an admin views their account with Impersonate. Set under Site Settings → Legal → Support access. |
| `consent_medical_retention_days` | `30` | Youth events: medical and emergency details from parental consent forms are deleted this many days after the event ends (daily 09:00 job). The consent record itself — who agreed, when, to which text — is kept. Set under Site Settings → Legal. |
| `org_email` (as used on legal pages specifically) | `"privacy@example.com"` | Different fallback than `org_email`'s general default (blank) — also rendered as a `mailto:` link, so it needs to stay a valid-looking address. |
## Campuses
| Setting | Default when unset | Notes |
|---|---|---|
| `campuses_enabled` | `false` | Site settings → Campuses → "Use campuses". Changed only through `PUT /api/v2/campuses/enabled` (audited); hidden from the generic settings endpoints. Off hides campus fields and filters everywhere; campuses and each event's campus are kept. The campuses themselves are in the `Campus` table. |
## Cross Events Hub (licence)
| Setting | Default when unset | Notes |
|---|---|---|
| `HUB_URL` (env) | `https://events-hub.crosscode.co.za` | Where the Hub runs. |
| `HUB_PUBLIC_KEY` (env) | The production key built into `backend/src/hub/publicKey.js` | Only for a local or test Hub. Licence tokens are checked with this key. |
| `HUB_HEARTBEAT_ENABLED` (env) | `true` | The 15-minute `hub-heartbeat` job (plus one check-in 30 s after starting and after connecting). Off means the licence isn't refreshed — after 30 days the site goes into grace, then read-only. |
| `LICENCE_CHECK_DISABLED` (env) | `false` | `true` turns read-only mode off — **ignored when `NODE_ENV=production`**. For the end-to-end tests and local development without a Hub. |
| `hub_install_id`, `hub_install_secret` (encrypted), `hub_licence`, `hub_last_heartbeat_at`, `hub_last_error`, `hub_latest_version` | — | Written only by `src/hub/client.js` when connecting and on each heartbeat. Never readable or writable through the generic settings endpoints. Deleting them disconnects the site (it becomes "no licence", which is read-only). The heartbeat deletes the install and licence keys itself when the Hub answers `INSTALL_NOT_FOUND`. |
## WhatsApp
| Setting | Default when unset | Notes |
|---|---|---|
| `WAWP_ACCESS_TOKEN` / `WAWP_INSTANCE_ID` | `WAWP_ACCESS_TOKEN`/`WAWP_INSTANCE_ID` env vars, else *(blank)* | No hardcoded default — WhatsApp sending is simply unavailable until both are configured (Admin → Site Settings → WhatsApp). |
| `WAWP_WEBHOOK_SECRET` | Generated (random) the first time the WhatsApp tab is opened | Part of the webhook URL shown in Site Settings → WhatsApp (`/api/v2/webhooks/whatsapp?secret=…`; set-ups from before 1.51.16 use `/api/whatsapp/webhook?secret=…`, which still works). WAWP doesn't sign webhooks, so incoming messages (STOP replies) are only acted on when the secret matches. Not editable in the UI; delete the row to get a new one (then update the URL in WAWP). The URL uses `BACKEND_URL`. |
## Privacy (POPIA)
| Setting | Default when unset | Notes |
|---|---|---|
| `legal_io_email` (Information Officer, Site Settings → Legal) | — | Also where new privacy requests and the daily "requests due" reminder are emailed, together with all admins. The `io@example.com` placeholder is skipped. |
| `PRIVACY_JOBS_ENABLED` (env) | `true` | The daily 08:00 `privacy` job that reminds admins of requests due within a week or overdue. |
| `retention_policies` | Inactive accounts 60 months (on), form answers 12, login history 24, payment details 24, children at kids check-in (`kids_profiles`) 6, audit/access logs 60 — all on | Admin → Privacy → Retention (JSON `{ policies: { key: { enabled, months } }, reviewedAt, reviewedBy }`). Minimums: inactive accounts and logs 12 months, login history and payment details 3, form answers and kids profiles 1; maximum 240. Saving marks them reviewed (readiness check). |
| `retention_last_run` | — | When the `retention` job last ran and what it did (readiness check: within 2 days). |
| `VOLUNTEER_JOBS_ENABLED` (env) | `true` | The `volunteers` job (every 15 minutes) that sends volunteer reminders the day before a shift. |
| `WEBHOOKS_JOBS_ENABLED` (env) | `true` | The `webhooks` job (every minute): sends deliveries that are due (retries), picks up sends cut off by a restart, deletes deliveries older than 30 days. New events are sent straight away without it. |
| `WEBHOOKS_ENABLED` (env) | `true` | `false` stops noticing events for outbound webhooks altogether (nothing new is queued). |
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints use http and private or local addresses — for local testing only (the e2e tests set it). |
| `SERIES_JOBS_ENABLED` (env) | `true` | The `series` job (every 15 minutes) that emails a series' followers once when a new event in it goes live (News & announcements: only people opted in to news). |
| `RETENTION_JOBS_ENABLED` (env) | `true` | The nightly 03:30 `retention` job. Off means nothing expires automatically. |
| `wawp_webhook_last_seen` | — | Set when WAWP's webhook arrives with the right secret; the readiness page uses it to check WhatsApp STOP is set up. |
| `privacy_notice_draft` | — | The unpublished draft from Admin → Privacy → Privacy notice (JSON). Published versions are in the `PrivacyNotice` table. With no published version the built-in notice (`backend/src/utils/privacyNotice.js`) is shown. The notice's org name, Information Officer, website, emails and medical retention days come from the settings above when it's shown. |
People's News & announcements opt-in is per account (`User.newsEmail`, `User.newsWhatsApp`), not a site setting. Unsubscribe links are signed with `JWT_SECRET` and don't expire — changing `JWT_SECRET` breaks links in emails already sent.
## Backups
| Setting | Default when unset | Notes |
|---|---|---|
| `backup_retain_count` | `14` | How many nightly backups to keep on disk (oldest deleted beyond this count). Editable at Admin → Site Settings → Backups. See `BACKUP_ENABLED` (env var) to turn the nightly job off entirely. |
## Setup state
| Setting | Default when unset | Notes |
|---|---|---|
| `setup_complete` | `false` (treated as `"not true"`) | Controls whether `/setup` redirects to `/login` or runs the first-time wizard. Set to `"true"` automatically when the wizard finishes. |
+795
View File
@@ -0,0 +1,795 @@
# What's new in Cross Events
What each version changes for the church, in plain language. Churches see these notes on Site
settings → Licence before they ask for an update, so they can decide whether they want it.
<!--
How this file is used: the Cross Events Hub reads it from main every 15 minutes, and shows a section
only once its version is tagged (so write it before tagging; fixes to old sections show straight away). Each version is a "## 1.2.3" heading; add "— urgent" (or "security") to the heading for a
security or serious bug fix, which churches can't put off. Under it, lines starting with "- " show as
a list and other lines as paragraphs; **bold**, `code` and links are shown as plain text.
Write for church admins, not developers: no environment variables, endpoints or job names. The
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 2.3.0
- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone
(Google Authenticator, Microsoft Authenticator, 1Password and others) instead of a code by email
or WhatsApp. It's the most secure option and works without signal. Set it up under Profile &
Security.
- **Recovery codes.** When you turn on two-factor you get 10 single-use recovery codes to keep
somewhere safe: if you lose your phone, one of them lets you sign in.
- **Admins can see how each person signs in**: the Users page shows whether each account uses an
app, email or WhatsApp for its codes.
## 2.2.0
- **AI use is now shown in tokens.** Site settings → AI shows how much of this month's AI allowance
your team has used, as input tokens (what's sent to the AI) and output tokens (its answers), with
an estimate of the whole allowance. The tables of who used it and for what show tokens too.
- **Behind the scenes:** Cross Events now lives alongside our other church products, so every
product is updated the same way. Your site works as before, and your data and settings stay as
they are.
## 2.1.1
- **Sending feedback forms and reminders no longer makes you wait.** "Send now" and "Remind" on the
Feedback page now answer straight away and the emails go out in the background, so you can carry
on working. The page updates itself as they go out.
## 2.1.0
- **A Feedback page for supervisors and admins** (Dashboard → Feedback). See every event's feedback
in one place: how many people answered, the average star rating, each question's results and
every response. On a named form you can also see who was asked and who hasn't answered yet.
- **Remind the people who haven't answered.** One button sends everyone who hasn't given feedback
a fresh link by email or WhatsApp, or you can remind one person at a time on a named form.
Nobody is reminded twice within 24 hours. The automatic reminder after 3 days still goes out.
- **Anonymous forms stay anonymous:** the page never shows who gave which answer, or who has and
hasn't answered.
- Opening the answers to a named form is recorded in the access log.
## 2.0.2
- **Licence information sent to Cross Code.** Your site now tells Cross Code which range your event
income falls in over the last 12 months (for example "R150 001–R250 000"), which is what your
licence tier is based on. Donations and sponsorships aren't counted, and the exact amount never
leaves your site. The ranges now go up to over R10 million.
- Fixed: a donation that was applied to a registration was counted twice in the income range sent
to Cross Code.
## 2.0.1
- **Summarise this report on every report.** Reports that list people — payments, attendees,
revenue detailed, master orders, the cashup audit trail, parental consent, feedback and the
medical list — now have the AI summary button too. Only anonymised totals are sent (for example
"40 attendees, 6 with allergies"): no names, contact details, notes, comments or anyone's medical
details. Each of these summaries is recorded in the access log.
## 2.0.0
- **AI helpers.** Where you already work, a button can now do the first draft for you: describe
an event in a sentence and the new-event form is filled in; turn a short note into a friendly
email or WhatsApp message; get a plain-language summary under a report or of an event's
feedback; or improve, shorten or correct a piece of text. You always see the suggestion first —
nothing is saved or sent until you do it. The buttons appear when your licence includes an AI
allowance (ask us about it); Site settings → AI shows what's been used this month. Only what a
helper needs is sent: email addresses and phone numbers in your text stay on your site, reports
are only summarised when they list no people, and feedback goes without names.
- **Stronger password protection.** Passwords are now stored with a stronger, modern method. Nobody
needs to do anything: each person's password is upgraded the next time they sign in.
- **The site banner keeps time.** A banner with start and end times now appears and disappears at
those times on pages that are already open.
- **For anyone with their own integration** (a script or website plug-in that talks to Cross Events
directly): the old version of the connection was retired. Payments, WhatsApp replies and links in
emails you've already sent keep working. Whoever looks after your integration can ask us for the
migration guide.
## 1.52.3
- **A licence check fix.** When a site's licence has run out or isn't connected, the site is
meant to go read-only (tickets still scan and all data can still be viewed and exported). Since
1.51.15 that wasn't being applied; it is again. Sites with an active licence see no change.
## 1.52.2
- **Safer updates.** If files on your server were changed by hand, an update now stops straight
away and says which files, instead of failing part-way. Nothing else changes.
## 1.52.1
- **Better documentation for developers.** If someone builds on your Cross Events site (for example
an integration or a website plug-in), the API reference now explains every part of it in full.
Nothing changes in how the site works.
## 1.52.0 — urgent
- **Paying at the door always gives people their tickets now.** On events with a required
attendee form, people registered at the door or in Manual registration were paid but got no
tickets, so they couldn't be checked in. The form now pops up to fill in with them — or tap
**Fill in later**: the tickets are issued straight away and they're sent a link to fill in the
form afterwards.
- **New: Corrections (for admins).** Pick any event, even one that's over, to see who's missing
tickets, still has a form to fill in or owes money. Issue all missing tickets in one click, give
someone their tickets now and let them pay later, make a ticket free, or check people in after
the event.
- The self-service kiosk asks for exactly the forms still needed, and shows headings on the form
as text instead of an empty box.
- People booked on several sessions now fill in one form each, not one per session.
## 1.51.17 — security update
- **Better protection for people's accounts.** The forgot-password and sign-in pages no longer
let anyone find out whether an email address has an account here.
## 1.51.16
- **The move to the new server connection is complete.** Payment confirmations from Yoco and
PayFast, WhatsApp messages coming in, and the calendar and unsubscribe links in emails now use
the new addresses. Links in emails you've already sent keep working.
## 1.51.15
- **The app now talks to the server only through its new version.** Privacy settings, the admin
pages, site settings, the Hub, webhooks and backups were the last to move. Everything works just
as before.
## 1.51.14
- **More groundwork for 2.0.** Accounts, messaging and broadcasts, WhatsApp set-up, the dashboards,
saved filters and report files now run on the new version of the server's connection to the
app. They work just as before.
## 1.51.13
- **More groundwork for 2.0.** Kids check-in and volunteer rosters now run on the new version of
the server's connection to the app. They work just as before.
## 1.51.12
- **More groundwork for 2.0.** Tickets, ticket transfers, offline scanning, the attendance register,
certificates and group allocations now run on the new version of the server's connection to the
app. They work just as before.
## 1.51.11
- **More groundwork for 2.0.** Payments, cash-ups, the waitlist, sponsorship, consent forms and
feedback now run on the new version of the server's connection to the app. They work just as
before.
## 1.51.10
- **More groundwork for 2.0.** Registrations — at the door, in the dashboards, attendee forms and
bulk actions — now run on the new version of the server's connection to the app. They work
just as before.
## 1.51.9
- **More groundwork for 2.0.** Event series, season passes, bundle deals, coupon codes and campuses
now run on the new version of the server's connection to the app. They work just as before.
## 1.51.8
- **More groundwork for 2.0.** Event pages, ticket types, scanning sections, attachments, planned
costs and picture uploads now run on the new version of the server's connection to the app. They
work just as before.
## 1.51.7
- **More groundwork for 2.0.** Creating and editing events, and every list of events staff choose
from, now run on the new version of the server's connection to the app. They work as before.
- The background job runner was updated. Its list of recent runs (Site settings → Background jobs)
starts afresh with this version.
## 1.51.6
- **Find anything with Ctrl+K.** The search box (Ctrl+K) now lists every report, and pages that
were missing: the dashboard, all reports, ticket options, your groups, and your own events,
payments, privacy, kids, serving, forms and donations.
- Excel downloads use a newer, maintained library. They look the same.
## 1.51.5
- **Updated framework.** The site now runs on the latest version of its web framework. Nothing
changes in how it works.
## 1.51.4 — security
- **Security updates** to the parts the site is built on, including a critical fix in the web
framework. Recommended for everyone.
## 1.51.3
- **More groundwork for 2.0.** The ticket scanner and check-in at the door now run on the new version
of the server's connection to the app, and the server's web framework has been updated. They work
just as before.
## 1.51.2
- **More groundwork for 2.0.** Logging in, signing up and changing your details now run on the
new version of the server's connection to the app. They work just as before.
## 1.51.1
- **More groundwork for 2.0.** Registering, paying online and cancelling now run on the new
version of the server's connection to the app. They work just as before.
## 1.51.0
- **Groundwork for Cross Events 2.0.** Behind the scenes, the server is moving to a newer, safer
way of talking to the app, ready for the AI helpers in 2.0. Nothing changes in how you use
Cross Events.
## 1.50.2
- **Finding an event quickly.** Wherever staff and supervisors choose an event (the scanner, at
the door, payments, messages, forms, attendance and more) there is now a search box. The list
opens on upcoming events, past ones are one click away, and typing finds any event by name,
campus or date. The events list in Reports can be searched too.
- **Webhook guide.** Site settings → Webhooks has a "How webhooks work" guide for whoever connects
another system: what is sent and when, how to check it came from you, and an example message for
every kind of event.
## 1.50.1
- **Finding things in long lists.** The audit log can be searched by person, what was changed or
IP address, filtered by role, and its action list now includes every kind of action. Data
requests can be searched and come a page at a time, and the webhook delivery log can show only
failed deliveries and load older ones.
- **Fix:** the audit log's "To" date now includes that day.
- **Faster Payments page** for churches with a few years of payments behind them.
## 1.50.0
- **Easier for everyone to use.** The public pages, registration, payment, My Events and the
self-service kiosk now work properly with a keyboard and with screen readers: a "Skip to main
content" link, a clear outline showing where you are, popups that can be closed with Escape, and
every form field, button and error message read out correctly. Faint grey text is darker and
links in sentences are underlined, so they're easier to read.
- **Branding check.** If the main colour you pick in Site settings → Branding is too light for
white text to be readable, you'll see a warning and can switch to a darker shade with one click.
## 1.49.2
- **Saved filters.** On Manage registrations, Users, Events and Reports, save the filters you use
under a name and get back to them with one click. Star one and it's ready every time you open the
page. They're yours and follow you to any device.
## 1.49.1
- **Do many at once.** On Manage registrations, tick the people you want (or select everyone
shown after filtering) and send them a message, mark them paid, move them to another ticket, put
them in a room or group, export them to Excel, or cancel them.
- Moving people to another ticket keeps their tickets and QR codes; the price follows the new
ticket, so any difference shows as owing.
- You see what happened to each one, and anything that couldn't be done says why.
## 1.49.0
- **Today, at a glance.** The dashboard now starts with what's on today: each event with how many
people are checked in, children in at kids church, and volunteers here — plus money in today and
this week.
- **Waiting for you.** One list of what needs someone — unpaid registrations, consent forms still
outstanding, waitlists, volunteers asking for cover, events to cash up — each a click away.
- **Ctrl K to find anything.** Press Ctrl K anywhere in the dashboard to jump to a page or setting,
start "New event", or find an event, a payment by amount ("R450") or a person.
## 1.48.2
- No changes for churches in this version — it adds demo data for showing Cross Events to other
churches.
## 1.48.1
- **Privacy notice brought up to date** with volunteer rosters, event series, season passes and
webhooks. If you haven't published your own version, your site shows the new text straight away.
- **Published your own version?** Admin → Privacy → Privacy notice now shows what changed in the
built-in text, section by section, so you can take the new wording with one click and publish.
- **Everyone agrees to the notice once.** People whose account was made for them agree when they
activate it, and anyone who never has is asked once after they next log in.
## 1.48.0
- **Webhooks.** Connect Cross Events to other systems — ChurchSuite, Planning Center, a Google
Sheet through Zapier or Make. Choose what to send (new registrations, payments, check-ins, new
accounts, published events) in Site settings → Webhooks, and it goes out as it happens.
- Every message is signed so the other system can trust it, failures are tried again
automatically, and a delivery log shows what was sent.
- Each webhook is added to your operator register for POPIA. Children's details are never sent.
## 1.47.4
- **Asked for an update, and a newer one came out?** The Licence page now shows which version you
asked for, tells you when a newer one is out, and lets you ask for that one instead with one
button.
## 1.47.3
- **Season passes.** Sell a ticket for several events in a series at one price — say all of next
year's breakfasts. People buy it on the series page, pay once, and get a ticket for each event.
- The money is shared out over the events in line with their normal ticket prices, so each event's
cashup shows its part.
- Set passes up on the Event series page. A pass stops selling when its first event starts.
## 1.47.2
- **Compare a series year on year.** A new report puts the events in a series side by side —
registrations, tickets, income and how many came — with how much each went up or down from the
one before. Open it from Reports, or with **Compare** on the Event series page.
## 1.47.1
- **Event series.** Group events that come back — every year's camp, the monthly breakfast — on
one page that shows what's coming up and what's been. Each event in a series links to the next one.
- **Follow a series.** People can follow a series and get an email when the next event in it is
out. It counts as news, so only people who chose to get news and announcements receive it.
- A copied event stays in its series, and a series can have events at different campuses.
## 1.47.0
- **Copy an event.** Running the same camp, course or breakfast again? Press **Copy** on the event
and the editor opens with everything filled in: tickets and prices, early birds, sessions, the
form, feedback questions, certificates and groups.
- **Pick the new start date** and every other date moves with it — sessions, deadlines and
early-bird dates included. Check each step, change what's different this time, and save.
- Registrations, coupons, attachments, kids check-in and volunteer roles aren't copied.
## 1.46.2
- **See what's new before you update.** When a new version is out, the Licence page lists what it
brings, so you can decide whether you want it.
- **Changed your mind?** Withdraw an update request, and your provider is told not to update the site.
- **Not now:** hide the "update available" reminder until the next version comes out. Updates that
fix a security problem or a serious bug are marked in red and can't be put off.
- **Notices from your provider**, such as planned maintenance, now show as a banner for site admins
and supervisors.
## 1.46.1
- Behind-the-scenes maintenance. Nothing changes for you.
## 1.46.0
- **Volunteer rosters:** set up serving roles (Welcome, Parking, Kids, Sound…) per event or session.
Anyone with an account can sign up under My account → Serving, or supervisors can assign people.
- Reminders by WhatsApp or email the day before a shift.
- **"Can't make it" swaps:** a volunteer asks for cover, and the first to accept takes the place.
- Volunteers check in by scanning the event's QR code; kids-room volunteers count as leaders on duty.
- Roster sheet with phone numbers and check-in times, and hours served per person.
- Fixed: the free kids check-in ticket was offered on the public event page.
## 1.45.1
- The built-in privacy notice and terms of use are brought up to date for kids check-in, sessions,
certificates and campuses. If you published your own privacy notice, review it under Admin →
Privacy.
## 1.45.0
- **Kids check-in:** a secure check-in and pickup for children's ministry, run from a staff desk, with
no label printers needed.
- Parents keep their children's details (allergies, medical and custody notes) and authorised adults
under My account → Kids.
- Each check-in gives the family a pickup code by WhatsApp or email; children can only be collected
with the code.
- Rooms with age ranges, capacity and ratios, live room screens, and an offline desk mode.
## 1.44.0
- **Staff for some campuses:** supervisors and staff can be limited to certain campuses (Admin →
Users). They then see only those campuses' events, plus events for all campuses, everywhere in the
dashboard, reports and the scanner.
- The scanner says which campus a ticket is for.
## 1.43.0
- **Campuses** for churches with more than one campus (Site settings → Campuses, off by default).
- Events belong to one campus or to all campuses; the public events page has a campus filter and
each campus gets its own page.
- Reports, dashboards, broadcasts and the daily summary can be filtered by campus.
- People can choose their home campus on their profile.
## 1.42.1
- Behind-the-scenes improvements to licence checking. Nothing changes for you.
## 1.42.0
- **Request update:** when a new version is out, press Request update on Site settings → Licence and
your provider updates the site for you.
## 1.41.3
- The platform is now called **Cross Events**. Nothing else changes, and everyone stays signed in.
## 1.41.2
- Fixed: the Background jobs page showed last-run times two hours ahead.
## 1.41.1
- A site without a licence is now read-only until a licence key is connected.
- Fixed: a site whose licence was released kept showing it as active.
## 1.41.0
- **Licences:** the site connects to Cross Events with a licence key (Site settings → Licence) and
checks in every 15 minutes with its version and health — never anyone's personal information.
- After a licence's end date there's a grace period with a reminder for site admins.
- Site admins see when a newer version is available.
## 1.40.0
- **POPIA toolkit, part 3:** a privacy readiness checklist with a score, and links to fix each item.
- **Retention settings:** choose how long personal information is kept. Inactive accounts are warned
and then anonymised after 5 years (on by default).
- **Breach register:** record security incidents, with draft messages for the people affected and
for the Information Regulator.
## 1.39.0
- **POPIA toolkit, part 2:** Admin → Privacy (POPIA).
- Edit and publish your own privacy notice, with numbered versions, and ask everyone to accept a new
version when it changes significantly.
- A register of the outside services that handle personal information, a consent log, and an access
log of who downloaded personal information.
## 1.38.0
- **POPIA toolkit, part 1:** a Privacy page for everyone (My account → Privacy): choose whether to get
news by email or WhatsApp, download your data, ask for a correction or delete your account.
- Bulk messages are either **event updates** (to everyone booked) or **news** (only to people who
opted in, with an unsubscribe link). Replying STOP on WhatsApp stops news.
- Admins handle correction and deletion requests under Admin → Data requests.
## 1.37.4
- Behind-the-scenes improvements to updating the site. Nothing changes for you.
## 1.37.3
- Behind-the-scenes fix. Nothing changes for you.
## 1.37.2
- **Payment status checks:** online payments whose confirmation never arrived from PayFast are found
and recorded automatically, with a "Check status" button under Payments → Reconcile.
- A "Test connection" button for the PayFast settings.
## 1.37.1
- "Pay online" is no longer offered when online payments are off or the amount is under R15; people
are told to pay at the event instead.
## 1.37.0
- **PayFast:** a second online payment provider (card, instant EFT and more), set up in Site
settings → Payments.
- When more than one provider is on, people choose how to pay.
## 1.36.0
- **Site settings → Payments:** turn online payment providers on or off and choose their order.
- Online payments must be at least R15; smaller balances are paid at the door.
## 1.35.1
- **Waitlist per session** on events where people pick sessions.
- "All sessions" tickets let people choose which sessions they'll come to.
- At the door, walk-ins can be booked straight into today's session.
- Several fixes for per-session tickets and stock limits.
## 1.35.0
- **Pick sessions:** a multi-session event can let people choose which sessions to come to — day
passes for a conference, or a weekly drop-in class — with a price per session.
- Each session can have its own capacity, and tickets only scan on their own session.
## 1.34.0
- **Background jobs page** (Site settings → Background jobs): see every scheduled task, when it last
ran, and run it now.
- Scheduled tasks (reminders, summaries, backups) are more reliable and run on South African time.
- Fixed: at the door, multi-day tickets showed as used up from the second session.
## 1.33.0
- **Multi-day events:** an event can run over several sessions (e.g. every Wednesday for 5 weeks);
people register and pay once.
- Check-in per session, optional reminders before each session, and late joining at a lower price.
- **Attendance register** with ticks per session and Excel/PDF export.
- **Completion certificates** with four designs, issued automatically, each with a QR code anyone can
check.
## 1.32.0
- Event cards show an "Early bird" ribbon while early-bird pricing is running.
## 1.31.1
- A field for Google Search Console verification (Site settings → Organisation).
## 1.31.0
- The registration funnel recognises visits from Facebook, Instagram, Google and other sites without
tagged links, and shows shares and QR code scans separately.
- Events can appear in Google's event listings with their date, venue and tickets.
## 1.30.1
- All tickets — emailed, WhatsApped and printed — share one clean design, with bigger QR codes.
## 1.30.0
- People can add an optional **donation** when they register, paid together with their tickets.
- Fixed: event pages with a waitlist could crash.
## 1.29.1
- The Coupon codes page is easier to use, including on phones, and hides codes that are off, expired
or used up.
## 1.29.0
- Bundle deals come in four types: an exact set, pick any mix, buy X get Y free, and group discounts.
## 1.28.3
- Fixed: the bundle deals form didn't fit on the screen.
## 1.28.2
- The Bundle deals page has a new layout that works on phones.
## 1.28.1
- Bundle deals work at the door, in manual registration and on the self-service kiosk too.
## 1.28.0
- **Bundle deals:** sell a set of tickets together for one price, e.g. 2 adults + 3 kids for R220.
They apply automatically, with no code, and the saving shows on invoices and receipts.
## 1.27.1
- Behind-the-scenes improvements to the demo data. Nothing changes for you.
## 1.27.0
- **Cashups** record where each payment method's money ended up: in the bank, cash on hand, or still
pending. Card fees and bank charges can be written off with a reason.
- Pending money can be marked received later without reopening the event.
- Every dashboard page has the same "Back to dashboard" link.
## 1.26.1
- Behind-the-scenes improvements to the demo data. Nothing changes for you.
## 1.26.0
- Behind-the-scenes upgrades and security updates.
- Fixed: the refund reason didn't show at the door.
## 1.25.1
- On phones, the cookie notice and the help button no longer hide each other or the menu.
## 1.25.0
- **Yoco settings** in Site settings: enter and check the secret key, and set up payment
notifications with one click.
## 1.24.0
- **Ticket transfers** now need the new holder to accept, by a link sent to them.
- Updated terms of use and privacy policy, with a full cookie policy and a "Cookie settings" link.
- Fixed: activating an account didn't sign you in.
## 1.23.0
- **View as user:** admins can see the site exactly as someone else does, to help with problems.
It's read-only, limited to 30 minutes and recorded in the audit log.
## 1.22.0
- **Registration funnel report:** see where people drop off between viewing an event and paying, by
traffic source and device. Only visitors who allow it are counted.
## 1.21.0
- **Post-event feedback:** send a short survey after an event, with one reminder, and see the results
in a Feedback summary report.
- New form question types: star ratings and multiple choice.
## 1.20.0
- **Sponsor a spot:** people can pay for a place for someone who can't afford it, with an optional
goal and progress bar.
## 1.19.0
- **Rooms & groups** for camps: put attendees into rooms, cabins, small groups or buses by drag and
drop or automatically, with printable lists.
- Events can ask each person's gender.
## 1.18.0
- **Ticket transfer:** hand a ticket to someone else before the event; the old QR code stops working.
## 1.17.0
- **Offline ticket scanning:** download an event's tickets to a device and keep scanning without a
connection; scans sync when it's back online.
## 1.16.0
- **Waitlists** for sold-out tickets: when a place frees up, the next person is offered it
automatically.
## 1.15.0
- **Parental consent** for youth events: parents give consent online, with optional medical and
emergency details, before their child can be checked in.
## 1.14.0
- **Named attendees:** when booking for several people, each person can be named and get their own
ticket.
## 1.13.0
- **Coupon codes:** percentage, fixed-amount or free codes, with limits on events, dates and uses.
- Staff prices for tickets.
- A Discounts report.
## 1.12.0
- Two-factor login is now required for admins and supervisors.
## 1.11.0
- **Two-factor login** for everyone who wants it: a code by email or WhatsApp after the password, and
"Trust this device for 30 days".
## 1.10.6
- Security updates.
## 1.10.5
- Events that have started but not finished stay listed on the home and events pages.
## 1.10.4
- Fixed: "Add to calendar" didn't work.
## 1.10.3
- More admin actions are written to the audit log.
## 1.10.2
- Behind-the-scenes fix to error monitoring. Nothing changes for you.
## 1.10.1
- Security fixes for file uploads, and security updates.
## 1.10.0
- **Add to calendar** on event pages and in confirmation emails.
- Better link previews and search engine listings for events.
- **Nightly database backups**, which you can download from Site settings → Backups.
- **Audit log** of refunds, donations, manual registrations, cancellations, event changes and
settings changes.
## 1.9.5
- The site copes better with automated traffic probing for pages that don't exist.
## 1.9.4
- Behind-the-scenes server setting. Nothing changes for you.
## 1.9.3
- People registered at the door or by staff get their account activation link straight away.
- Fixed: the self-service kiosk's "Choose a password" didn't work.
## 1.9.2
- Contact-only events no longer get a daily summary email.
## 1.9.1
- Fixed: the browser tab and home page showed the default name instead of your church's name.
## 1.9.0
- Events have a **location**, with a "Directions" link and a map on the event and contact pages.
## 1.8.0
- **Contact-only events** (e.g. baptism) show a "Contact us" button instead of registration.
- **Invoices and receipts** as branded PDFs with registration and payment emails, with a "pay now"
link and QR code.
- Fixed: buying more tickets after early bird ended re-priced the tickets already bought.
## 1.7.0
- **Brand colours:** primary, secondary and accent colours across the whole site and emails, a
favicon, and a live preview. Colours can be suggested from your logo.
## 1.6.0
- Supervisors can unassign a donation that was applied to a registration.
- Faster payments and dashboards.
## 1.5.4
- The home page shows "My Dashboard" to people who are signed in.
## 1.5.3
- Fixed: help popups could be taller than a phone screen.
## 1.5.2
- Dashboard tiles and charts fit better on phones.
## 1.5.1
- Fixed: scheduled WhatsApp messages were sent as emails.
## 1.5.0
- **Site redesign:** a new look across the whole site, new dashboards with trends and top events, and
a "Need help?" button with a guide on every page.
- A separate Contact page, and recent sign-ins on Profile & Security.
## 1.4.2
- Fixes to how refunds and donations are counted in reports and cashups.
## 1.4.1
- Reports fit better on phones.
## 1.4.0
- **Reports redesigned:** filters that apply to every report, charts, and styled PDF and Excel
exports, by email or WhatsApp too.
- Cashups show who recorded each payment, with per-person cash counts.
- A payment link placeholder for messages to attendees.
## 1.3.2
- The self-service kiosk is safer with returning visitors' details, and asks before changing them.
## 1.3.1
- The self-service kiosk can find a returning visitor's account.
## 1.3.0
- **Check-in at the door** by number of people, without scanning each QR code, and a confirmation
message to the ticket holder.
## 1.2.0
- "Make payment" goes straight to paying the full balance.
- Staff can record a payment straight after a manual registration.
## 1.1.0
- A payment history page in My account.
- Registration status shows as a coloured badge.
## 1.0.1
- Closed and past events are tidied away in My Events.
## 1.0.0
- The first release.
+116
View File
@@ -0,0 +1,116 @@
# ─── Database ────────────────────────────────────────────────────────────────
DATABASE_URL="postgresql://username:password@localhost:5432/hope_events"
# ─── Auth ─────────────────────────────────────────────────────────────────────
JWT_SECRET=your_jwt_secret_here_minimum_32_characters
# Two-factor authentication is required for admins and supervisors whenever
# email (SMTP) or WhatsApp can deliver a code. Set to false only as an emergency
# switch, e.g. if the mail server is down and admins are locked out.
# TWO_FACTOR_REQUIRED_ROLES=true
# ─── Server ───────────────────────────────────────────────────────────────────
PORT=5000
NODE_ENV=development
# Time zone for background job schedules (e.g. the 07:00 daily summary), session dates
# and printed times. An IANA name, e.g. Africa/Johannesburg or Europe/London.
APP_TIMEZONE=Africa/Johannesburg
# Set this if the app runs behind a reverse proxy (e.g. nginx on a separate
# server) so rate limiting reads the real client IP instead of the proxy's.
# Accepts a hop count ("1"), "true"/"false", or comma-separated IP(s)/CIDR(s)
# of your trusted proxy (e.g. "10.0.0.5" or "10.0.0.0/8"). Leave unset if the
# app is not behind a proxy.
# TRUST_PROXY=1
# ─── CORS ─────────────────────────────────────────────────────────────────────
# Comma-separated list of allowed frontend origins
FRONTEND_URL=http://localhost:3000
# ─── Email (SMTP) — optional fallbacks ───────────────────────────────────────
# Preferred: configure SMTP via Admin → Site Settings (stored AES-256 encrypted).
# These env vars are used as fallbacks if no SMTP settings are saved in the DB.
# EMAIL_HOST=smtp.example.com
# EMAIL_PORT=587
# EMAIL_USER=your_email@example.com
# EMAIL_PASS=your_email_password
# EMAIL_FROM=no-reply@example.com
# ─── Payments (Yoco) — optional fallbacks ─────────────────────────────────────
# Preferred: set the secret key and generate the webhook in Admin → Site Settings →
# Yoco (stored AES-256 encrypted). These are only used if the database has no value.
# YOCO_SECRET_KEY=sk_test_...
# YOCO_WEBHOOK_SECRET=whsec_...
# ─── Payments (PayFast) — optional fallbacks ──────────────────────────────────
# Preferred: Admin → Site Settings → Payments → PayFast. Only used if the database has no value.
# PAYFAST_MERCHANT_ID=
# PAYFAST_MERCHANT_KEY=
# PAYFAST_PASSPHRASE=
# PAYFAST_MODE=sandbox
# PayFast notifications (ITNs) must come from a PayFast address. Behind a reverse proxy, set
# TRUST_PROXY so the real address is seen. Only for testing through a tunnel:
# PAYFAST_SKIP_IP_CHECK=true
# ─── Public URLs ──────────────────────────────────────────────────────────────
# Used to build links in emails (password reset, activation, etc.)
APP_BASE_URL=https://your-frontend-domain.com
# Used to serve ticket PDFs to WhatsApp (must be publicly reachable)
BACKEND_URL=https://your-backend-domain.com
# ─── WhatsApp (WAWP) — optional, preferred stored via Admin → Site Settings ───
# These are env-var fallbacks. Use the admin panel to manage them at runtime.
WAWP_ACCESS_TOKEN=your_wawp_access_token
WAWP_INSTANCE_ID=your_wawp_instance_id
# ─── Background workers ───────────────────────────────────────────────────────
DAILY_SUMMARY_ENABLED=true
SCHEDULED_EMAILS_ENABLED=true
SCHEDULED_EMAILS_INTERVAL_MS=30000
# Daily 09:00 parental-consent job: reminders, and deleting medical details after events
CONSENT_JOBS_ENABLED=true
# Waitlist: expire unclaimed offers and offer freed places (every 10 minutes by default)
WAITLIST_JOB_ENABLED=true
# WAITLIST_JOB_INTERVAL_MS=600000
# Payments: every 15 minutes, look up PayFast checkouts whose notification never arrived
PAYMENT_STATUS_JOB_ENABLED=true
# Volunteer rosters: reminders the day before a shift (every 15 minutes)
VOLUNTEER_JOBS_ENABLED=true
SERIES_JOBS_ENABLED=true
WEBHOOKS_JOBS_ENABLED=true
WEBHOOKS_ENABLED=true
# Local testing only: lets webhook endpoints be http:// or on a private network
WEBHOOKS_ALLOW_PRIVATE=false
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
PRIVACY_JOBS_ENABLED=true
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
# accounts are anonymised after 5 years by default (with a warning 30 days before).
RETENTION_JOBS_ENABLED=true
# ─── Cross Events Hub (licence and health) ─────────────────────────────────────
# Where the Hub runs. The site checks in every 15 minutes once connected (Site settings → Licence).
# HUB_URL=https://events-hub.crosscode.co.za
# For a local or test Hub only: its public key (the release has the production key built in).
# HUB_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n…\n-----END PUBLIC KEY-----"
HUB_HEARTBEAT_ENABLED=true
# Nightly database backup at 02:00 (requires the `pg_dump` binary on this host).
# Retention count is set via Admin → Site Settings → Backups (default 14).
BACKUP_ENABLED=true
# ─── Error monitoring (Sentry) — optional ─────────────────────────────────────
# Leave unset to disable entirely (a no-op, not an error). Set NEXT_PUBLIC_SENTRY_DSN
# in frontend/.env too if you want frontend errors captured.
# SENTRY_DSN=https://xxxxx@oxxxxxx.ingest.sentry.io/xxxxx
# ─── Note ─────────────────────────────────────────────────────────────────────
# The following are managed via Admin → Site Settings and stored in the database:
# - Organisation name, tagline, contact details, branding colour, logo
# - Registration notification emails
# - SMTP settings (username and password stored AES-256-GCM encrypted, key
# derived from JWT_SECRET — do not change JWT_SECRET after saving SMTP creds)
# - Yoco secret key and webhook secret (encrypted the same way)
# - Legal page content (operator name, Information Officer, website URL, etc.)
# The first-time setup wizard handles initial configuration on fresh deployments.
# You no longer need ORG_NAME, ORG_TAGLINE, EMAIL_HEADER_COLOR, REGISTRATIONS_EMAIL,
# or SMTP vars in this file (they still work as fallbacks if the DB entry is absent).
+16
View File
@@ -0,0 +1,16 @@
# Cross Events — API Documentation
Since 2.0 the API is `/api/v2` only, described by **OpenAPI 3.1** generated from the route
declarations (`backend/src/v2/`), so it is never out of date:
- **Reference:** `/docs/v2` on the running backend (admin token).
- **Document:** `GET /api/v2/openapi.json` (admin); the frontend's copy is
`frontend/src/lib/api-v2/openapi.json` (regenerate with `npm run api:types` in the repo root).
Every answer is `{ "data": … }`; lists add `meta: { page, limit, total, pages }` (`?page=&limit=`);
errors are `{ "error": { "code", "message", "reason"?, "fields"? } }`. Send the sign-in token as
`Authorization: Bearer <token>` (`POST /api/v2/auth/login`).
Version 1 (`/api/…`) was removed in 2.0 and answers `410 Gone`, except the incoming webhooks and the
links in messages already sent. What changed and the full v1 → v2 table are in
[MIGRATING-TO-2.md](../MIGRATING-TO-2.md). The old v1 reference is in git history (tag `v1.52.3`).
+204
View File
@@ -0,0 +1,204 @@
# Demo data
The demo seeds replace everything in the database with a realistic set of demo data, for
showing the platform to other churches. Pick the one that looks like the church you're
showing it to:
| Command (repo root) | For | What's in it |
|---|---|---|
| `npm run demo:small` | A small church, one congregation | 3 upcoming events (a sold-out breakfast with a waitlist, a family day, free carols), 4 past events with check-ins and cashups. No campuses, kids check-in, rosters, courses or series. |
| `npm run demo:events` | Events and conferences (the original demo) | 6 upcoming events (coupons, variants, early birds, a youth camp with consent and cabins, bundles, donations) and 10 past events with every kind of cashup and funnel analytics. |
| `npm run demo:ministry` | One campus with weekly ministry | The Alpha Course running now (sessions, attendance, late joining, certificates), a finished Marriage Course with certificates, a 3-day conference sold by day, **Kids Church** with families, children, rooms and check-ins, **volunteer rosters**, a **Men's Breakfast series** with followers and a **season pass**, plus a family day, women's conference and carols. |
| `npm run demo:multicampus` | A church with several campuses | **Campuses** Central, North and South (switched on), events per campus and church-wide, home campuses, staff limited to a campus (Anri Botha → North, Daniel Pillay → South), the breakfast series moving between campuses, kids church and rosters at two campuses, and all the events-demo events spread over the campuses. |
`npm run demo:list` prints the same list. Kids church always has a session **today** with
children checked in right now, so the kids desk and room screens have something live to
show on any day.
> **This deletes real data.** Run it only against a database you're happy to wipe, such
> as a dedicated demo deployment. It is not something to run on a live church site.
---
## Running it
```bash
npm run demo:ministry # (repo root) shows the database it will wipe and asks you to type "demo"
npm run demo:ministry -- --yes # no prompt (for scripts)
# or in backend/:
npm run set-demo -- --profile=ministry --yes # without --profile it seeds "events"
```
The campuses setting is switched on for `multicampus` and off for the others (site settings
are otherwise kept). **Restart the backend afterwards** so it picks the setting up.
The script uses `DATABASE_URL` from `backend/.env`. To point it at another database
for one run, set it in the environment first. A value already in the environment wins
over `.env`:
```bash
DATABASE_URL="postgresql://user:pass@host:5432/hope_demo" npm run set-demo
```
It takes about five seconds and is safe to re-run as often as you like. Each run wipes the
previous demo and creates it again.
### Before you run it
- The admin account must already exist. By default that's `joshua@crosscode.co.za`.
To keep a different account, set `DEMO_ADMIN_EMAIL`:
```bash
DEMO_ADMIN_EMAIL="admin@example.org" npm run set-demo
```
If the account isn't found, the script stops before changing anything.
- Migrations must be up to date (`npm run prisma:deploy`).
---
## What it keeps and what it clears
| Kept | Cleared |
|---|---|
| Site settings (`AppSetting`): org name, branding, SMTP, Yoco, WhatsApp, legal pages | Every event, with its options, variants, early-bird tiers, sections, forms, costs and cash-ups |
| The admin account, including its login history, trusted devices and 2FA | Every other user |
| Migration history | Registrations, payments, tickets, scans, coupons, waitlists, consents, cabins, feedback, analytics, audit log |
| Uploaded files on disk (`public/uploads`) | Queued scheduled emails/WhatsApps (`data/scheduled-emails.json`) |
The wipe and the new data are written in one database transaction. If that fails,
nothing changes. The past events' cashups run straight afterwards, through the same
code as the cashup screen. If one of those fails, re-run the script.
---
## What it creates
### Upcoming events
All dates are worked out from the day you run it, so these events are always upcoming.
Registrations are spread over the past month, as if sign-ups have been coming in.
The data is generated from a fixed seed, so every run looks the same.
| When (from today) | Event | Shows off |
|---|---|---|
| ~1½ weeks, Sat 07:30 | **Men's Breakfast: Built to Last** | **Sold out** (60 places), 5 people on the **waitlist**, card / cash / EFT payments recorded by staff, 2 cancelled registrations |
| ~2½ weeks, Sat 10:00 | **Family Fun Day** | Adult and child tickets with a **bundle deal** (Family deal: 2 adults + 3 kids for R220 instead of R280, used by about a third of registrations) and a **pick-any** deal (Lunch for four: any 4 lunch packs for R220), a non-ticket **add-on** (lunch pack), a fixed-amount **coupon** (`FUNDAY20`), entry and food-stall check-in sections |
| ~5 weeks, Fri–Sat | **Rooted Women's Conference** | Two **early-bird tiers** (one already expired, one still open) plus a Saturday-only ticket, T-shirt **variants** (S–XXL), a **required sign-up form** (dietary needs, workshop choice, prayer requests), a 20% **group coupon** (`ROOTED20`) used by 4 registrations |
| ~7 weeks, Mon–Thu | **Ignite Summer Camp** | **Named attendees** (campers aged 12–17), signed **parental consent**, gender collected, **deposits and part-payments**, campers placed in boys' and girls' **cabins** with staff leaders, **sponsor-a-spot** donations towards a 10-spot goal |
| ~8 weeks, Sun 19:00 | **Carols by Candlelight** | A **free event** with group tickets (1–6 people), plus general **donations** |
| ~14 weeks, Fri–Sun | **Marriage Enrichment Weekend** | Room-type **variants with limited stock**, early-bird prices per room type, a per-person spa add-on, R1 000 EFT deposits |
Each event also gets:
- A cover photo (from Unsplash, which `next.config` already allows) and a contact person.
- **Costs**, both once-off and per item, so the profit view and cash-up have figures.
- About 30 days of **funnel analytics** (views → started → submitted → paid) by source
(WhatsApp, Facebook, Instagram, email, direct) and device.
Paid registrations have tickets with QR codes, the same way the app issues them once
payment is complete. Part-paid and pending ones don't have tickets yet.
### Past events
Ten completed events spread over the past year, for showing cashups and the historical
reports. Each one has:
- Online sales in the five weeks before the event, with a few unpaid no-shows.
- **Door sales** on the day, recorded by the staff team (cash and card machine).
- **Check-ins**: about 90% of tickets scanned, with the odd group arriving short.
- **Staff cash counts** with note and coin denominations.
Some events also have refunds, donations and post-event feedback.
The cashups cover every path through the cashup screen:
| When | Event | Cashup to demo |
|---|---|---|
| ~11 months ago | **Church Family Picnic** | **Quick closed** (no settlement) |
| 24 Dec | **Christmas Eve Candlelight Service** | Free event with card and cash **donations**. Card settled net of **Yoco fees**, collection banked |
| Easter Sunday | **Easter Sunrise Service & Breakfast** | Cash banked less a **cash deposit fee** (bank charge), card fees, a **refund** |
| Mother's Day | **Mother's Day Brunch** | **Closed with R50 cash short → reopened → recounted → closed again.** The history shows all three steps |
| ~3½ months ago | **Youth Winter Camp** | Deposits and balances. **EFT pending** (POPs) at close, later **marked received** without reopening |
| ~2½ months ago | **Men's Golf Day** | Card-heavy, card fees written off, a refund |
| ~2 months ago | **Kids Holiday Club** | Cash-heavy door sales. **R20 cash shortfall written off**, **R500 kept on hand** as float |
| ~6 weeks ago | **Women's High Tea** | Closed with **R30 unaccounted**, shown in red |
| ~4 weeks ago | **Missions Fundraiser Dinner** | **R2 600 EFT still pending** (POP received, not cleared). Shows "Mark received" / "Write off" |
| ~10 days ago | **Worship Night** | **Still open, with the cash already counted.** Use it to do a cashup live in the demo |
Easter, the Youth Camp, the Holiday Club and the High Tea have **feedback forms** with
ratings and comments. Funnel stats older than 90 days are stored as daily totals, the
way the app rolls them up overnight, so the funnel report covers the whole year.
### Totals
A typical run gives roughly:
| | |
|---|---|
| Users | 130 (plus the admin) |
| Registrations | ~700 (paid, part-paid, pending, cancelled and refunded) |
| Payments | ~640, including donations, sponsorships and refunds |
| Tickets | ~780, with ~490 check-ins |
| Named campers | ~45 |
| Feedback responses | ~80 |
| Funnel rows | ~4 400 |
---
## Logging in
Every demo account uses the password **`Demo@1234`**.
| Role | Email | Good for showing |
|---|---|---|
| Supervisor | `lerato.khumalo@example.com` | Event setup, reports, coupons, viewing cashups |
| Staff | `sipho.dlamini@example.com` | At-the-door payments and check-in scanning |
| Staff | `anri.botha@example.com` | |
| Staff | `daniel.pillay@example.com` | |
Closing, reopening and settling pending money in a cashup are admin-only, so do the
live Worship Night cashup as your own admin account.
The other 126 people are ordinary members (role `user`), with emails like
`thandi.mokoena@example.com`. Log in as one of them to show the member view: their
registrations, tickets and payments. Any registrant's email from an event's attendee
list works.
Your own admin account keeps its existing password.
---
## Safety
- **Nothing is sent.** The script writes straight to the database and never calls the
email, WhatsApp or Yoco code.
- **Nothing can reach a real person later.** Demo people use `@example.com` addresses
(a reserved domain that can't receive mail) and have **no phone numbers**, so
reminders or broadcasts sent during a demo go nowhere. All parental consents are
already signed, so no consent reminders go out.
- Card payments have made-up Yoco ids (`demo_…`). They don't exist in Yoco, so leave
the demo site's Yoco settings in test mode or empty.
---
## Customising
Everything lives in [`scripts/set-demo.js`](scripts/set-demo.js). There is one
`build…()` function per event (`buildMensBreakfast`, `buildYouthCamp`, …), and
`main()` decides which ones run. To change an event's name, prices, ticket types or
number of registrations, edit its function. To add an event, write a new `build…()`
and add it to the list in `main()`. `addBundle(event, { name, price }, [[option, quantity], …])`
adds a bundle deal. Registrations added after it get the deal automatically, worked out
the same way as the app does it.
The past events are in `buildPastEvents()`, one spec each: dates, ticket types, costs,
how many people bought online and at the door, and a `cashup` that says how it was
closed. Supported closes:
- `'quick'`
- `'full'`, with `lines` saying where the money ended up
- `'reclose'`
- `'none'`, which leaves the event open
A full close can add `later` to settle pending money after closing. The helpers
`cardLine`, `eftLine` and `cashLine` build the usual settlements: card net of Yoco fees,
EFT with an optional pending POP, and cash banked with an optional float, deposit fee or
shortfall.
+555
View File
@@ -0,0 +1,555 @@
# Cross Events — Backend API
Node.js + Express REST API for the Cross Events platform used by Hope Family Church (`events.hopehenley.co.za`).
---
## Table of Contents
1. [Overview](#overview)
2. [Tech Stack](#tech-stack)
3. [Prerequisites](#prerequisites)
4. [Installation](#installation)
5. [Environment Variables](#environment-variables)
6. [Database](#database)
7. [Running the Server](#running-the-server)
8. [Authentication & Roles](#authentication--roles)
9. [API Reference](#api-reference)
10. [Background Workers](#background-workers)
11. [Notification System](#notification-system)
12. [WhatsApp Integration](#whatsapp-integration)
13. [File Uploads](#file-uploads)
14. [Payments (Yoco)](#payments-yoco)
15. [Deployment](#deployment)
---
## Overview
Full-stack event management backend handling:
- User registration, authentication (JWT), and role-based access control
- Event creation, management, and public listings
- Attendee registration with optional payment tiers and early-bird pricing
- Yoco checkout integration with webhook reconciliation
- Ticket generation (PDF + QR code) and email/WhatsApp delivery
- Scheduled bulk messaging (email + WhatsApp) for attendees and broadcast lists
- Admin WhatsApp instance management via WAWP
---
## Tech Stack
| Layer | Technology |
|-------|-----------|
| Runtime | Node.js 18+ |
| Framework | Express 4 |
| Database | PostgreSQL (via Prisma ORM 5) |
| Auth | JWT (`jsonwebtoken`), `bcryptjs` |
| Email | Nodemailer (any SMTP — configured via Admin → Site Settings, AES-256 encrypted in DB) |
| WhatsApp | WAWP REST API (`api.wawp.net/v2`) |
| PDF/QR | PDFKit, QRCode |
| File Uploads | Multer |
| Payments | Yoco |
---
## Prerequisites
- Node.js 18+
- PostgreSQL 14+ (hosted at `database.crosscode.co.za` for production)
- npm
---
## Installation
```bash
cd backend
npm install # installs deps and runs `prisma generate`
```
---
## Environment Variables
Create `backend/.env` from `.env.example`. The only variables you must set are:
| Variable | Required | Description |
|----------|----------|-------------|
| `DATABASE_URL` | Yes | PostgreSQL connection string |
| `JWT_SECRET` | Yes | Secret key for JWTs (32+ random characters). Also used to derive the AES-256 encryption key for sensitive settings (SMTP credentials) stored in the DB — must be set before saving SMTP settings. |
| `FRONTEND_URL` | Yes | Comma-separated allowed CORS origins |
| `YOCO_SECRET_KEY` | — | Fallback Yoco secret API key (preferred: set via Admin → Site Settings → Yoco) |
| `YOCO_WEBHOOK_SECRET` | — | Fallback Yoco webhook secret (preferred: generate or enter it via Admin → Site Settings → Yoco) |
| `APP_BASE_URL` | — | Public frontend URL — used in email links (fallback if not set via admin panel) |
| `BACKEND_URL` | — | Public backend URL — used to serve ticket PDFs over WhatsApp |
| `PORT` | — | Port to listen on (default `3000`) |
| `TRUST_PROXY` | — | Set when running behind a reverse proxy (e.g. nginx on a separate server), so `req.ip`/`X-Forwarded-For` are read correctly by rate limiting. Accepts a hop count (`1`), `true`/`false`, or comma-separated trusted proxy IP(s)/CIDR(s). |
| `NODE_ENV` | — | `production` or `development` |
| `WAWP_ACCESS_TOKEN` | — | WAWP fallback token (preferred: set via Admin → Site Settings) |
| `WAWP_INSTANCE_ID` | — | WAWP fallback instance ID (preferred: set via Admin → Site Settings) |
| `DAILY_SUMMARY_ENABLED` | — | `false` to disable daily summaries (default `true`) |
| `SCHEDULED_EMAILS_ENABLED` | — | `false` to disable scheduled-send worker (default `true`) |
| `SCHEDULED_EMAILS_INTERVAL_MS` | — | Polling interval in ms (default `30000`) |
| `SMTP_HOST` / `EMAIL_HOST` | — | Fallback SMTP host (preferred: set via Admin → Site Settings) |
| `SMTP_PORT` / `EMAIL_PORT` | — | Fallback SMTP port |
| `SMTP_USER` / `EMAIL_USER` | — | Fallback SMTP username |
| `SMTP_PASS` / `EMAIL_PASS` | — | Fallback SMTP password |
| `MAIL_FROM` / `EMAIL_FROM` | — | Fallback from address |
> **Organisation name, branding colour, logo, registration notification email, SMTP settings, and legal page content** are now managed through the admin panel at **Admin → Site Settings** and stored in the database. You no longer need `ORG_NAME`, `ORG_TAGLINE`, `EMAIL_HEADER_COLOR`, `REGISTRATIONS_EMAIL`, or SMTP vars in `.env` (they still work as fallbacks). On a fresh deployment these are set via the first-time setup wizard.
>
> **SMTP credentials** (`smtp_user`, `smtp_pass`) and the **Yoco secret key and webhook secret** are stored **AES-256-GCM encrypted** in the database. The encryption key is derived from `JWT_SECRET`. Do not change `JWT_SECRET` after saving them — the stored values will become unreadable.
>
> To move existing Yoco values from `.env` into the database, run `npm run migrate:env-to-db` (or save them in the Yoco tab).
---
## Database
### Schema summary
| Model | Purpose |
|-------|---------|
| `User` | Accounts with roles (`admin`, `supervisor`, `staff`, `user`) |
| `Event` | Events with dates, pricing, options, attachments |
| `EventOption` | Ticket types / items per event; `stockLimit` (0 = unlimited), `isMainTicket` flag |
| `EarlyBirdTier` | Time-limited discounted prices; linked to an `EventOption` (option-level) or an `OptionVariant` (variant-level via nullable `variantId`); `stockLimit` (0 = unlimited) |
| `OptionVariant` | Sub-items per option (size, colour, ticket type); optional `price` override; own `stockLimit` |
| `Registration` | A user's registration for an event; `status`: pending/confirmed/partial_paid/paid/cancelled |
| `RegistrationOption` | Which options (and quantities) a registration includes; `priceSnapshot`, `appliedTierId`, `variantId` |
| `Payment` | Payment records (Yoco, manual, donation, refund) |
| `Ticket` | QR-code tickets linked to registration options |
| `TicketUsage` | Scan log for each ticket redemption |
| `PasswordReset` | One-time tokens for password reset flow |
| `EventAttachment` | Files attached to events (PDFs, images) |
| `EventForm` / `EventFormField` | Per-event custom forms |
| `FormResponse` / `FormAnswer` | Submitted form data from attendees |
| `FormDraft` | Auto-saved in-progress form data |
| `YocoTransaction` | Raw webhook events from Yoco for reconciliation |
| `Section` / `SectionOption` | Grouping of event options into sections |
| `AppSetting` | Key-value store for runtime config — WAWP credentials, org name, branding, notification emails, SMTP settings (credentials stored AES-256-GCM encrypted), legal page content |
### Migrations
```bash
# Apply pending migrations (production)
npm run prisma:deploy
# Check migration status
npm run prisma:status
# Regenerate Prisma client after schema changes
npm run prisma:generate
```
### Demo data
`npm run set-demo -- --profile=<small|events|ministry|multicampus>` wipes the database (keeping site settings and the admin account) and stages demo data for that kind of church; from the repo root it's `npm run demo:<name>` (`npm run demo:list` describes them). See [DEMO_DATA.md](DEMO_DATA.md).
---
## Running the Server
```bash
# Development (auto-reload; runs the TypeScript in src/ through tsx)
npm run dev
# Production: build once per update, then start (src/index.js runs the build in dist/)
npm run build
npm start
# Type-check only
npm run typecheck
```
Since 1.51.0 the backend is partly TypeScript (`allowJs`: `.js` compiles as it is, `.ts` is checked
strictly). `src/index.js` is a small launcher: with plain Node it runs `dist/` when `dist/build.json`
matches this version, otherwise it compiles on the fly with tsx. The server itself is `src/app.js`.
Visit `/` for the status page. Visit `/docs?token=<admin-jwt>` for the v1 API documentation and `/docs/v2` for the v2 (OpenAPI) reference — both admin only.
---
## Authentication & Roles
All protected routes require a `Bearer` token in the `Authorization` header:
```
Authorization: Bearer <jwt>
```
Tokens are issued on `POST /api/users/login`. Token version is stored per-user; revoking sessions increments the version and invalidates all existing tokens for that user.
### Role Hierarchy
| Role | Description |
|------|-------------|
| `admin` | Full access — user management, delete operations, WhatsApp admin, payment stats |
| `supervisor` | Event/registration/payment management, bulk messaging, reports |
| `staff` | Read access to registrations, payments, tickets; ticket scanning |
| `user` | Own profile, own registrations, own tickets |
### Middleware
| Middleware | Applied when |
|-----------|-------------|
| `protect` | Any authenticated route |
| `admin` | Admin-only actions |
| `supervisor` | Supervisor + admin |
| `staff` | Staff + supervisor + admin |
| `optionalAuth` | Routes that work for guests but enrich responses if authenticated |
| `loginLimiter` | Rate-limits login to 15 req/min per IP |
---
## API Reference
Full interactive API docs available at `GET /docs` (requires admin JWT — pass via `?token=<jwt>` query param or `Authorization: Bearer` header).
### Quick reference by domain
#### Users — `/api/users`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/` | public | Register a new account |
| POST | `/login` | public | Login, returns JWT |
| POST | `/forgot` | public | Request password reset email |
| POST | `/reset` | public | Reset password with token |
| POST | `/activate` | public | Activate account from email link |
| GET | `/profile` | user+ | Get own profile |
| PUT | `/profile` | user+ | Update own profile |
| POST | `/revoke-sessions` | user+ | Revoke own sessions |
| POST | `/close-account` | user+ | Deactivate own account |
| GET | `/` | supervisor+ | List all users (paginated); supports `?search=`, `?role=`, `?isActive=true\|false`, `?page=`, `?limit=` |
| GET | `/:id` | admin | Get user by ID |
| PUT | `/:id` | admin | Update user |
| DELETE | `/:id` | admin | Deactivate user (sets `isActive: false`) |
| POST | `/:id/revoke-sessions` | admin | Revoke all sessions for a user |
| POST | `/:id/anonymize` | admin | Erase personal data — sets name to "Deleted User", clears email/phone, deactivates account, revokes all sessions |
#### Events — `/api/events`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | public | List public/active upcoming events; response includes `isSoldOut: boolean` per event |
| GET | `/all` | staff+ | All events including hidden/past |
| GET | `/admin/all` | admin | All events (admin view) |
| GET | `/attachments/status` | admin | Attachment manifest sync status |
| POST | `/attachments/sync` | admin | Re-sync attachment manifests to DB |
| GET | `/:id` | public | Get event by ID |
| GET | `/by-alias/:redirectUrl` | public | Get event by redirect alias |
| POST | `/` | supervisor+ | Create event |
| PUT | `/:id` | supervisor+ | Update event |
| DELETE | `/:id` | admin | Delete event |
| GET | `/:id/attachments` | public | List event file attachments |
| POST | `/:id/attachments` | supervisor+ | Upload attachment |
| DELETE | `/:eventId/attachments/:id` | supervisor+ | Delete attachment |
| POST | `/:id/email-attendees` | supervisor+ | Bulk email attendees (supports `dryRun`) |
| POST | `/:id/email-attendees/schedule` | supervisor+ | Schedule bulk email |
| POST | `/:id/whatsapp-attendees` | supervisor+ | Bulk WhatsApp to attendees (supports `dryRun`) |
| POST | `/:id/whatsapp-attendees/schedule` | supervisor+ | Schedule bulk WhatsApp |
| POST | `/:id/options` | supervisor+ | Add event option |
| PUT | `/options/:id` | supervisor+ | Update event option |
| DELETE | `/options/:id` | admin | Delete event option |
#### Registrations — `/api/registrations`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/` | optional | Create registration |
| GET | `/myregistrations` | user+ | Own registrations |
| PUT | `/:id/options` | user+ | Update registration options |
| DELETE | `/:id` | user+ | Cancel registration |
| GET | `/:id` | optional | Get registration by ID |
| GET | `/:id/forms/draft` | optional | Get form draft |
| PUT | `/:id/forms/draft` | optional | Save form draft |
| POST | `/:id/forms/responses` | optional | Submit form responses |
| PUT | `/:id/forms/responses` | supervisor+ | Replace form responses |
| GET | `/` | staff+ | List all registrations |
| PUT | `/:id` | staff+ | Update registration status |
| GET | `/event/:eventId` | staff+ | Registrations for an event |
| POST | `/manual` | supervisor+ | Manual registration |
#### Payments — `/api/payments`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/` | supervisor+ | Record manual payment |
| POST | `/yoco-checkout` | user+ | Initiate Yoco checkout |
| GET | `/mypayments` | user+ | Own payments |
| GET | `/:id` | user+ | Payment by ID |
| GET | `/registration/:registrationId` | user+ | Payments for a registration |
| GET | `/` | supervisor+ | All payments |
| GET | `/event/:eventId` | staff+ | Payments for an event |
| PUT | `/assign-donation` | supervisor+ | Assign donation to registration |
| POST | `/refund` | supervisor+ | Create refund |
| GET | `/admin/stats` | admin | Payment statistics |
#### Tickets — `/api/tickets`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/mytickets` | user+ | Own tickets |
| GET | `/:id` | user+ | Ticket by ID |
| POST | `/email` | user+ | Email own tickets |
| POST | `/send-to` | staff+ | Send tickets to a specific user |
| GET | `/scan-preview/:qrCode` | staff+ | Preview scan (no mark) |
| GET | `/qr/:qrCode` | staff+ | Ticket by QR code |
| POST | `/scan/:qrCode` | staff+ | Scan/redeem ticket |
| GET | `/event/:eventId` | staff+ | All tickets for event |
| GET | `/scans/recent` | staff+ | Recent scan activity |
| GET | `/scans/stats` | staff+ | Scan statistics |
| POST | `/generate` | supervisor+ | Generate tickets for registration |
| GET | `/` | supervisor+ | All tickets |
| PUT | `/email-sent` | admin | Bulk mark tickets as emailed |
#### Webhooks — `/api/webhooks`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/yoco` | HMAC | Yoco payment webhook |
| POST | `/whatsapp` | — | WAWP inbound webhook |
#### Broadcasts — `/api/broadcasts` (email)
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/preview` | supervisor+ | Dry-run, returns recipient count/sample |
| POST | `/send` | supervisor+ | Send email broadcast |
| POST | `/schedule` | supervisor+ | Schedule email broadcast |
#### WhatsApp Broadcasts — `/api/whatsapp-broadcasts`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/preview` | supervisor+ | Dry-run |
| POST | `/send` | supervisor+ | Send WA broadcast |
| POST | `/schedule` | supervisor+ | Schedule WA broadcast |
#### Scheduled Messages — `/api/scheduled-emails`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | supervisor+ | List all scheduled jobs |
| PATCH | `/:id` | supervisor+ | Edit a queued job |
| DELETE | `/:id` | supervisor+ | Cancel a queued job |
#### Automations — `/api/automations`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/schedule` | supervisor+ | Schedule event lifecycle automations |
#### Reports — `/api/reports`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/pdf` | user+ | Generate and download PDF report |
| POST | `/email` | user+ | Email PDF report to current user |
#### Settings — `/api/settings`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | public | Public settings (org name, colour, logo, legal keys, etc.) |
| GET | `/all` | admin | All settings — `smtp_pass` returned masked (`••••••••`), `smtp_user` decrypted |
| GET | `/needs-setup` | public | `{ needsSetup: bool }` — true until setup wizard completes |
| PUT | `/` | admin | Upsert settings; `smtp_user` and `smtp_pass` are AES-256-GCM encrypted before storage; sending `••••••••` for `smtp_pass` is a no-op (keeps existing value) |
| POST | `/test-smtp` | admin | Test SMTP connection with provided credentials; success returns `{ message }`, failure returns `{ message, raw }` where `message` is human-readable and `raw` is the original SMTP error. The short-lived admin JWT returned by `POST /api/setup/register` also qualifies during the setup wizard. |
#### Yoco — `/api/yoco`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/config` | admin | Yoco settings with secrets masked card-style (`sk_test_***…aba`), the source of each (`db`/`env`/`none`), test/live mode and the default webhook URL |
| PUT | `/config` | admin | Save `secretKey` and/or `webhookSecret` (AES-256-GCM encrypted). A new key is checked with Yoco first; `''` clears a value |
| GET | `/webhooks` | admin | Webhooks on the Yoco account, flagged `isActive` (its secret is the stored one) and `pointsHere` |
| POST | `/webhooks` | admin | Register a webhook at Yoco (`{ name?, url? }`, URL defaults to `BACKEND_URL/api/webhooks/yoco`, must be public https) and store the secret it returns |
| DELETE | `/webhooks/:id` | admin | Delete a webhook at Yoco; clears the stored secret if it was the active one |
#### Setup — `/api/setup`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/register` | public (one-time) | Step 2 of setup wizard — creates the first admin account and returns a short-lived JWT setup token; blocked once any user exists |
| POST | `/` | setup token or admin | Final step of setup wizard — saves initial site settings (SMTP, org name, branding); requires setup token from `/register` |
#### Uploads — `/api/uploads`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/event-image` | supervisor+ | Upload event cover image (`image` field) |
| POST | `/logo` | admin (or no-auth during setup) | Upload site logo (`image` field) |
#### Sections — `/api/sections`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | staff+ | List sections |
| POST | `/` | supervisor+ | Create section |
| PUT | `/:id` | supervisor+ | Update section |
| DELETE | `/:id` | admin | Delete section |
#### Banner — `/api/banner`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | public | Get current site banner |
| POST | `/` | supervisor+ | Set site banner |
#### Forms — `/api/forms`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/responses` | staff+ | List all form responses |
#### Yoco Transactions — `/api/yoco-transactions`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| GET | `/` | supervisor+ | All Yoco webhook transactions |
| GET | `/unreconciled` | supervisor+ | Unmatched transactions |
| POST | `/:id/reconcile` | supervisor+ | Manually reconcile transaction |
| POST | `/:id/ignore` | supervisor+ | Mark transaction as ignored |
#### WhatsApp Admin — `/api/whatsapp`
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | `/webhook` | public | WAWP inbound event |
| GET | `/config` | admin | Get WAWP credentials |
| POST | `/config` | admin | Save WAWP credentials to DB |
| POST | `/create-instance` | admin | Create WAWP instance |
| POST | `/delete-instance` | admin | Delete WAWP instance |
| GET | `/status` | admin | WAWP session status |
| GET | `/qr` | admin | QR code for WhatsApp linking |
| POST | `/request-code` | admin | Request pairing code |
| POST | `/logout` | admin | Logout WAWP session |
| POST | `/start` | admin | Start WAWP instance |
| POST | `/restart` | admin | Restart WAWP instance |
#### Static Files
| Path | Description |
|------|-------------|
| `/uploads/*` | Served uploaded files (images, PDFs) |
---
## Background Workers
All workers start automatically with `npm start`.
### Scheduled Emails Worker
Polls every 30 s (configurable via `SCHEDULED_EMAILS_INTERVAL_MS`) for due jobs. Handles attendee emails, attendee WhatsApp, email broadcasts, and WhatsApp broadcasts. Disable with `SCHEDULED_EMAILS_ENABLED=false`.
### Daily Event Summaries
Runs at 07:00 local time. Sends summary emails to supervisors about that day's events. Disable with `DAILY_SUMMARY_ENABLED=false`.
### Temp File Cleanup
Runs at 03:00 local time. Removes files older than 7 days from `public/uploads/tickets-temp/`.
### Attachment Manifest Sync
Runs once on startup. Imports on-disk attachment manifests not yet in the database.
---
## Notification System
Outbound notifications are routed through `src/utils/notify.js`:
- `shouldEmail(user)` — true if preference is `email` or `both`
- `canWhatsApp(user)` — true if preference is `whatsapp` or `both` and user has a phone number
- `waText(user, message)` — sends a WhatsApp text
- `waPdf(user, pdfPath, caption)` — copies PDF to temp, sends URL to WAWP, cleans up after 5 min
**Automated notifications**: login, account deletion, ticket delivery, payment confirmation, password reset, daily summaries.
**Dynamic placeholders** in bulk messages: `{{name}}`, `{{event.title}}`, `{{event.start}}`, `{{event.link}}`, `{{balance}}`, `{{promo.title}}`, `{{promo.link}}`.
---
## WhatsApp Integration
WAWP API (`api.wawp.net/v2`). All calls go through `src/utils/whatsapp.js`.
Credentials are stored in `AppSetting` (`WAWP_ACCESS_TOKEN`, `WAWP_INSTANCE_ID`), with `.env` as fallback. Cached in memory for 30 s.
"Session not found" recovery: stale session is deleted and a new one is created automatically, saving the new `instance_id` to `AppSetting`.
Admin UI: `/dashboard/admin/whatsapp`.
---
## File Uploads
- Event images: `POST /api/uploads/event-image` (field `image`), saved to `public/uploads/`
- Event attachments: `POST /api/events/:id/attachments` (field `file`)
- Ticket PDFs: generated on demand, temporarily in `public/uploads/tickets-temp/`, auto-deleted after 5 min
Files are served from `/uploads/*`.
---
## Pricing & Cancellation Rules
### Cancellation
`DELETE /api/registrations/:id`
| Actor | Condition | Result |
|-------|-----------|--------|
| Owner (user) | No positive payments recorded | 200 — status set to `cancelled` |
| Owner (user) | Any positive payment exists | 403 — must contact organisation |
| Admin | Any state | 200 — always allowed |
| Anyone | Already cancelled | 400 |
Cancelled registrations are excluded from all stock-limit counts (option, variant, and tier stock).
### Early-bird pricing — two-phase evaluation
Prices are evaluated in two phases:
**Phase 1 — Registration time** (`resolveOptionPrice` in `src/utils/pricing.js`)
- Selects the cheapest applicable tier, checking **both** the deadline **and** the stock limit.
- Result stored as `priceSnapshot` and `appliedTierId` on each `RegistrationOption`.
- Tier sort order: cheapest first; earliest deadline breaks ties.
**Phase 2 — Payment time** (`refreshPricingForRegistration` in `src/utils/pricing.js`)
- Called automatically before any Yoco checkout is created or any manual payment is recorded.
- Re-runs `resolveOptionPrice` for every `RegistrationOption` that has an `appliedTierId`.
- If a tier has since expired **or its stock has been exhausted**, `priceSnapshot` and `appliedTierId` are updated in the DB to reflect the next applicable tier or the base price.
- If prices changed, `POST /api/payments/yoco-checkout` returns HTTP 200 with `{ priceUpdated: true, newTotal, message }` instead of proceeding to Yoco. The frontend must present the updated total before the user can retry.
- For manual payments (`POST /api/payments`) prices are refreshed silently — no blocking response.
**`computeRegistrationTotalDue`** (also in `src/utils/pricing.js`)
- Uses `priceSnapshot` as the authoritative price when it is set on a `RegistrationOption`.
- Falls back to `getEffectiveUnitPrice` (deadline-only re-evaluation) for legacy rows without a snapshot.
### Variant + tier interaction
Early-bird tiers can be defined at either the **option level** (no `variantId`) or the **variant level** (`variantId` set). Both are stored as `EarlyBirdTier` records on the `EventOption`.
| Variant state | Effective price |
|---------------|-----------------|
| No variant selected | Option-level tiers are evaluated via `resolveOptionPrice` |
| Variant selected, variant has its own tier(s) | Variant-level tiers are evaluated first via `resolveVariantTierPrice` |
| Variant selected, no variant-level tier | Variant's own `price` is used (or option price if `variant.price` is null) |
The resolution priority at registration/payment time is: **variant tier → variant price → option tier → option base price**.
---
## Payments (Yoco)
Setup: Admin → Site Settings → **Yoco**. Paste the secret key (checked with Yoco before saving), then **Generate** a webhook — this registers `BACKEND_URL/api/webhooks/yoco` with Yoco and stores the secret Yoco returns (it's only shown once). Or **Enter** the secret of a webhook you registered yourself. The tab also lists the account's webhooks and can delete them.
1. Frontend calls `POST /api/payments/yoco-checkout`
2. Backend calls `refreshPricingForRegistration` — if any early-bird price changed, returns `{ priceUpdated: true, newTotal }` (HTTP 200) and does **not** create a checkout. Frontend shows warning; user retries.
3. On the retry (or first attempt when prices are current), backend creates a Yoco checkout and returns `{ redirectUrl }`.
4. User pays on Yoco's hosted page.
5. Yoco sends webhook to `POST /api/webhooks/yoco`.
6. Backend verifies HMAC, creates `Payment` + `YocoTransaction`, updates registration status, generates tickets.
7. Unmatched transactions visible at `/api/yoco-transactions/unreconciled`.
---
## Deployment
### PM2 (recommended)
```bash
npm install -g pm2
npm run build
pm2 start src/index.js --name hope-events-api
pm2 save && pm2 startup
```
### Checklist
- [ ] `DATABASE_URL` points to production DB
- [ ] `JWT_SECRET` is long (32+ chars) and secret
- [ ] `FRONTEND_URL` lists only production origins
- [ ] `NODE_ENV=production`
- [ ] Yoco secret key saved and webhook generated (Site Settings → Yoco), over HTTPS
- [ ] WAWP credentials saved via admin panel
- [ ] SMTP credentials correct
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
testMatch: ['**/tests/**/*.test.js', '**/tests/**/*.test.ts'],
// TypeScript (src/**/*.ts and tests) runs through ts-jest; plain JS is left as it is.
transform: { '^.+\\.ts$': ['ts-jest', { tsconfig: 'tsconfig.json' }] },
moduleFileExtensions: ['ts', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
};
+73
View File
@@ -0,0 +1,73 @@
{
"name": "@crosscode/events-backend",
"version": "2.3.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"dev": "tsx watch src/index.js",
"test": "jest",
"postinstall": "prisma generate",
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"prisma:status": "prisma migrate status",
"prisma:reset": "prisma migrate reset --force",
"migrate:env-to-db": "node scripts/migrate-env-to-db.js",
"migrate:env-to-db:dry": "node scripts/migrate-env-to-db.js --dry-run",
"set-demo": "node scripts/set-demo.js",
"build": "tsc -p tsconfig.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"openapi": "tsx scripts/openapi.ts",
"ai:eval": "tsx scripts/ai-eval.ts"
},
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"@sentry/node": "^10.71.0",
"axios": "^1.11.0",
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"cron-parser": "^5.10.2",
"dotenv": "^16.3.1",
"express": "^5.3.0",
"express-rate-limit": "^8.6.2",
"ics": "^3.12.0",
"jsonwebtoken": "^9.0.3",
"multer": "^2.5.0",
"nodemailer": "^10.3.0",
"pdfkit": "^0.17.1",
"pg-boss": "^11.1.2",
"qrcode": "^1.5.4",
"raw-body": "^3.0.0",
"swagger-ui-dist": "^5.34.0",
"tsx": "^4.23.15",
"typescript": "^5.9.3",
"uuid": "^11.1.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^20.19.43",
"@types/supertest": "^7.2.1",
"@types/swagger-ui-dist": "^3.30.6",
"jest": "^30.4.2",
"prisma": "^7.10.1",
"supertest": "^7.3.1",
"ts-jest": "^29.4.15"
},
"overrides": {
"uuid": "^11.1.1",
"@istanbuljs/load-nyc-config": {
"js-yaml": "^4.1.1"
},
"follow-redirects": "^1.16.1"
},
"engines": {
"node": ">=22"
},
"private": true
}
+16
View File
@@ -0,0 +1,16 @@
// Prisma CLI config (migrate, generate, studio). Prisma 7 no longer reads the
// datasource URL from schema.prisma or auto-loads .env, so both happen here.
require('dotenv/config');
const { defineConfig } = require('prisma/config');
module.exports = defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
// process.env rather than env() so `prisma generate` still works on a
// machine with no DATABASE_URL (generate never connects).
url: process.env.DATABASE_URL,
},
});
@@ -0,0 +1,342 @@
-- CreateEnum
CREATE TYPE "UserRole" AS ENUM ('admin', 'supervisor', 'staff', 'user');
-- CreateEnum
CREATE TYPE "RegistrationStatus" AS ENUM ('pending', 'confirmed', 'partial_paid', 'paid', 'cancelled');
-- CreateEnum
CREATE TYPE "FormFieldType" AS ENUM ('yes_no', 'text', 'date', 'numeric', 'statement', 'paragraph');
-- CreateTable
CREATE TABLE "User" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"phoneNumber" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
"role" "UserRole" NOT NULL DEFAULT 'user',
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Event" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT,
"startDate" TIMESTAMP(3) NOT NULL,
"endDate" TIMESTAMP(3) NOT NULL,
"registrationDeadline" TIMESTAMP(3),
"goLiveAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"price" DOUBLE PRECISION NOT NULL,
"picture" TEXT,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"createdById" TEXT,
"redirectUrl" TEXT,
CONSTRAINT "Event_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventOption" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"price" DOUBLE PRECISION NOT NULL,
"isMainTicket" BOOLEAN NOT NULL,
CONSTRAINT "EventOption_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EarlyBirdTier" (
"id" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"deadline" TIMESTAMP(3) NOT NULL,
"price" DOUBLE PRECISION NOT NULL,
"order" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "EarlyBirdTier_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Registration" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"status" "RegistrationStatus" NOT NULL DEFAULT 'pending',
"checkoutId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Registration_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "RegistrationOption" (
"id" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"quantity" INTEGER NOT NULL DEFAULT 1,
CONSTRAINT "RegistrationOption_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Payment" (
"id" TEXT NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"method" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"registrationId" TEXT,
"eventId" TEXT,
"isDonation" BOOLEAN NOT NULL DEFAULT false,
"externalId" TEXT,
"status" TEXT,
"originalPaymentId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Payment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Ticket" (
"id" TEXT NOT NULL,
"qrCode" TEXT NOT NULL,
"registrationOptionId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"isUsed" BOOLEAN NOT NULL DEFAULT false,
"emailSent" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Ticket_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "TicketUsage" (
"id" TEXT NOT NULL,
"ticketId" TEXT NOT NULL,
"scannedById" TEXT NOT NULL,
"scannedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TicketUsage_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PasswordReset" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,
"used" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "PasswordReset_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventAttachment" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"originalName" TEXT NOT NULL,
"filename" TEXT NOT NULL,
"mimeType" TEXT NOT NULL,
"size" INTEGER NOT NULL,
"url" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventAttachment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventForm" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"isRequired" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EventForm_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventFormField" (
"id" TEXT NOT NULL,
"formId" TEXT NOT NULL,
"type" "FormFieldType" NOT NULL,
"label" TEXT NOT NULL,
"isRequired" BOOLEAN NOT NULL DEFAULT false,
"order" INTEGER NOT NULL DEFAULT 0,
"helpText" TEXT,
"options" JSONB,
CONSTRAINT "EventFormField_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FormResponse" (
"id" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FormResponse_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FormAnswer" (
"id" TEXT NOT NULL,
"responseId" TEXT NOT NULL,
"fieldId" TEXT NOT NULL,
"value" TEXT NOT NULL,
CONSTRAINT "FormAnswer_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FormDraft" (
"id" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"data" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "FormDraft_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "YocoTransaction" (
"id" TEXT NOT NULL,
"externalId" TEXT NOT NULL,
"amount" INTEGER,
"currency" TEXT,
"createdDate" TIMESTAMP(3),
"checkoutId" TEXT,
"methodType" TEXT,
"reconciled" BOOLEAN NOT NULL DEFAULT false,
"ignored" BOOLEAN NOT NULL DEFAULT false,
"paymentId" TEXT,
"raw" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "YocoTransaction_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-- CreateIndex
CREATE UNIQUE INDEX "Event_redirectUrl_key" ON "Event"("redirectUrl");
-- CreateIndex
CREATE INDEX "Event_createdById_idx" ON "Event"("createdById");
-- CreateIndex
CREATE INDEX "EarlyBirdTier_eventOptionId_deadline_idx" ON "EarlyBirdTier"("eventOptionId", "deadline");
-- CreateIndex
CREATE UNIQUE INDEX "Registration_checkoutId_key" ON "Registration"("checkoutId");
-- CreateIndex
CREATE UNIQUE INDEX "Payment_externalId_key" ON "Payment"("externalId");
-- CreateIndex
CREATE UNIQUE INDEX "Ticket_qrCode_key" ON "Ticket"("qrCode");
-- CreateIndex
CREATE UNIQUE INDEX "PasswordReset_token_key" ON "PasswordReset"("token");
-- CreateIndex
CREATE UNIQUE INDEX "EventForm_eventId_key" ON "EventForm"("eventId");
-- CreateIndex
CREATE UNIQUE INDEX "FormDraft_registrationId_userId_key" ON "FormDraft"("registrationId", "userId");
-- CreateIndex
CREATE UNIQUE INDEX "YocoTransaction_externalId_key" ON "YocoTransaction"("externalId");
-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventOption" ADD CONSTRAINT "EventOption_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EarlyBirdTier" ADD CONSTRAINT "EarlyBirdTier_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Registration" ADD CONSTRAINT "Registration_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Registration" ADD CONSTRAINT "Registration_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_originalPaymentId_fkey" FOREIGN KEY ("originalPaymentId") REFERENCES "Payment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_scannedById_fkey" FOREIGN KEY ("scannedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "PasswordReset" ADD CONSTRAINT "PasswordReset_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventAttachment" ADD CONSTRAINT "EventAttachment_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventForm" ADD CONSTRAINT "EventForm_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventFormField" ADD CONSTRAINT "EventFormField_formId_fkey" FOREIGN KEY ("formId") REFERENCES "EventForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormResponse" ADD CONSTRAINT "FormResponse_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormAnswer" ADD CONSTRAINT "FormAnswer_responseId_fkey" FOREIGN KEY ("responseId") REFERENCES "FormResponse"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormAnswer" ADD CONSTRAINT "FormAnswer_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "EventFormField"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormDraft" ADD CONSTRAINT "FormDraft_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormDraft" ADD CONSTRAINT "FormDraft_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "YocoTransaction" ADD CONSTRAINT "YocoTransaction_paymentId_fkey" FOREIGN KEY ("paymentId") REFERENCES "Payment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,34 @@
-- CreateTable
CREATE TABLE "Section" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SectionOption" (
"id" TEXT NOT NULL,
"sectionId" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
CONSTRAINT "SectionOption_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Section_eventId_idx" ON "Section"("eventId");
-- CreateIndex
CREATE UNIQUE INDEX "SectionOption_sectionId_eventOptionId_key" ON "SectionOption"("sectionId", "eventOptionId");
-- AddForeignKey
ALTER TABLE "Section" ADD CONSTRAINT "Section_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SectionOption" ADD CONSTRAINT "SectionOption_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SectionOption" ADD CONSTRAINT "SectionOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "failedAttempts" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "lockUntil" TIMESTAMP(3);
@@ -0,0 +1,2 @@
-- AlterTable: add tokenVersion for JWT revocation
ALTER TABLE "User" ADD COLUMN "tokenVersion" INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,9 @@
-- Add isHidden and requiresAuth to Event
ALTER TABLE "Event" ADD COLUMN "isHidden" BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE "Event" ADD COLUMN "requiresAuth" BOOLEAN NOT NULL DEFAULT true;
-- Add quantity to Ticket (1 ticket per option, not per qty unit)
ALTER TABLE "Ticket" ADD COLUMN "quantity" INTEGER NOT NULL DEFAULT 1;
-- Add quantityRedeemed to TicketUsage (for partial redemption)
ALTER TABLE "TicketUsage" ADD COLUMN "quantityRedeemed" INTEGER NOT NULL DEFAULT 1;
@@ -0,0 +1,8 @@
/*
Warnings:
- A unique constraint covering the columns `[phoneNumber]` on the table `User` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateIndex
CREATE UNIQUE INDEX "User_phoneNumber_key" ON "User"("phoneNumber");
@@ -0,0 +1,14 @@
-- CreateIndex
CREATE INDEX "Ticket_eventId_idx" ON "Ticket"("eventId");
-- CreateIndex
CREATE INDEX "Ticket_userId_idx" ON "Ticket"("userId");
-- CreateIndex
CREATE INDEX "TicketUsage_ticketId_idx" ON "TicketUsage"("ticketId");
-- CreateIndex
CREATE INDEX "TicketUsage_scannedAt_idx" ON "TicketUsage"("scannedAt");
-- CreateIndex
CREATE INDEX "TicketUsage_scannedById_scannedAt_idx" ON "TicketUsage"("scannedById", "scannedAt");
@@ -0,0 +1,56 @@
-- CreateIndex
CREATE INDEX "EventAttachment_eventId_idx" ON "EventAttachment"("eventId");
-- CreateIndex
CREATE INDEX "EventFormField_formId_idx" ON "EventFormField"("formId");
-- CreateIndex
CREATE INDEX "EventOption_eventId_idx" ON "EventOption"("eventId");
-- CreateIndex
CREATE INDEX "FormAnswer_responseId_idx" ON "FormAnswer"("responseId");
-- CreateIndex
CREATE INDEX "FormAnswer_fieldId_idx" ON "FormAnswer"("fieldId");
-- CreateIndex
CREATE INDEX "FormResponse_registrationId_idx" ON "FormResponse"("registrationId");
-- CreateIndex
CREATE INDEX "PasswordReset_userId_idx" ON "PasswordReset"("userId");
-- CreateIndex
CREATE INDEX "Payment_userId_idx" ON "Payment"("userId");
-- CreateIndex
CREATE INDEX "Payment_registrationId_idx" ON "Payment"("registrationId");
-- CreateIndex
CREATE INDEX "Payment_eventId_idx" ON "Payment"("eventId");
-- CreateIndex
CREATE INDEX "Payment_createdAt_idx" ON "Payment"("createdAt");
-- CreateIndex
CREATE INDEX "Registration_userId_idx" ON "Registration"("userId");
-- CreateIndex
CREATE INDEX "Registration_eventId_idx" ON "Registration"("eventId");
-- CreateIndex
CREATE INDEX "Registration_userId_status_idx" ON "Registration"("userId", "status");
-- CreateIndex
CREATE INDEX "Registration_eventId_status_idx" ON "Registration"("eventId", "status");
-- CreateIndex
CREATE INDEX "RegistrationOption_registrationId_idx" ON "RegistrationOption"("registrationId");
-- CreateIndex
CREATE INDEX "RegistrationOption_eventOptionId_idx" ON "RegistrationOption"("eventOptionId");
-- CreateIndex
CREATE INDEX "Ticket_registrationOptionId_idx" ON "Ticket"("registrationOptionId");
-- CreateIndex
CREATE INDEX "YocoTransaction_paymentId_idx" ON "YocoTransaction"("paymentId");
@@ -0,0 +1,5 @@
-- CreateEnum
CREATE TYPE "NotificationPreference" AS ENUM ('email', 'whatsapp', 'both');
-- AlterTable
ALTER TABLE "User" ADD COLUMN "notificationPreference" "NotificationPreference" NOT NULL DEFAULT 'email';
@@ -0,0 +1,8 @@
-- CreateTable
CREATE TABLE "AppSetting" (
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
);
@@ -0,0 +1,37 @@
-- Add stockLimit to EventOption
ALTER TABLE "EventOption" ADD COLUMN "stockLimit" INTEGER NOT NULL DEFAULT 0;
-- Add stockLimit to EarlyBirdTier
ALTER TABLE "EarlyBirdTier" ADD COLUMN "stockLimit" INTEGER NOT NULL DEFAULT 0;
-- CreateTable OptionVariant
CREATE TABLE "OptionVariant" (
"id" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"price" DOUBLE PRECISION,
"stockLimit" INTEGER NOT NULL DEFAULT 0,
"order" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "OptionVariant_pkey" PRIMARY KEY ("id")
);
-- Add new columns to RegistrationOption
ALTER TABLE "RegistrationOption" ADD COLUMN "variantId" TEXT;
ALTER TABLE "RegistrationOption" ADD COLUMN "appliedTierId" TEXT;
ALTER TABLE "RegistrationOption" ADD COLUMN "priceSnapshot" DOUBLE PRECISION;
-- CreateIndex
CREATE INDEX "OptionVariant_eventOptionId_idx" ON "OptionVariant"("eventOptionId");
CREATE INDEX "RegistrationOption_variantId_idx" ON "RegistrationOption"("variantId");
CREATE INDEX "RegistrationOption_appliedTierId_idx" ON "RegistrationOption"("appliedTierId");
-- AddForeignKey
ALTER TABLE "OptionVariant" ADD CONSTRAINT "OptionVariant_eventOptionId_fkey"
FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_variantId_fkey"
FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_appliedTierId_fkey"
FOREIGN KEY ("appliedTierId") REFERENCES "EarlyBirdTier"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,8 @@
-- AlterTable
ALTER TABLE "EarlyBirdTier" ADD COLUMN "variantId" TEXT;
-- CreateIndex
CREATE INDEX "EarlyBirdTier_variantId_idx" ON "EarlyBirdTier"("variantId");
-- AddForeignKey
ALTER TABLE "EarlyBirdTier" ADD CONSTRAINT "EarlyBirdTier_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,213 @@
-- CreateTable
CREATE TABLE "Ministry" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT,
"image" TEXT,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"order" INTEGER NOT NULL DEFAULT 0,
"leaderId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "TeamMember" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"title" TEXT NOT NULL,
"bio" TEXT,
"photo" TEXT,
"order" INTEGER NOT NULL DEFAULT 0,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"email" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TeamMember_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ContentBlock" (
"id" TEXT NOT NULL,
"page" TEXT NOT NULL,
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
"type" TEXT NOT NULL DEFAULT 'text',
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ContentBlock_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChurchDocument" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"description" TEXT,
"fileUrl" TEXT NOT NULL,
"category" TEXT NOT NULL DEFAULT 'other',
"isPublic" BOOLEAN NOT NULL DEFAULT true,
"uploadedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ChurchDocument_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FellowshipGroup" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"leader" TEXT,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "FellowshipGroup_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChurchMember" (
"id" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"mainName" TEXT NOT NULL,
"mainEmail" TEXT NOT NULL,
"mainPhone" TEXT,
"mainBirthday" TIMESTAMP(3),
"mainOccupation" TEXT,
"mainEmploymentStatus" TEXT,
"mainDateOfSalvation" TIMESTAMP(3),
"mainDateOfWaterBaptism" TIMESTAMP(3),
"mainHolySpiritBaptism" BOOLEAN NOT NULL DEFAULT false,
"spouseName" TEXT,
"spouseEmail" TEXT,
"spousePhone" TEXT,
"spouseBirthday" TIMESTAMP(3),
"spouseOccupation" TEXT,
"spouseEmploymentStatus" TEXT,
"spouseDateOfSalvation" TIMESTAMP(3),
"spouseDateOfWaterBaptism" TIMESTAMP(3),
"spouseHolySpiritBaptism" BOOLEAN,
"homeAddress" TEXT,
"inFellowshipGroup" BOOLEAN NOT NULL DEFAULT false,
"fellowshipGroupId" TEXT,
"membershipConfirmed" BOOLEAN NOT NULL DEFAULT false,
"notes" TEXT,
"appliedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"approvedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ChurchMember_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ChurchChild" (
"id" TEXT NOT NULL,
"memberId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"birthday" TIMESTAMP(3),
CONSTRAINT "ChurchChild_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MinistryInterest" (
"id" TEXT NOT NULL,
"memberId" TEXT NOT NULL,
"ministryId" TEXT NOT NULL,
"forSpouse" BOOLEAN NOT NULL DEFAULT false,
CONSTRAINT "MinistryInterest_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Donation" (
"id" TEXT NOT NULL,
"donorName" TEXT,
"donorEmail" TEXT,
"donorPhone" TEXT,
"amount" DOUBLE PRECISION NOT NULL,
"method" TEXT NOT NULL,
"reference" TEXT,
"note" TEXT,
"isAnonymous" BOOLEAN NOT NULL DEFAULT false,
"linkedMemberId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Donation_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
-- CreateIndex
CREATE INDEX "Ministry_isActive_order_idx" ON "Ministry"("isActive", "order");
-- CreateIndex
CREATE INDEX "Ministry_leaderId_idx" ON "Ministry"("leaderId");
-- CreateIndex
CREATE INDEX "TeamMember_isActive_order_idx" ON "TeamMember"("isActive", "order");
-- CreateIndex
CREATE INDEX "ContentBlock_page_idx" ON "ContentBlock"("page");
-- CreateIndex
CREATE UNIQUE INDEX "ContentBlock_page_key_key" ON "ContentBlock"("page", "key");
-- CreateIndex
CREATE INDEX "FellowshipGroup_isActive_order_idx" ON "FellowshipGroup"("isActive", "order");
-- CreateIndex
CREATE INDEX "ChurchMember_status_idx" ON "ChurchMember"("status");
-- CreateIndex
CREATE INDEX "ChurchMember_mainEmail_idx" ON "ChurchMember"("mainEmail");
-- CreateIndex
CREATE INDEX "ChurchMember_fellowshipGroupId_idx" ON "ChurchMember"("fellowshipGroupId");
-- CreateIndex
CREATE INDEX "ChurchChild_memberId_idx" ON "ChurchChild"("memberId");
-- CreateIndex
CREATE INDEX "MinistryInterest_memberId_idx" ON "MinistryInterest"("memberId");
-- CreateIndex
CREATE INDEX "MinistryInterest_ministryId_idx" ON "MinistryInterest"("ministryId");
-- CreateIndex
CREATE UNIQUE INDEX "MinistryInterest_memberId_ministryId_forSpouse_key" ON "MinistryInterest"("memberId", "ministryId", "forSpouse");
-- CreateIndex
CREATE INDEX "Donation_linkedMemberId_idx" ON "Donation"("linkedMemberId");
-- CreateIndex
CREATE INDEX "Donation_createdAt_idx" ON "Donation"("createdAt");
-- CreateIndex
CREATE INDEX "Donation_method_idx" ON "Donation"("method");
-- AddForeignKey
ALTER TABLE "Ministry" ADD CONSTRAINT "Ministry_leaderId_fkey" FOREIGN KEY ("leaderId") REFERENCES "TeamMember"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChurchMember" ADD CONSTRAINT "ChurchMember_fellowshipGroupId_fkey" FOREIGN KEY ("fellowshipGroupId") REFERENCES "FellowshipGroup"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ChurchChild" ADD CONSTRAINT "ChurchChild_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "ChurchMember"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MinistryInterest" ADD CONSTRAINT "MinistryInterest_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "ChurchMember"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "MinistryInterest" ADD CONSTRAINT "MinistryInterest_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Donation" ADD CONSTRAINT "Donation_linkedMemberId_fkey" FOREIGN KEY ("linkedMemberId") REFERENCES "ChurchMember"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,158 @@
/*
Warnings:
- You are about to drop the `ChurchChild` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `ChurchDocument` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `ChurchMember` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `ContentBlock` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `Donation` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `FellowshipGroup` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `Ministry` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `MinistryInterest` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `TeamMember` table. If the table is not empty, all the data it contains will be lost.
*/
-- CreateEnum
CREATE TYPE "CashupStatus" AS ENUM ('open', 'closed');
-- CreateEnum
CREATE TYPE "CashupAction" AS ENUM ('closed', 'quick_closed', 'reopened');
-- CreateEnum
CREATE TYPE "EventCostType" AS ENUM ('once_off', 'per_item');
-- DropForeignKey
ALTER TABLE "ChurchChild" DROP CONSTRAINT "ChurchChild_memberId_fkey";
-- DropForeignKey
ALTER TABLE "ChurchMember" DROP CONSTRAINT "ChurchMember_fellowshipGroupId_fkey";
-- DropForeignKey
ALTER TABLE "Donation" DROP CONSTRAINT "Donation_linkedMemberId_fkey";
-- DropForeignKey
ALTER TABLE "Ministry" DROP CONSTRAINT "Ministry_leaderId_fkey";
-- DropForeignKey
ALTER TABLE "MinistryInterest" DROP CONSTRAINT "MinistryInterest_memberId_fkey";
-- DropForeignKey
ALTER TABLE "MinistryInterest" DROP CONSTRAINT "MinistryInterest_ministryId_fkey";
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "cashupDraft" JSONB,
ADD COLUMN "cashupStatus" "CashupStatus" NOT NULL DEFAULT 'open',
ADD COLUMN "closedAt" TIMESTAMP(3),
ADD COLUMN "closedById" TEXT,
ADD COLUMN "reopenedAt" TIMESTAMP(3),
ADD COLUMN "reopenedById" TEXT;
-- DropTable
DROP TABLE "ChurchChild";
-- DropTable
DROP TABLE "ChurchDocument";
-- DropTable
DROP TABLE "ChurchMember";
-- DropTable
DROP TABLE "ContentBlock";
-- DropTable
DROP TABLE "Donation";
-- DropTable
DROP TABLE "FellowshipGroup";
-- DropTable
DROP TABLE "Ministry";
-- DropTable
DROP TABLE "MinistryInterest";
-- DropTable
DROP TABLE "TeamMember";
-- CreateTable
CREATE TABLE "EventCost" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"eventOptionId" TEXT,
"label" TEXT NOT NULL,
"costType" "EventCostType" NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"notes" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EventCost_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventCashup" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"action" "CashupAction" NOT NULL,
"donationsWrittenOff" DOUBLE PRECISION NOT NULL DEFAULT 0,
"totalCosts" DOUBLE PRECISION NOT NULL DEFAULT 0,
"totalExpectedRevenue" DOUBLE PRECISION NOT NULL DEFAULT 0,
"totalActualRevenue" DOUBLE PRECISION,
"notes" TEXT,
"performedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventCashup_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventCashupLine" (
"id" TEXT NOT NULL,
"cashupId" TEXT NOT NULL,
"method" TEXT NOT NULL,
"expectedAmount" DOUBLE PRECISION NOT NULL DEFAULT 0,
"actualAmount" DOUBLE PRECISION,
"variance" DOUBLE PRECISION,
"notes" TEXT,
CONSTRAINT "EventCashupLine_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventCost_eventId_idx" ON "EventCost"("eventId");
-- CreateIndex
CREATE INDEX "EventCost_eventOptionId_idx" ON "EventCost"("eventOptionId");
-- CreateIndex
CREATE INDEX "EventCashup_eventId_createdAt_idx" ON "EventCashup"("eventId", "createdAt");
-- CreateIndex
CREATE INDEX "EventCashupLine_cashupId_idx" ON "EventCashupLine"("cashupId");
-- CreateIndex
CREATE INDEX "Event_closedById_idx" ON "Event"("closedById");
-- CreateIndex
CREATE INDEX "Event_reopenedById_idx" ON "Event"("reopenedById");
-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_closedById_fkey" FOREIGN KEY ("closedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_reopenedById_fkey" FOREIGN KEY ("reopenedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCost" ADD CONSTRAINT "EventCost_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCost" ADD CONSTRAINT "EventCost_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashup" ADD CONSTRAINT "EventCashup_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashup" ADD CONSTRAINT "EventCashup_performedById_fkey" FOREIGN KEY ("performedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupLine" ADD CONSTRAINT "EventCashupLine_cashupId_fkey" FOREIGN KEY ("cashupId") REFERENCES "EventCashup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,21 @@
-- AlterTable: rename donationsWrittenOff -> unallocatedDonationsTotal, preserving existing values
ALTER TABLE "EventCashup" RENAME COLUMN "donationsWrittenOff" TO "unallocatedDonationsTotal";
-- AlterTable
ALTER TABLE "EventCost" ADD COLUMN "paidFromMethod" TEXT;
-- CreateTable
CREATE TABLE "EventCashupDenomination" (
"id" TEXT NOT NULL,
"lineId" TEXT NOT NULL,
"value" DOUBLE PRECISION NOT NULL,
"count" INTEGER NOT NULL,
CONSTRAINT "EventCashupDenomination_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventCashupDenomination_lineId_idx" ON "EventCashupDenomination"("lineId");
-- AddForeignKey
ALTER TABLE "EventCashupDenomination" ADD CONSTRAINT "EventCashupDenomination_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE "_EventNotifyRecipients" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "_EventNotifyRecipients_AB_unique" ON "_EventNotifyRecipients"("A", "B");
-- CreateIndex
CREATE INDEX "_EventNotifyRecipients_B_index" ON "_EventNotifyRecipients"("B");
-- AddForeignKey
ALTER TABLE "_EventNotifyRecipients" ADD CONSTRAINT "_EventNotifyRecipients_A_fkey" FOREIGN KEY ("A") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_EventNotifyRecipients" ADD CONSTRAINT "_EventNotifyRecipients_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,5 @@
-- AlterTable
ALTER TABLE "Payment" ADD COLUMN "feeAmount" DOUBLE PRECISION,
ADD COLUMN "feeChannel" TEXT,
ADD COLUMN "feePayer" TEXT,
ADD COLUMN "feeRate" DOUBLE PRECISION;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "feePayerOnline" TEXT;
@@ -0,0 +1,12 @@
/*
Warnings:
- You are about to drop the column `feePayerOnline` on the `Event` table. All the data in the column will be lost.
- You are about to drop the column `feePayer` on the `Payment` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "Event" DROP COLUMN "feePayerOnline";
-- AlterTable
ALTER TABLE "Payment" DROP COLUMN "feePayer";
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "EventCashupLine" ADD COLUMN "feeAmount" DOUBLE PRECISION;
@@ -0,0 +1,11 @@
-- AlterTable
ALTER TABLE "Payment" ADD COLUMN "recordedById" TEXT;
-- CreateIndex
CREATE INDEX "Payment_recordedById_idx" ON "Payment"("recordedById");
-- CreateIndex
CREATE INDEX "Payment_originalPaymentId_idx" ON "Payment"("originalPaymentId");
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_recordedById_fkey" FOREIGN KEY ("recordedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,43 @@
-- CreateTable
CREATE TABLE "EventCashupPersonCount" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"enteredById" TEXT,
"notes" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EventCashupPersonCount_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventCashupPersonCountDenomination" (
"id" TEXT NOT NULL,
"countId" TEXT NOT NULL,
"value" DOUBLE PRECISION NOT NULL,
"count" INTEGER NOT NULL,
CONSTRAINT "EventCashupPersonCountDenomination_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventCashupPersonCount_eventId_idx" ON "EventCashupPersonCount"("eventId");
-- CreateIndex
CREATE UNIQUE INDEX "EventCashupPersonCount_eventId_userId_key" ON "EventCashupPersonCount"("eventId", "userId");
-- CreateIndex
CREATE INDEX "EventCashupPersonCountDenomination_countId_idx" ON "EventCashupPersonCountDenomination"("countId");
-- AddForeignKey
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPersonCount" ADD CONSTRAINT "EventCashupPersonCount_enteredById_fkey" FOREIGN KEY ("enteredById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPersonCountDenomination" ADD CONSTRAINT "EventCashupPersonCountDenomination_countId_fkey" FOREIGN KEY ("countId") REFERENCES "EventCashupPersonCount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,20 @@
-- CreateEnum
CREATE TYPE "SecurityEventType" AS ENUM ('login', 'password_changed', 'password_reset');
-- CreateTable
CREATE TABLE "SecurityEvent" (
"id" TEXT NOT NULL,
"userId" TEXT,
"type" "SecurityEventType" NOT NULL,
"ip" TEXT,
"device" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SecurityEvent_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "SecurityEvent_userId_createdAt_idx" ON "SecurityEvent"("userId", "createdAt");
-- AddForeignKey
ALTER TABLE "SecurityEvent" ADD CONSTRAINT "SecurityEvent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,11 @@
-- DropIndex
DROP INDEX "Payment_originalPaymentId_idx";
-- CreateIndex
CREATE INDEX "Payment_originalPaymentId_isDonation_idx" ON "Payment"("originalPaymentId", "isDonation");
-- CreateIndex
CREATE INDEX "Registration_createdAt_status_idx" ON "Registration"("createdAt", "status");
-- CreateIndex
CREATE INDEX "Ticket_createdAt_idx" ON "Ticket"("createdAt");
@@ -0,0 +1,16 @@
/*
Warnings:
- You are about to drop the column `feeAmount` on the `EventCashupLine` table. All the data in the column will be lost.
- You are about to drop the column `feeAmount` on the `Payment` table. All the data in the column will be lost.
- You are about to drop the column `feeChannel` on the `Payment` table. All the data in the column will be lost.
- You are about to drop the column `feeRate` on the `Payment` table. All the data in the column will be lost.
*/
-- AlterTable
ALTER TABLE "EventCashupLine" DROP COLUMN "feeAmount";
-- AlterTable
ALTER TABLE "Payment" DROP COLUMN "feeAmount",
DROP COLUMN "feeChannel",
DROP COLUMN "feeRate";
@@ -0,0 +1,29 @@
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "contactEmail" TEXT,
ADD COLUMN "contactName" TEXT,
ADD COLUMN "contactPhone" TEXT,
ADD COLUMN "requiresRegistration" BOOLEAN NOT NULL DEFAULT true;
-- CreateTable
CREATE TABLE "RegistrationOptionTranche" (
"id" TEXT NOT NULL,
"registrationOptionId" TEXT NOT NULL,
"quantity" INTEGER NOT NULL,
"priceSnapshot" DOUBLE PRECISION NOT NULL,
"appliedTierId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "RegistrationOptionTranche_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "RegistrationOptionTranche_registrationOptionId_idx" ON "RegistrationOptionTranche"("registrationOptionId");
-- CreateIndex
CREATE INDEX "RegistrationOptionTranche_appliedTierId_idx" ON "RegistrationOptionTranche"("appliedTierId");
-- AddForeignKey
ALTER TABLE "RegistrationOptionTranche" ADD CONSTRAINT "RegistrationOptionTranche_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "RegistrationOptionTranche" ADD CONSTRAINT "RegistrationOptionTranche_appliedTierId_fkey" FOREIGN KEY ("appliedTierId") REFERENCES "EarlyBirdTier"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "location" TEXT;
@@ -0,0 +1,29 @@
-- CreateEnum
CREATE TYPE "AdminAuditAction" AS ENUM ('refund_created', 'donation_assigned', 'donation_unassigned', 'registration_created_manual', 'registration_cancelled', 'event_created', 'event_updated', 'event_deleted', 'settings_updated');
-- CreateTable
CREATE TABLE "AdminAuditLog" (
"id" TEXT NOT NULL,
"actorId" TEXT,
"actorRole" TEXT NOT NULL,
"action" "AdminAuditAction" NOT NULL,
"targetType" TEXT NOT NULL,
"targetId" TEXT,
"metadata" JSONB,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AdminAuditLog_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "AdminAuditLog_actorId_createdAt_idx" ON "AdminAuditLog"("actorId", "createdAt");
-- CreateIndex
CREATE INDEX "AdminAuditLog_action_createdAt_idx" ON "AdminAuditLog"("action", "createdAt");
-- CreateIndex
CREATE INDEX "AdminAuditLog_targetType_targetId_idx" ON "AdminAuditLog"("targetType", "targetId");
-- AddForeignKey
ALTER TABLE "AdminAuditLog" ADD CONSTRAINT "AdminAuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,62 @@
-- CreateEnum
CREATE TYPE "TwoFactorMethod" AS ENUM ('email', 'whatsapp');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "SecurityEventType" ADD VALUE 'two_factor_enabled';
ALTER TYPE "SecurityEventType" ADD VALUE 'two_factor_disabled';
-- AlterTable
ALTER TABLE "User" ADD COLUMN "twoFactorEnabled" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "twoFactorMethod" "TwoFactorMethod";
-- CreateTable
CREATE TABLE "TwoFactorChallenge" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"purpose" TEXT NOT NULL,
"method" "TwoFactorMethod" NOT NULL,
"codeHash" TEXT NOT NULL,
"attempts" INTEGER NOT NULL DEFAULT 0,
"lastSentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
"usedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TwoFactorChallenge_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "TrustedDevice" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"device" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"lastUsedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TrustedDevice_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "TwoFactorChallenge_userId_idx" ON "TwoFactorChallenge"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "TrustedDevice_tokenHash_key" ON "TrustedDevice"("tokenHash");
-- CreateIndex
CREATE INDEX "TrustedDevice_userId_idx" ON "TrustedDevice"("userId");
-- AddForeignKey
ALTER TABLE "TwoFactorChallenge" ADD CONSTRAINT "TwoFactorChallenge_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TrustedDevice" ADD CONSTRAINT "TrustedDevice_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,164 @@
-- CreateEnum
CREATE TYPE "CouponType" AS ENUM ('percent', 'fixed', 'comp');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_created';
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_disabled';
ALTER TYPE "AdminAuditAction" ADD VALUE 'coupon_applied_manual';
-- AlterTable
ALTER TABLE "EventOption" ADD COLUMN "staffPrice" DOUBLE PRECISION;
-- AlterTable
ALTER TABLE "OptionVariant" ADD COLUMN "staffPrice" DOUBLE PRECISION;
-- AlterTable
ALTER TABLE "Registration" ADD COLUMN "discountTotal" DOUBLE PRECISION NOT NULL DEFAULT 0;
-- CreateTable
CREATE TABLE "Coupon" (
"id" TEXT NOT NULL,
"code" TEXT NOT NULL,
"description" TEXT,
"type" "CouponType" NOT NULL,
"value" DOUBLE PRECISION NOT NULL DEFAULT 0,
"stackEarlyBird" BOOLEAN NOT NULL DEFAULT false,
"validFrom" TIMESTAMP(3),
"validUntil" TIMESTAMP(3),
"maxUses" INTEGER,
"maxUsesPerUser" INTEGER DEFAULT 1,
"minQuantity" INTEGER,
"restrictRoles" "UserRole"[],
"restrictDomain" TEXT,
"active" BOOLEAN NOT NULL DEFAULT true,
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Coupon_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CouponEvent" (
"id" TEXT NOT NULL,
"couponId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
CONSTRAINT "CouponEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CouponOption" (
"id" TEXT NOT NULL,
"couponId" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"variantId" TEXT,
CONSTRAINT "CouponOption_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CouponUser" (
"id" TEXT NOT NULL,
"couponId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "CouponUser_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "CouponRedemption" (
"id" TEXT NOT NULL,
"couponId" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"discountAmount" DOUBLE PRECISION NOT NULL,
"appliedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"releasedAt" TIMESTAMP(3),
CONSTRAINT "CouponRedemption_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Coupon_code_key" ON "Coupon"("code");
-- CreateIndex
CREATE INDEX "Coupon_createdById_idx" ON "Coupon"("createdById");
-- CreateIndex
CREATE INDEX "CouponEvent_eventId_idx" ON "CouponEvent"("eventId");
-- CreateIndex
CREATE UNIQUE INDEX "CouponEvent_couponId_eventId_key" ON "CouponEvent"("couponId", "eventId");
-- CreateIndex
CREATE INDEX "CouponOption_couponId_idx" ON "CouponOption"("couponId");
-- CreateIndex
CREATE INDEX "CouponOption_eventOptionId_idx" ON "CouponOption"("eventOptionId");
-- CreateIndex
CREATE INDEX "CouponOption_variantId_idx" ON "CouponOption"("variantId");
-- CreateIndex
CREATE INDEX "CouponUser_userId_idx" ON "CouponUser"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "CouponUser_couponId_userId_key" ON "CouponUser"("couponId", "userId");
-- CreateIndex
CREATE INDEX "CouponRedemption_couponId_releasedAt_idx" ON "CouponRedemption"("couponId", "releasedAt");
-- CreateIndex
CREATE INDEX "CouponRedemption_registrationId_idx" ON "CouponRedemption"("registrationId");
-- CreateIndex
CREATE INDEX "CouponRedemption_userId_idx" ON "CouponRedemption"("userId");
-- CreateIndex
CREATE INDEX "CouponRedemption_appliedById_idx" ON "CouponRedemption"("appliedById");
-- AddForeignKey
ALTER TABLE "Coupon" ADD CONSTRAINT "Coupon_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponEvent" ADD CONSTRAINT "CouponEvent_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponEvent" ADD CONSTRAINT "CouponEvent_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponOption" ADD CONSTRAINT "CouponOption_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponUser" ADD CONSTRAINT "CouponUser_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponUser" ADD CONSTRAINT "CouponUser_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_couponId_fkey" FOREIGN KEY ("couponId") REFERENCES "Coupon"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CouponRedemption" ADD CONSTRAINT "CouponRedemption_appliedById_fkey" FOREIGN KEY ("appliedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,69 @@
-- CreateEnum
CREATE TYPE "TicketDelivery" AS ENUM ('payer', 'each');
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "allowNamedAttendees" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable
ALTER TABLE "FormResponse" ADD COLUMN "attendeeId" TEXT;
-- AlterTable
ALTER TABLE "Registration" ADD COLUMN "ticketDelivery" "TicketDelivery" NOT NULL DEFAULT 'payer';
-- AlterTable
ALTER TABLE "Ticket" ADD COLUMN "attendeeId" TEXT,
ADD COLUMN "holderUserId" TEXT;
-- CreateTable
CREATE TABLE "Attendee" (
"id" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"registrationOptionId" TEXT,
"eventOptionId" TEXT NOT NULL,
"variantId" TEXT,
"name" TEXT NOT NULL,
"email" TEXT,
"phone" TEXT,
"userId" TEXT,
"dateOfBirth" TIMESTAMP(3),
"gender" TEXT,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Attendee_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Attendee_registrationId_idx" ON "Attendee"("registrationId");
-- CreateIndex
CREATE INDEX "Attendee_registrationOptionId_idx" ON "Attendee"("registrationOptionId");
-- CreateIndex
CREATE INDEX "Attendee_userId_idx" ON "Attendee"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "Ticket_attendeeId_key" ON "Ticket"("attendeeId");
-- CreateIndex
CREATE INDEX "Ticket_holderUserId_idx" ON "Ticket"("holderUserId");
-- AddForeignKey
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Ticket" ADD CONSTRAINT "Ticket_holderUserId_fkey" FOREIGN KEY ("holderUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FormResponse" ADD CONSTRAINT "FormResponse_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_registrationOptionId_fkey" FOREIGN KEY ("registrationOptionId") REFERENCES "RegistrationOption"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Attendee" ADD CONSTRAINT "Attendee_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,71 @@
-- CreateEnum
CREATE TYPE "ConsentStatus" AS ENUM ('pending', 'given', 'declined');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'consent_override';
ALTER TYPE "AdminAuditAction" ADD VALUE 'consent_rerequested';
ALTER TYPE "AdminAuditAction" ADD VALUE 'medical_list_viewed';
-- AlterTable
ALTER TABLE "Attendee" ADD COLUMN "parentEmail" TEXT,
ADD COLUMN "parentName" TEXT,
ADD COLUMN "parentPhone" TEXT;
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "consentCollectEmergency" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "consentCollectMedical" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "consentCollectPhoto" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "consentText" TEXT,
ADD COLUMN "consentTextVersion" INTEGER NOT NULL DEFAULT 1,
ADD COLUMN "requiresParentalConsent" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "ConsentRequest" (
"id" TEXT NOT NULL,
"attendeeId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"status" "ConsentStatus" NOT NULL DEFAULT 'pending',
"textVersion" INTEGER NOT NULL,
"consentText" TEXT NOT NULL,
"parentName" TEXT,
"parentEmail" TEXT,
"parentPhone" TEXT,
"signedName" TEXT,
"ip" TEXT,
"device" TEXT,
"medical" TEXT,
"emergency" TEXT,
"photoConsent" BOOLEAN,
"respondedAt" TIMESTAMP(3),
"lastSentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"remindersSent" INTEGER NOT NULL DEFAULT 0,
"expiresAt" TIMESTAMP(3) NOT NULL,
"medicalPurgedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ConsentRequest_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "ConsentRequest_tokenHash_key" ON "ConsentRequest"("tokenHash");
-- CreateIndex
CREATE INDEX "ConsentRequest_attendeeId_createdAt_idx" ON "ConsentRequest"("attendeeId", "createdAt");
-- CreateIndex
CREATE INDEX "ConsentRequest_eventId_status_idx" ON "ConsentRequest"("eventId", "status");
-- AddForeignKey
ALTER TABLE "ConsentRequest" ADD CONSTRAINT "ConsentRequest_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ConsentRequest" ADD CONSTRAINT "ConsentRequest_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,63 @@
-- CreateEnum
CREATE TYPE "WaitlistStatus" AS ENUM ('waiting', 'offered', 'claimed', 'expired', 'removed', 'left');
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "waitlistEnabled" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "waitlistOfferHours" INTEGER NOT NULL DEFAULT 24,
ADD COLUMN "waitlistPartialOffers" BOOLEAN NOT NULL DEFAULT true;
-- CreateTable
CREATE TABLE "WaitlistEntry" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"variantId" TEXT,
"userId" TEXT NOT NULL,
"quantity" INTEGER NOT NULL,
"position" INTEGER NOT NULL,
"status" "WaitlistStatus" NOT NULL DEFAULT 'waiting',
"offeredQuantity" INTEGER,
"offerTokenHash" TEXT,
"offeredAt" TIMESTAMP(3),
"offerExpiresAt" TIMESTAMP(3),
"claimedAt" TIMESTAMP(3),
"registrationId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "WaitlistEntry_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "WaitlistEntry_offerTokenHash_key" ON "WaitlistEntry"("offerTokenHash");
-- CreateIndex
CREATE INDEX "WaitlistEntry_eventId_status_position_idx" ON "WaitlistEntry"("eventId", "status", "position");
-- CreateIndex
CREATE INDEX "WaitlistEntry_eventOptionId_status_idx" ON "WaitlistEntry"("eventOptionId", "status");
-- CreateIndex
CREATE INDEX "WaitlistEntry_variantId_idx" ON "WaitlistEntry"("variantId");
-- CreateIndex
CREATE INDEX "WaitlistEntry_userId_idx" ON "WaitlistEntry"("userId");
-- CreateIndex
CREATE INDEX "WaitlistEntry_registrationId_idx" ON "WaitlistEntry"("registrationId");
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,93 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_acquired';
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_released';
ALTER TYPE "AdminAuditAction" ADD VALUE 'scan_lock_force_released';
ALTER TYPE "AdminAuditAction" ADD VALUE 'offline_sync';
-- AlterTable
ALTER TABLE "TicketUsage" ADD COLUMN "clientScanId" TEXT,
ADD COLUMN "offline" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "scanLockId" TEXT,
ADD COLUMN "syncedAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "ScanLock" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"sectionId" TEXT,
"deviceId" TEXT NOT NULL,
"deviceName" TEXT,
"userId" TEXT NOT NULL,
"lockedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"snapshotAt" TIMESTAMP(3),
"lastSyncAt" TIMESTAMP(3),
"releasedAt" TIMESTAMP(3),
"forceReleasedById" TEXT,
CONSTRAINT "ScanLock_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "OfflineSyncReport" (
"id" TEXT NOT NULL,
"scanLockId" TEXT NOT NULL,
"accepted" INTEGER NOT NULL DEFAULT 0,
"duplicates" INTEGER NOT NULL DEFAULT 0,
"conflicts" JSONB NOT NULL DEFAULT '[]',
"afterForceRelease" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"reviewedAt" TIMESTAMP(3),
"reviewedById" TEXT,
CONSTRAINT "OfflineSyncReport_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ScanLock_eventId_releasedAt_idx" ON "ScanLock"("eventId", "releasedAt");
-- CreateIndex
CREATE INDEX "ScanLock_userId_idx" ON "ScanLock"("userId");
-- CreateIndex
CREATE INDEX "ScanLock_sectionId_idx" ON "ScanLock"("sectionId");
-- CreateIndex
CREATE INDEX "ScanLock_forceReleasedById_idx" ON "ScanLock"("forceReleasedById");
-- CreateIndex
CREATE INDEX "OfflineSyncReport_scanLockId_idx" ON "OfflineSyncReport"("scanLockId");
-- CreateIndex
CREATE INDEX "OfflineSyncReport_reviewedById_idx" ON "OfflineSyncReport"("reviewedById");
-- CreateIndex
CREATE UNIQUE INDEX "TicketUsage_clientScanId_key" ON "TicketUsage"("clientScanId");
-- AddForeignKey
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_sectionId_fkey" FOREIGN KEY ("sectionId") REFERENCES "Section"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ScanLock" ADD CONSTRAINT "ScanLock_forceReleasedById_fkey" FOREIGN KEY ("forceReleasedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_scanLockId_fkey" FOREIGN KEY ("scanLockId") REFERENCES "ScanLock"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "OfflineSyncReport" ADD CONSTRAINT "OfflineSyncReport_reviewedById_fkey" FOREIGN KEY ("reviewedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,36 @@
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'ticket_transferred';
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "allowTicketTransfer" BOOLEAN NOT NULL DEFAULT true;
-- CreateTable
CREATE TABLE "TicketTransfer" (
"id" TEXT NOT NULL,
"ticketId" TEXT NOT NULL,
"fromHolderName" TEXT NOT NULL,
"fromUserId" TEXT,
"toName" TEXT NOT NULL,
"toUserId" TEXT,
"byUserId" TEXT,
"oldQrCode" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TicketTransfer_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "TicketTransfer_ticketId_idx" ON "TicketTransfer"("ticketId");
-- CreateIndex
CREATE INDEX "TicketTransfer_oldQrCode_idx" ON "TicketTransfer"("oldQrCode");
-- AddForeignKey
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_toUserId_fkey" FOREIGN KEY ("toUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TicketTransfer" ADD CONSTRAINT "TicketTransfer_byUserId_fkey" FOREIGN KEY ("byUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,78 @@
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "collectGender" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "AllocationSet" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"showOnTicket" BOOLEAN NOT NULL DEFAULT false,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AllocationSet_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AllocationGroup" (
"id" TEXT NOT NULL,
"setId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"capacity" INTEGER,
"gender" TEXT,
"leaderUserId" TEXT,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "AllocationGroup_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AllocationAssignment" (
"id" TEXT NOT NULL,
"setId" TEXT NOT NULL,
"groupId" TEXT NOT NULL,
"attendeeId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AllocationAssignment_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "AllocationSet_eventId_idx" ON "AllocationSet"("eventId");
-- CreateIndex
CREATE INDEX "AllocationGroup_setId_idx" ON "AllocationGroup"("setId");
-- CreateIndex
CREATE INDEX "AllocationGroup_leaderUserId_idx" ON "AllocationGroup"("leaderUserId");
-- CreateIndex
CREATE INDEX "AllocationAssignment_groupId_idx" ON "AllocationAssignment"("groupId");
-- CreateIndex
CREATE INDEX "AllocationAssignment_attendeeId_idx" ON "AllocationAssignment"("attendeeId");
-- CreateIndex
CREATE UNIQUE INDEX "AllocationAssignment_setId_attendeeId_key" ON "AllocationAssignment"("setId", "attendeeId");
-- AddForeignKey
ALTER TABLE "AllocationSet" ADD CONSTRAINT "AllocationSet_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AllocationGroup" ADD CONSTRAINT "AllocationGroup_setId_fkey" FOREIGN KEY ("setId") REFERENCES "AllocationSet"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AllocationGroup" ADD CONSTRAINT "AllocationGroup_leaderUserId_fkey" FOREIGN KEY ("leaderUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_setId_fkey" FOREIGN KEY ("setId") REFERENCES "AllocationSet"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "AllocationGroup"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AllocationAssignment" ADD CONSTRAINT "AllocationAssignment_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "Attendee"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,11 @@
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "allowSponsorships" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "showSponsorshipProgress" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "sponsorshipGoalSpots" INTEGER;
-- AlterTable
ALTER TABLE "Payment" ADD COLUMN "isSponsorship" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "sponsorAnonymous" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "sponsorMessage" TEXT,
ADD COLUMN "sponsorName" TEXT;
@@ -0,0 +1,122 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "FormFieldType" ADD VALUE 'rating';
ALTER TYPE "FormFieldType" ADD VALUE 'multiple_choice';
-- CreateTable
CREATE TABLE "FeedbackForm" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"sendAt" TIMESTAMP(3),
"audience" TEXT NOT NULL DEFAULT 'checked_in',
"anonymous" BOOLEAN NOT NULL DEFAULT false,
"intro" TEXT,
"sentAt" TIMESTAMP(3),
"reminderSentAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "FeedbackForm_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedbackField" (
"id" TEXT NOT NULL,
"formId" TEXT NOT NULL,
"type" "FormFieldType" NOT NULL,
"label" TEXT NOT NULL,
"isRequired" BOOLEAN NOT NULL DEFAULT false,
"order" INTEGER NOT NULL DEFAULT 0,
"helpText" TEXT,
"options" JSONB,
CONSTRAINT "FeedbackField_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedbackInvite" (
"id" TEXT NOT NULL,
"formId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"tokenHash" TEXT NOT NULL,
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"remindedAt" TIMESTAMP(3),
"respondedAt" TIMESTAMP(3),
CONSTRAINT "FeedbackInvite_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedbackResponse" (
"id" TEXT NOT NULL,
"formId" TEXT NOT NULL,
"userId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "FeedbackResponse_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "FeedbackAnswer" (
"id" TEXT NOT NULL,
"responseId" TEXT NOT NULL,
"fieldId" TEXT NOT NULL,
"value" TEXT NOT NULL,
CONSTRAINT "FeedbackAnswer_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "FeedbackForm_eventId_key" ON "FeedbackForm"("eventId");
-- CreateIndex
CREATE INDEX "FeedbackField_formId_idx" ON "FeedbackField"("formId");
-- CreateIndex
CREATE UNIQUE INDEX "FeedbackInvite_tokenHash_key" ON "FeedbackInvite"("tokenHash");
-- CreateIndex
CREATE INDEX "FeedbackInvite_userId_idx" ON "FeedbackInvite"("userId");
-- CreateIndex
CREATE UNIQUE INDEX "FeedbackInvite_formId_userId_key" ON "FeedbackInvite"("formId", "userId");
-- CreateIndex
CREATE INDEX "FeedbackResponse_formId_idx" ON "FeedbackResponse"("formId");
-- CreateIndex
CREATE INDEX "FeedbackAnswer_responseId_idx" ON "FeedbackAnswer"("responseId");
-- CreateIndex
CREATE INDEX "FeedbackAnswer_fieldId_idx" ON "FeedbackAnswer"("fieldId");
-- AddForeignKey
ALTER TABLE "FeedbackForm" ADD CONSTRAINT "FeedbackForm_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackField" ADD CONSTRAINT "FeedbackField_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackInvite" ADD CONSTRAINT "FeedbackInvite_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackInvite" ADD CONSTRAINT "FeedbackInvite_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_formId_fkey" FOREIGN KEY ("formId") REFERENCES "FeedbackForm"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackResponse" ADD CONSTRAINT "FeedbackResponse_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackAnswer" ADD CONSTRAINT "FeedbackAnswer_responseId_fkey" FOREIGN KEY ("responseId") REFERENCES "FeedbackResponse"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "FeedbackAnswer" ADD CONSTRAINT "FeedbackAnswer_fieldId_fkey" FOREIGN KEY ("fieldId") REFERENCES "FeedbackField"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,47 @@
-- AlterTable
ALTER TABLE "Registration" ADD COLUMN "analyticsSessionId" TEXT;
-- CreateTable
CREATE TABLE "AnalyticsEvent" (
"id" TEXT NOT NULL,
"sessionId" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"stage" TEXT NOT NULL,
"source" TEXT,
"device" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AnalyticsEvent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "AnalyticsDaily" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"day" DATE NOT NULL,
"stage" TEXT NOT NULL,
"source" TEXT NOT NULL DEFAULT 'direct',
"device" TEXT NOT NULL DEFAULT 'unknown',
"sessions" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "AnalyticsDaily_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "AnalyticsEvent_eventId_createdAt_idx" ON "AnalyticsEvent"("eventId", "createdAt");
-- CreateIndex
CREATE UNIQUE INDEX "AnalyticsEvent_sessionId_eventId_stage_key" ON "AnalyticsEvent"("sessionId", "eventId", "stage");
-- CreateIndex
CREATE INDEX "AnalyticsDaily_eventId_day_idx" ON "AnalyticsDaily"("eventId", "day");
-- CreateIndex
CREATE UNIQUE INDEX "AnalyticsDaily_eventId_day_stage_source_device_key" ON "AnalyticsDaily"("eventId", "day", "stage", "source", "device");
-- AddForeignKey
ALTER TABLE "AnalyticsEvent" ADD CONSTRAINT "AnalyticsEvent_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "AnalyticsDaily" ADD CONSTRAINT "AnalyticsDaily_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,55 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'impersonation_started';
ALTER TYPE "AdminAuditAction" ADD VALUE 'impersonation_ended';
-- CreateTable
CREATE TABLE "ImpersonationSession" (
"id" TEXT NOT NULL,
"adminId" TEXT NOT NULL,
"targetUserId" TEXT NOT NULL,
"reason" TEXT NOT NULL,
"startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
"endedAt" TIMESTAMP(3),
"endedReason" TEXT,
CONSTRAINT "ImpersonationSession_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "ImpersonationRequestLog" (
"id" TEXT NOT NULL,
"sessionId" TEXT NOT NULL,
"method" TEXT NOT NULL,
"path" TEXT NOT NULL,
"blocked" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "ImpersonationRequestLog_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ImpersonationSession_adminId_idx" ON "ImpersonationSession"("adminId");
-- CreateIndex
CREATE INDEX "ImpersonationSession_targetUserId_idx" ON "ImpersonationSession"("targetUserId");
-- CreateIndex
CREATE INDEX "ImpersonationRequestLog_sessionId_createdAt_idx" ON "ImpersonationRequestLog"("sessionId", "createdAt");
-- AddForeignKey
ALTER TABLE "ImpersonationSession" ADD CONSTRAINT "ImpersonationSession_adminId_fkey" FOREIGN KEY ("adminId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ImpersonationSession" ADD CONSTRAINT "ImpersonationSession_targetUserId_fkey" FOREIGN KEY ("targetUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "ImpersonationRequestLog" ADD CONSTRAINT "ImpersonationRequestLog_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "ImpersonationSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,30 @@
-- CreateTable
CREATE TABLE "TicketTransferRequest" (
"id" TEXT NOT NULL,
"ticketId" TEXT NOT NULL,
"requestedById" TEXT NOT NULL,
"toName" TEXT NOT NULL,
"toEmail" TEXT,
"toPhone" TEXT,
"details" JSONB,
"tokenHash" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"expiresAt" TIMESTAMP(3) NOT NULL,
"respondedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TicketTransferRequest_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "TicketTransferRequest_tokenHash_key" ON "TicketTransferRequest"("tokenHash");
-- CreateIndex
CREATE INDEX "TicketTransferRequest_ticketId_status_idx" ON "TicketTransferRequest"("ticketId", "status");
-- AddForeignKey
ALTER TABLE "TicketTransferRequest" ADD CONSTRAINT "TicketTransferRequest_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "TicketTransferRequest" ADD CONSTRAINT "TicketTransferRequest_requestedById_fkey" FOREIGN KEY ("requestedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,12 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_config_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_webhook_registered';
ALTER TYPE "AdminAuditAction" ADD VALUE 'yoco_webhook_deleted';
@@ -0,0 +1,53 @@
-- CreateEnum
CREATE TYPE "CashupWriteOffCategory" AS ENUM ('card_fees', 'bank_charges', 'cash_shortfall', 'other');
-- AlterTable
ALTER TABLE "EventCashupLine" ADD COLUMN "bankAmount" DOUBLE PRECISION,
ADD COLUMN "onHandAmount" DOUBLE PRECISION,
ADD COLUMN "pendingAmount" DOUBLE PRECISION,
ADD COLUMN "pendingReference" TEXT,
ADD COLUMN "writeOffTotal" DOUBLE PRECISION NOT NULL DEFAULT 0;
-- CreateTable
CREATE TABLE "EventCashupWriteOff" (
"id" TEXT NOT NULL,
"lineId" TEXT NOT NULL,
"category" "CashupWriteOffCategory" NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"reason" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventCashupWriteOff_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventCashupPendingResolution" (
"id" TEXT NOT NULL,
"lineId" TEXT NOT NULL,
"outcome" TEXT NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"category" "CashupWriteOffCategory",
"notes" TEXT,
"performedById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "EventCashupPendingResolution_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventCashupWriteOff_lineId_idx" ON "EventCashupWriteOff"("lineId");
-- CreateIndex
CREATE INDEX "EventCashupPendingResolution_lineId_idx" ON "EventCashupPendingResolution"("lineId");
-- CreateIndex
CREATE INDEX "EventCashupPendingResolution_performedById_idx" ON "EventCashupPendingResolution"("performedById");
-- AddForeignKey
ALTER TABLE "EventCashupWriteOff" ADD CONSTRAINT "EventCashupWriteOff_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_lineId_fkey" FOREIGN KEY ("lineId") REFERENCES "EventCashupLine"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventCashupPendingResolution" ADD CONSTRAINT "EventCashupPendingResolution_performedById_fkey" FOREIGN KEY ("performedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,83 @@
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_created';
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'bundle_deleted';
-- AlterTable
ALTER TABLE "Registration" ADD COLUMN "bundleDiscount" DOUBLE PRECISION NOT NULL DEFAULT 0;
-- CreateTable
CREATE TABLE "EventBundle" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT,
"price" DOUBLE PRECISION NOT NULL,
"isActive" BOOLEAN NOT NULL DEFAULT true,
"validFrom" TIMESTAMP(3),
"validUntil" TIMESTAMP(3),
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EventBundle_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "EventBundleItem" (
"id" TEXT NOT NULL,
"bundleId" TEXT NOT NULL,
"eventOptionId" TEXT NOT NULL,
"variantId" TEXT,
"quantity" INTEGER NOT NULL,
CONSTRAINT "EventBundleItem_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "RegistrationBundle" (
"id" TEXT NOT NULL,
"registrationId" TEXT NOT NULL,
"bundleId" TEXT NOT NULL,
"count" INTEGER NOT NULL,
"discount" DOUBLE PRECISION NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "RegistrationBundle_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventBundle_eventId_idx" ON "EventBundle"("eventId");
-- CreateIndex
CREATE INDEX "EventBundleItem_bundleId_idx" ON "EventBundleItem"("bundleId");
-- CreateIndex
CREATE INDEX "EventBundleItem_eventOptionId_idx" ON "EventBundleItem"("eventOptionId");
-- CreateIndex
CREATE INDEX "EventBundleItem_variantId_idx" ON "EventBundleItem"("variantId");
-- CreateIndex
CREATE INDEX "RegistrationBundle_registrationId_idx" ON "RegistrationBundle"("registrationId");
-- CreateIndex
CREATE INDEX "RegistrationBundle_bundleId_idx" ON "RegistrationBundle"("bundleId");
-- AddForeignKey
ALTER TABLE "EventBundle" ADD CONSTRAINT "EventBundle_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_bundleId_fkey" FOREIGN KEY ("bundleId") REFERENCES "EventBundle"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_eventOptionId_fkey" FOREIGN KEY ("eventOptionId") REFERENCES "EventOption"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventBundleItem" ADD CONSTRAINT "EventBundleItem_variantId_fkey" FOREIGN KEY ("variantId") REFERENCES "OptionVariant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "RegistrationBundle" ADD CONSTRAINT "RegistrationBundle_registrationId_fkey" FOREIGN KEY ("registrationId") REFERENCES "Registration"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "RegistrationBundle" ADD CONSTRAINT "RegistrationBundle_bundleId_fkey" FOREIGN KEY ("bundleId") REFERENCES "EventBundle"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,12 @@
-- CreateEnum
CREATE TYPE "BundleKind" AS ENUM ('exact', 'mix', 'free', 'group');
-- CreateEnum
CREATE TYPE "BundleGroupPricing" AS ENUM ('per_ticket', 'percent');
-- AlterTable
ALTER TABLE "EventBundle" ADD COLUMN "freeCount" INTEGER,
ADD COLUMN "groupPricing" "BundleGroupPricing",
ADD COLUMN "kind" "BundleKind" NOT NULL DEFAULT 'exact',
ADD COLUMN "setSize" INTEGER;
@@ -0,0 +1,132 @@
-- CreateEnum
CREATE TYPE "ScheduleType" AS ENUM ('single', 'sessions');
-- CreateEnum
CREATE TYPE "AttendanceMode" AS ENUM ('whole', 'pick');
-- CreateEnum
CREATE TYPE "LatePricing" AS ENUM ('full', 'prorata', 'fixed');
-- CreateEnum
CREATE TYPE "CheckInWindow" AS ENUM ('whole_day', 'session_only');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'event_sessions_changed';
ALTER TYPE "AdminAuditAction" ADD VALUE 'attendance_marked';
ALTER TYPE "AdminAuditAction" ADD VALUE 'attendance_unmarked';
ALTER TYPE "AdminAuditAction" ADD VALUE 'certificate_issued';
ALTER TYPE "AdminAuditAction" ADD VALUE 'certificate_revoked';
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "attendanceMode" "AttendanceMode" NOT NULL DEFAULT 'whole',
ADD COLUMN "certificateConfig" JSONB,
ADD COLUMN "certificatesEnabled" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "checkInWindow" "CheckInWindow" NOT NULL DEFAULT 'whole_day',
ADD COLUMN "lateFixedPrice" DOUBLE PRECISION,
ADD COLUMN "lateJoinEnabled" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "lateJoinUntilSessionId" TEXT,
ADD COLUMN "latePricing" "LatePricing" NOT NULL DEFAULT 'full',
ADD COLUMN "scheduleType" "ScheduleType" NOT NULL DEFAULT 'single',
ADD COLUMN "sessionReminders" JSONB;
-- AlterTable
ALTER TABLE "TicketUsage" ADD COLUMN "manual" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "sessionId" TEXT;
-- CreateTable
CREATE TABLE "EventSession" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"label" TEXT,
"startsAt" TIMESTAMP(3) NOT NULL,
"endsAt" TIMESTAMP(3) NOT NULL,
"location" TEXT,
"cancelledAt" TIMESTAMP(3),
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "EventSession_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "SessionReminderLog" (
"id" TEXT NOT NULL,
"sessionId" TEXT NOT NULL,
"offset" INTEGER NOT NULL,
"sent" INTEGER NOT NULL DEFAULT 0,
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "SessionReminderLog_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Certificate" (
"id" TEXT NOT NULL,
"eventId" TEXT NOT NULL,
"ticketId" TEXT NOT NULL,
"userId" TEXT,
"name" TEXT NOT NULL,
"code" TEXT NOT NULL,
"sessionsAttended" INTEGER NOT NULL DEFAULT 0,
"totalSessions" INTEGER NOT NULL DEFAULT 0,
"manual" BOOLEAN NOT NULL DEFAULT false,
"issuedById" TEXT,
"issuedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"emailedAt" TIMESTAMP(3),
"revokedAt" TIMESTAMP(3),
CONSTRAINT "Certificate_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "EventSession_eventId_startsAt_idx" ON "EventSession"("eventId", "startsAt");
-- CreateIndex
CREATE UNIQUE INDEX "SessionReminderLog_sessionId_offset_key" ON "SessionReminderLog"("sessionId", "offset");
-- CreateIndex
CREATE UNIQUE INDEX "Certificate_code_key" ON "Certificate"("code");
-- CreateIndex
CREATE INDEX "Certificate_userId_idx" ON "Certificate"("userId");
-- CreateIndex
CREATE INDEX "Certificate_ticketId_idx" ON "Certificate"("ticketId");
-- CreateIndex
CREATE INDEX "Certificate_issuedById_idx" ON "Certificate"("issuedById");
-- CreateIndex
CREATE UNIQUE INDEX "Certificate_eventId_ticketId_key" ON "Certificate"("eventId", "ticketId");
-- CreateIndex
CREATE INDEX "TicketUsage_sessionId_idx" ON "TicketUsage"("sessionId");
-- AddForeignKey
ALTER TABLE "TicketUsage" ADD CONSTRAINT "TicketUsage_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "EventSession" ADD CONSTRAINT "EventSession_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "SessionReminderLog" ADD CONSTRAINT "SessionReminderLog_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_eventId_fkey" FOREIGN KEY ("eventId") REFERENCES "Event"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_ticketId_fkey" FOREIGN KEY ("ticketId") REFERENCES "Ticket"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Certificate" ADD CONSTRAINT "Certificate_issuedById_fkey" FOREIGN KEY ("issuedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,17 @@
-- CreateEnum
CREATE TYPE "OptionSessionMode" AS ENUM ('all', 'pick');
-- AlterTable
ALTER TABLE "EventOption" ADD COLUMN "sessionMode" "OptionSessionMode" NOT NULL DEFAULT 'all';
-- AlterTable
ALTER TABLE "EventSession" ADD COLUMN "capacity" INTEGER;
-- AlterTable
ALTER TABLE "RegistrationOption" ADD COLUMN "sessionId" TEXT;
-- CreateIndex
CREATE INDEX "RegistrationOption_sessionId_idx" ON "RegistrationOption"("sessionId");
-- AddForeignKey
ALTER TABLE "RegistrationOption" ADD CONSTRAINT "RegistrationOption_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'job_run_manual';
@@ -0,0 +1,8 @@
-- AlterTable
ALTER TABLE "WaitlistEntry" ADD COLUMN "sessionId" TEXT;
-- CreateIndex
CREATE INDEX "WaitlistEntry_sessionId_idx" ON "WaitlistEntry"("sessionId");
-- AddForeignKey
ALTER TABLE "WaitlistEntry" ADD CONSTRAINT "WaitlistEntry_sessionId_fkey" FOREIGN KEY ("sessionId") REFERENCES "EventSession"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "RegistrationOption" ADD COLUMN "sessionIds" TEXT[] DEFAULT ARRAY[]::TEXT[];
@@ -0,0 +1,23 @@
-- Payment providers (1.36.0). YocoTransaction becomes ProviderTransaction: renamed in place
-- so every stored transaction is kept (Prisma's generated plan drops and recreates it).
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'payment_providers_updated';
-- Rename YocoTransaction → ProviderTransaction
ALTER TABLE "YocoTransaction" RENAME TO "ProviderTransaction";
ALTER TABLE "ProviderTransaction" RENAME CONSTRAINT "YocoTransaction_pkey" TO "ProviderTransaction_pkey";
ALTER TABLE "ProviderTransaction" RENAME CONSTRAINT "YocoTransaction_paymentId_fkey" TO "ProviderTransaction_paymentId_fkey";
ALTER INDEX "YocoTransaction_paymentId_idx" RENAME TO "ProviderTransaction_paymentId_idx";
-- Which provider sent it; external ids are unique per provider
ALTER TABLE "ProviderTransaction" ADD COLUMN "provider" TEXT NOT NULL DEFAULT 'yoco';
DROP INDEX "YocoTransaction_externalId_key";
CREATE UNIQUE INDEX "ProviderTransaction_provider_externalId_key" ON "ProviderTransaction"("provider", "externalId");
-- Payment.provider: every online payment so far came through Yoco (linked to a transaction,
-- or the donation split off one)
ALTER TABLE "Payment" ADD COLUMN "provider" TEXT;
UPDATE "Payment" SET "provider" = 'yoco'
WHERE "id" IN (SELECT "paymentId" FROM "ProviderTransaction" WHERE "paymentId" IS NOT NULL)
OR "originalPaymentId" IN (SELECT "paymentId" FROM "ProviderTransaction" WHERE "paymentId" IS NOT NULL);
@@ -0,0 +1,24 @@
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'payfast_config_updated';
-- AlterTable
ALTER TABLE "ProviderTransaction" ADD COLUMN "note" TEXT;
-- CreateTable
CREATE TABLE "ProviderCheckout" (
"id" TEXT NOT NULL,
"provider" TEXT,
"externalId" TEXT,
"redirectUrl" TEXT,
"amountCents" INTEGER NOT NULL,
"currency" TEXT NOT NULL DEFAULT 'ZAR',
"metadata" JSONB NOT NULL,
"request" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "ProviderCheckout_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "ProviderCheckout_provider_externalId_idx" ON "ProviderCheckout"("provider", "externalId");
@@ -0,0 +1,102 @@
-- CreateEnum
CREATE TYPE "DataRequestType" AS ENUM ('access', 'correction', 'deletion');
-- CreateEnum
CREATE TYPE "DataRequestStatus" AS ENUM ('open', 'completed', 'rejected', 'cancelled');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'data_request_completed';
ALTER TYPE "AdminAuditAction" ADD VALUE 'data_request_rejected';
ALTER TYPE "AdminAuditAction" ADD VALUE 'user_anonymised';
-- AlterTable
ALTER TABLE "User" ADD COLUMN "newsAskedAt" TIMESTAMP(3),
ADD COLUMN "newsEmail" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "newsWhatsApp" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "CommunicationConsent" (
"id" TEXT NOT NULL,
"userId" TEXT,
"address" TEXT,
"channel" TEXT NOT NULL,
"granted" BOOLEAN NOT NULL,
"source" TEXT NOT NULL,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "CommunicationConsent_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "MessagingOptOut" (
"id" TEXT NOT NULL,
"channel" TEXT NOT NULL,
"address" TEXT NOT NULL,
"source" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "MessagingOptOut_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DataRequest" (
"id" TEXT NOT NULL,
"type" "DataRequestType" NOT NULL,
"status" "DataRequestStatus" NOT NULL DEFAULT 'open',
"userId" TEXT,
"name" TEXT NOT NULL,
"email" TEXT NOT NULL,
"details" TEXT,
"response" TEXT,
"selfService" BOOLEAN NOT NULL DEFAULT false,
"dueAt" TIMESTAMP(3) NOT NULL,
"closedAt" TIMESTAMP(3),
"handledById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "DataRequest_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "CommunicationConsent_userId_createdAt_idx" ON "CommunicationConsent"("userId", "createdAt");
-- CreateIndex
CREATE INDEX "CommunicationConsent_address_idx" ON "CommunicationConsent"("address");
-- CreateIndex
CREATE UNIQUE INDEX "MessagingOptOut_channel_address_key" ON "MessagingOptOut"("channel", "address");
-- CreateIndex
CREATE INDEX "DataRequest_status_dueAt_idx" ON "DataRequest"("status", "dueAt");
-- CreateIndex
CREATE INDEX "DataRequest_userId_idx" ON "DataRequest"("userId");
-- AddForeignKey
ALTER TABLE "CommunicationConsent" ADD CONSTRAINT "CommunicationConsent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DataRequest" ADD CONSTRAINT "DataRequest_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DataRequest" ADD CONSTRAINT "DataRequest_handledById_fkey" FOREIGN KEY ("handledById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- Existing accounts: kept opted in to news (WhatsApp only when they have a phone number),
-- logged as "existing_account", and asked once at their next login (newsAskedAt stays null).
UPDATE "User" SET "newsEmail" = true, "newsWhatsApp" = ("phoneNumber" IS NOT NULL)
WHERE "isActive" = true AND "email" NOT LIKE '%@deleted.invalid' AND "email" NOT LIKE '%@deleted.local' AND "email" NOT LIKE '%@guest.local';
INSERT INTO "CommunicationConsent" ("id", "userId", "channel", "granted", "source")
SELECT gen_random_uuid()::text, "id", 'email', true, 'existing_account' FROM "User" WHERE "newsEmail" = true;
INSERT INTO "CommunicationConsent" ("id", "userId", "channel", "granted", "source")
SELECT gen_random_uuid()::text, "id", 'whatsapp', true, 'existing_account' FROM "User" WHERE "newsWhatsApp" = true;
@@ -0,0 +1,110 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'privacy_notice_published';
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_created';
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'operator_deleted';
-- AlterTable
ALTER TABLE "User" ADD COLUMN "noticeVersionAccepted" INTEGER;
-- CreateTable
CREATE TABLE "PrivacyNotice" (
"id" TEXT NOT NULL,
"version" INTEGER NOT NULL,
"sections" JSONB NOT NULL,
"changeSummary" TEXT,
"requiresAcceptance" BOOLEAN NOT NULL DEFAULT false,
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"publishedById" TEXT,
CONSTRAINT "PrivacyNotice_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "NoticeAcceptance" (
"id" TEXT NOT NULL,
"userId" TEXT,
"version" INTEGER NOT NULL,
"source" TEXT NOT NULL,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "NoticeAcceptance_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Operator" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"purpose" TEXT NOT NULL,
"dataShared" TEXT NOT NULL,
"location" TEXT,
"website" TEXT,
"active" BOOLEAN NOT NULL DEFAULT true,
"order" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Operator_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DataAccessLog" (
"id" TEXT NOT NULL,
"actorId" TEXT,
"actorRole" TEXT NOT NULL,
"action" TEXT NOT NULL,
"what" TEXT NOT NULL,
"eventId" TEXT,
"records" INTEGER,
"ip" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "DataAccessLog_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "PrivacyNotice_version_key" ON "PrivacyNotice"("version");
-- CreateIndex
CREATE INDEX "NoticeAcceptance_userId_createdAt_idx" ON "NoticeAcceptance"("userId", "createdAt");
-- CreateIndex
CREATE INDEX "NoticeAcceptance_version_idx" ON "NoticeAcceptance"("version");
-- CreateIndex
CREATE INDEX "DataAccessLog_createdAt_idx" ON "DataAccessLog"("createdAt");
-- CreateIndex
CREATE INDEX "DataAccessLog_actorId_createdAt_idx" ON "DataAccessLog"("actorId", "createdAt");
-- CreateIndex
CREATE INDEX "DataAccessLog_action_createdAt_idx" ON "DataAccessLog"("action", "createdAt");
-- AddForeignKey
ALTER TABLE "PrivacyNotice" ADD CONSTRAINT "PrivacyNotice_publishedById_fkey" FOREIGN KEY ("publishedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "NoticeAcceptance" ADD CONSTRAINT "NoticeAcceptance_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "DataAccessLog" ADD CONSTRAINT "DataAccessLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- The operator register starts with the services Hope Events itself uses. Admins correct the
-- details (e.g. which email and hosting provider) in Admin → Privacy → Operators.
INSERT INTO "Operator" ("id", "name", "purpose", "dataShared", "location", "website", "active", "order", "updatedAt") VALUES
(gen_random_uuid()::text, 'Yoco', 'Card payments', 'Payment amount and reference; card details are entered on Yoco''s own page', 'South Africa', 'https://www.yoco.com', true, 1, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'PayFast', 'Online payments', 'Name, email address, payment amount and reference', 'South Africa', 'https://payfast.io', true, 2, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'WAWP', 'Delivering WhatsApp messages', 'Mobile number and message content', NULL, 'https://wawp.net', true, 3, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'WhatsApp (Meta Platforms)', 'The WhatsApp messaging service', 'Mobile number and message content', NULL, 'https://www.whatsapp.com/legal/privacy-policy', true, 4, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'Email delivery provider', 'Sending emails (the SMTP server in Site settings)', 'Name, email address and message content', NULL, NULL, true, 5, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'Hosting provider', 'The servers this site and its database run on', 'All information held by the site', 'South Africa', NULL, true, 6, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'Google Maps', 'Maps on event pages', 'Your device''s IP address and browser details when a map loads', NULL, 'https://policies.google.com/privacy', true, 7, CURRENT_TIMESTAMP),
(gen_random_uuid()::text, 'Sentry', 'Error monitoring (only when it is set up)', 'Technical error reports, which can include the signed-in user''s id', NULL, 'https://sentry.io', false, 8, CURRENT_TIMESTAMP);
@@ -0,0 +1,57 @@
-- CreateEnum
CREATE TYPE "BreachStatus" AS ENUM ('open', 'contained', 'closed');
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_policies_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'retention_run';
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_recorded';
ALTER TYPE "AdminAuditAction" ADD VALUE 'breach_updated';
-- AlterTable
ALTER TABLE "DataAccessLog" ADD COLUMN "sensitive" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "inactivityWarnedAt" TIMESTAMP(3),
ADD COLUMN "lastLoginAt" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "SecurityBreach" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"status" "BreachStatus" NOT NULL DEFAULT 'open',
"discoveredAt" TIMESTAMP(3) NOT NULL,
"occurredAt" TIMESTAMP(3),
"description" TEXT NOT NULL,
"dataAffected" TEXT NOT NULL,
"peopleAffected" INTEGER,
"whoAffected" TEXT,
"consequences" TEXT,
"actionsTaken" TEXT,
"adviceToPeople" TEXT,
"causedBy" TEXT,
"regulatorNotifiedAt" TIMESTAMP(3),
"peopleNotifiedAt" TIMESTAMP(3),
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "SecurityBreach_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "SecurityBreach_status_discoveredAt_idx" ON "SecurityBreach"("status", "discoveredAt");
-- AddForeignKey
ALTER TABLE "SecurityBreach" ADD CONSTRAINT "SecurityBreach_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- Last login, from the login history (which the retention job will start expiring).
UPDATE "User" u SET "lastLoginAt" = l.at
FROM (SELECT "userId", MAX("createdAt") AS at FROM "SecurityEvent" WHERE "type" = 'login' AND "userId" IS NOT NULL GROUP BY "userId") l
WHERE u."id" = l."userId";
@@ -0,0 +1,3 @@
-- AlterEnum
ALTER TYPE "AdminAuditAction" ADD VALUE 'hub_connected';
@@ -0,0 +1,76 @@
-- AlterEnum
-- This migration adds more than one value to an enum.
-- With PostgreSQL versions 11 and earlier, this is not possible
-- in a single migration. This can be worked around by creating
-- multiple migrations, each migration adding only one value to
-- the enum.
ALTER TYPE "AdminAuditAction" ADD VALUE 'hub_update_requested';
ALTER TYPE "AdminAuditAction" ADD VALUE 'campuses_toggled';
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_created';
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_updated';
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_archived';
ALTER TYPE "AdminAuditAction" ADD VALUE 'campus_deleted';
ALTER TYPE "AdminAuditAction" ADD VALUE 'event_campus_changed';
-- AlterTable
ALTER TABLE "Event" ADD COLUMN "campusId" TEXT;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "homeCampusId" TEXT;
-- CreateTable
CREATE TABLE "Campus" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"address" TEXT,
"contactName" TEXT,
"contactEmail" TEXT,
"contactPhone" TEXT,
"colour" TEXT,
"logoUrl" TEXT,
"defaultLocation" TEXT,
"order" INTEGER NOT NULL DEFAULT 0,
"archivedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Campus_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "_CampusNotifyRecipients" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL,
CONSTRAINT "_CampusNotifyRecipients_AB_pkey" PRIMARY KEY ("A","B")
);
-- CreateIndex
CREATE UNIQUE INDEX "Campus_slug_key" ON "Campus"("slug");
-- CreateIndex
CREATE INDEX "Campus_order_idx" ON "Campus"("order");
-- CreateIndex
CREATE INDEX "_CampusNotifyRecipients_B_index" ON "_CampusNotifyRecipients"("B");
-- CreateIndex
CREATE INDEX "Event_campusId_idx" ON "Event"("campusId");
-- CreateIndex
CREATE INDEX "User_homeCampusId_idx" ON "User"("homeCampusId");
-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_homeCampusId_fkey" FOREIGN KEY ("homeCampusId") REFERENCES "Campus"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_campusId_fkey" FOREIGN KEY ("campusId") REFERENCES "Campus"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_CampusNotifyRecipients" ADD CONSTRAINT "_CampusNotifyRecipients_A_fkey" FOREIGN KEY ("A") REFERENCES "Campus"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "_CampusNotifyRecipients" ADD CONSTRAINT "_CampusNotifyRecipients_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

Some files were not shown because too many files have changed in this diff Show More