diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index b9cd8d0..6b7b9c1 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -7,6 +7,90 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.0.0] - 2026-11-02 + +### Added + +- **AI helpers — the plumbing** (2.0, roadmap §15). The site calls AI through the Cross Events Hub + (protocol §3b, Hub 1.6.0), which holds the Claude API key and a monthly allowance in rand per + licence; no key is ever stored on the site. `GET /api/v2/ai/status` says whether to show the AI + buttons: hidden when the licence has no AI (worked out from the licence token, without asking the + Hub), disabled with the reason once the month's allowance is used up or the Hub can't be reached. + The answer is cached for a minute and refreshed by every AI call. `` and + `useAiStatus()` on the frontend; only supervisors and admins see AI. +- **Site settings → AI** (admins): this month's use against the allowance, use per person, per + helper and per day, a switch per helper, and an optional most-uses-per-person-per-day. Admins are + emailed once a month when 80% is used. Changes are audited (`ai_settings_changed`). +- Each AI call is logged in `AiCall` (person, helper, outcome, cost — never the prompt or answer); + anonymising an account unlinks its calls, and calls go after 13 months. Anthropic is added to the + operator register, switched off until a site uses AI. Migration `20261030120000_ai_helpers`. +- v2 errors have a new code, `UNAVAILABLE` (503), for when the Hub or the AI service can't be + reached. +- **The five AI helpers' API** (supervisors and admins): `POST /api/v2/ai/draft-event` (the event + form from a description, with ticket options, early bird, schedule and a budget from the notes), + `/ai/summarise-report` (reports without people in them only), `/ai/draft-message` (email or + WhatsApp, with `{{name}}` and the event placeholders), `/ai/summarise-feedback` (an event's + feedback, sent without who answered; recorded in the access log) and `/ai/improve-text` + (improve, shorter, or only fix mistakes). Every helper is told today's date. Email addresses, + phone numbers and ID numbers in what's sent are swapped for placeholders and put back in the + answer, so they never leave the site. Two checks are worked out in code as well as by the AI: a + weekday that doesn't match its date, and costs a full event can't cover. +- **AI buttons in the app** (only where the licence has AI; supervisors and admins): + - New event → **Describe your event**: a few sentences fill in the form (details, dates, tickets, + early bird; course dates as sessions), with the checks and a budget from the notes to look at + first. Nothing changes until "Fill in the form". + - **Improve / Shorter / Fix mistakes** under the event description, the site banner, and the + email and WhatsApp message boxes; the suggestion replaces the text only with "Use this". + - **Draft with AI** in Email attendees and WhatsApp attendees: a short note becomes the email's + subject and body, or the WhatsApp message, with `{{name}}` and the event's details. + - **Summarise this report** on reports without people in them, and **Summarise feedback** per + event on the Feedback summary report. + - Every suggestion says "AI suggestion — check it before saving". +- **Privacy notice:** the built-in text says how the AI helpers use information and where requests + go (sections 4 and 9). Sites with their own published notice see the change in the notice + editor. +- `npm run ai:eval` (backend): the helpers' eval set — fixed examples run through the site's Hub + connection, with automatic checks on the facts and every answer printed to read. +- **MIGRATING-TO-2.md:** what changes for integrations and for whoever runs the server, with every + v1 address and its v2 replacement. + +### Removed + +- **API v1** (`/api/…`). Every screen has used `/api/v2` since 1.51.16. Any v1 address now answers + `410 Gone` with `code: "API_V1_REMOVED"`, except what outside senders still use: the provider + webhooks (`/api/webhooks/yoco|payfast|whatsapp` and WAWP's oldest `/api/whatsapp/webhook`) and + the links in messages already sent (calendar files and one-click unsubscribe answer `308` with + their v2 address; a mail app's one-click POST to the old address is still handled) — + `legacyV1Router` and `v1Removed` in `src/v2/links.ts`. The 43 v1 route files are gone (the + controllers stay: `v1Route` runs them behind v2 routes); so are the `Deprecation` headers + (`src/v2/deprecation.ts`), the v1 reference at `/docs` (it redirects to `/docs/v2`) and the + hand-written `backend/API_DOCUMENTATION.md` (now a pointer to `/docs/v2`). +- `node-fetch` from the backend's dependencies (nothing used it since the move to native `fetch`). + +### Changed + +- **Passwords are hashed with Argon2id** (`@node-rs/argon2`, 19 MiB, 2 passes) instead of bcrypt. + bcrypt hashes still sign in, and are re-hashed with Argon2id the first time each person signs in + (`needsRehash` in `src/config/auth.js`, used by `logIn`). `bcryptjs` stays only to check those. +- The campus-scope route test runs over the v2 routes (`tests/v2CampusScope.test.ts`): each staff + or supervisor route needs a campus-scope middleware or must be on the list of routes whose + service checks campuses itself. The read-only and impersonation lists name v2 paths only. +- e2e tests call `/api/v2` only (`v2()` in `e2e/fixtures.ts` returns the answer's `data`); + Playwright waits for `/api/v2/setup/needed`. +- Documented shapes corrected: the access log's `actions` (action → label) and a cash-up's + `cashDenominations` (notes and coins). +- **The React Compiler lint rules are errors again** (`set-state-in-effect`, `purity`, + `immutability`, `refs`, `static-components`); the 192 places they flagged are fixed, and + `npx eslint src` reports nothing. New hooks in `frontend/src/lib/hooks.ts`: `useStateSync` (state + that follows other state, set while rendering), `useExternalEffect` (loading from the API or + reading the browser), `useNow` (the time, refreshed each minute); `hardNavigate` in + `lib/navigation.ts` for the full reloads after signing out or switching who is signed in. Other + pages navigate with the router. Several resets moved into the handlers that cause them. +- Small behaviour fixes from that work: the site banner now appears and goes at its set times + without a reload; lists of past/upcoming events stay right on a page left open; registering + goes to the next page without a full reload; popups keep the latest close handler without + writing it during render. + ## [1.52.3] - 2026-11-02 ### Fixed diff --git a/apps/events/FEATURES.md b/apps/events/FEATURES.md index fe4b09f..e982985 100644 --- a/apps/events/FEATURES.md +++ b/apps/events/FEATURES.md @@ -903,8 +903,8 @@ can't start, the same jobs run on in-process timers. - **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 (`/`) and built-in API docs page (`/docs`); **API v2** (`/api/v2`, 1.51.0) - with one error shape, paged lists and an OpenAPI 3.1 reference at `/docs/v2` (admins). Public +- 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 diff --git a/apps/events/MIGRATING-TO-2.md b/apps/events/MIGRATING-TO-2.md new file mode 100644 index 0000000..39404ec --- /dev/null +++ b/apps/events/MIGRATING-TO-2.md @@ -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}` | diff --git a/apps/events/README.md b/apps/events/README.md index ef017f5..727d69c 100644 --- a/apps/events/README.md +++ b/apps/events/README.md @@ -20,7 +20,8 @@ The backend provides a RESTful API for managing users, events, registrations, pa - Static uploads for event images Documentation: see Backend API Documentation and Backend README for environment setup and endpoints. -- Backend API Documentation: ./backend/API_DOCUMENTATION.md +- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md +- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md - Backend README: ./backend/README.md ### Frontend @@ -155,7 +156,8 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use. ## Useful Links -- Backend API Documentation: ./backend/API_DOCUMENTATION.md +- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./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 @@ -163,6 +165,9 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use. ## 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** diff --git a/apps/events/SETTINGS.md b/apps/events/SETTINGS.md index f4771b2..e2f8693 100644 --- a/apps/events/SETTINGS.md +++ b/apps/events/SETTINGS.md @@ -60,7 +60,7 @@ or Branding tab has been saved even once — the wizard always writes ## Payments -Managed in the Payments tab (through `/api/payments/providers/settings` and `/api/yoco`, not the generic settings endpoints). +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 | |---|---|---| @@ -89,7 +89,7 @@ Managed in the Payments tab (through `/api/payments/providers/settings` and `/ap | Setting | Default when unset | Notes | |---|---|---| -| `campuses_enabled` | `false` | Site settings → Campuses → "Use campuses". Changed only through `PUT /api/campuses/settings` (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. | +| `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) @@ -106,7 +106,7 @@ Managed in the Payments tab (through `/api/payments/providers/settings` and `/ap | 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/whatsapp/webhook?secret=…`). 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`. | +| `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) diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index 3089939..5b2ac86 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,25 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 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 diff --git a/apps/events/backend/API_DOCUMENTATION.md b/apps/events/backend/API_DOCUMENTATION.md index fcf061c..1d077f9 100644 --- a/apps/events/backend/API_DOCUMENTATION.md +++ b/apps/events/backend/API_DOCUMENTATION.md @@ -1,1172 +1,16 @@ # Cross Events — API Documentation -Full interactive docs (with request/response examples) are available at `GET /docs?token=` on the running backend. +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: -> **API v2 (1.51.0 on):** `/api/v2` is described by OpenAPI 3.1. The reference is at `/docs/v2` -> (admin token), the document at `GET /api/v2/openapi.json` (admin). It is generated from the route -> declarations, so it is not repeated here. v2 responses are `{ data }` (lists add -> `meta: { page, limit, total, pages }`, `?page=&limit=` up to 100) and errors -> `{ error: { code, message, fields? } }`. This file documents v1 (`/api/…`). v1 endpoints that have a v2 replacement send `Deprecation` and -> `Link: ; rel="successor-version"` headers (1.51.3). The frontend calls v2 through the typed -> `apiV2()` helper (`frontend/src/lib/apiV2.ts`, types regenerated with `npm run api:types`). +- **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). -All authenticated requests require: -``` -Authorization: Bearer -``` +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 ` (`POST /api/v2/auth/login`). -Tokens are issued by `POST /api/users/login`. - ---- - -## Table of Contents - -- [Users](#users) -- [Events](#events) -- [Event Options & Variants](#event-options--variants) -- [Event Attachments](#event-attachments) -- [Registrations](#registrations) -- [Privacy (POPIA)](#privacy-popia) -- [Coupons](#coupons) -- [Parental consent](#parental-consent) -- [Waitlist](#waitlist) -- [Multi-day events & attendance](#multi-day-events--attendance) -- [Offline scanning](#offline-scanning) -- [Ticket transfer](#ticket-transfer) -- [Rooms & groups](#rooms--groups) -- [Sponsor a spot](#sponsor-a-spot) -- [Post-event feedback](#post-event-feedback) -- [Registration funnel](#registration-funnel) -- [Impersonation](#impersonation) -- [Background jobs](#background-jobs) -- [Payments](#payments) -- [Tickets](#tickets) -- [Broadcasts (Email)](#broadcasts-email) -- [WhatsApp Broadcasts](#whatsapp-broadcasts) -- [Scheduled Messages](#scheduled-messages) -- [Automations](#automations) -- [Reports](#reports) -- [Uploads](#uploads) -- [Sections](#sections) -- [Banner](#banner) -- [Forms](#forms) -- [Provider Transactions](#provider-transactions) -- [WhatsApp Admin](#whatsapp-admin) -- [Hub and licence](#hub-and-licence) -- [Webhooks](#webhooks) -- [Settings](#settings) -- [Setup](#setup) -- [Static Files](#static-files) - ---- - -## Users - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/users` | public | Register new account | -| POST | `/api/users/login` | public | Login, returns JWT — or a two-factor challenge when the account has 2FA on | -| POST | `/api/users/login/2fa` | public | Exchange a two-factor code for the JWT | -| POST | `/api/users/login/2fa/resend` | public | Send a new code for a pending login challenge (60s cooldown) | -| POST | `/api/users/forgot` | public | Request password reset email | -| POST | `/api/users/reset` | public | Reset password with token | -| POST | `/api/users/activate` | public | Activate account from email link | -| GET | `/api/users/profile` | user+ | Own profile | -| PUT | `/api/users/profile` | user+ | Update own profile | -| POST | `/api/users/revoke-sessions` | user+ | Revoke own sessions | -| POST | `/api/users/close-account` | user+ | Deactivate own account | -| POST | `/api/users/2fa/enable` | user+ | Start turning on 2FA — sends a code to the chosen channel | -| POST | `/api/users/2fa/confirm` | user+ | Finish turning on 2FA with that code | -| POST | `/api/users/2fa/disable` | user+ | Turn off 2FA (requires password) | -| POST | `/api/users/verify-password` | user+ | Re-confirm own password without starting a new session | -| GET | `/api/users` | supervisor+ | List users — supports `?search=`, `?role=`, `?isActive=true\|false`, `?page=`, `?limit=` | -| GET | `/api/users/:id` | admin | Get user by ID | -| PUT | `/api/users/:id` | admin | Update user (name, email, role, isActive, phoneNumber). `twoFactorEnabled: false` resets a user's 2FA; it cannot be switched on this way | -| DELETE | `/api/users/:id` | admin | Deactivate user (`isActive: false`) | -| POST | `/api/users/:id/revoke-sessions` | admin | Revoke all sessions for a user | -| POST | `/api/users/:id/anonymize` | admin | Erase personal data — sets name to "Deleted User", clears email/phone, deactivates account | - -### POST /api/users -```json -{ - "name": "Jane Smith", - "email": "jane@example.com", - "password": "securepass123", - "phoneNumber": "+27821234567" -} -``` -Returns: `{ _id, name, email, role, token }` - -### POST /api/users/login -```json -{ "email": "jane@example.com", "password": "securepass123", "deviceToken": "optional-trusted-device-token" } -``` -Returns: `{ _id, name, email, role, token }` - -If the account has two-factor authentication on and `deviceToken` is missing, expired or not recognised, no token is issued. A 6-digit code is sent by email or WhatsApp and the response is instead: -```json -{ "twoFactorRequired": true, "challengeId": "uuid", "method": "email", "destination": "j•••@example.com" } -``` - -**Required for admins and supervisors.** An admin or supervisor without 2FA gets the same challenge with `"enrolling": true` (trusted devices don't skip it), sent to their email when SMTP is configured, otherwise WhatsApp. Verifying it turns 2FA on with that channel. If neither channel can deliver a code, the requirement is skipped so the account isn't locked out. `TWO_FACTOR_REQUIRED_ROLES=false` turns the requirement off. - -### POST /api/users/login/2fa -```json -{ "challengeId": "uuid", "code": "123456", "rememberDevice": true } -``` -Returns: `{ _id, name, email, role, token }`, plus `deviceToken` when `rememberDevice` is `true`. Send that `deviceToken` with later logins to skip the code for 30 days. Codes expire after 10 minutes and allow 5 attempts. Trusted devices are cleared when the password changes or sessions are revoked. - -### Two-factor setup (`/api/users/2fa/*`) -- `POST /api/users/2fa/enable` — `{ "method": "email" | "whatsapp", "password": "..." }` sends a code to that channel and returns `{ challengeId, method, destination }`. WhatsApp needs a valid phone number on the account and a connected WhatsApp session. -- `POST /api/users/2fa/confirm` — `{ "challengeId": "uuid", "code": "123456" }` turns 2FA on. -- `POST /api/users/2fa/disable` — `{ "password": "..." }` turns it off. Returns 403 for admins and supervisors, who must keep it on (they can switch channel with `enable`/`confirm`). - -An admin or supervisor session without 2FA (from before the requirement, or after a promotion or 2FA reset) is rejected by every protected route with `401 { "code": "TWO_FACTOR_REQUIRED" }`; logging in again enrols them. Promoting a user to supervisor/admin ends their sessions when they don't have 2FA yet. - -At login, if a WhatsApp code can't be sent, the code falls back to the account's email address. - -### PUT /api/users/profile -```json -{ "name": "Jane Doe", "phoneNumber": "+27829999999", "notificationPreference": "email" } -``` -`notificationPreference`: `"email"` | `"whatsapp"` | `"both"` - ---- - -## Events - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/events` | public | Active, public, upcoming events. Includes `isSoldOut: boolean` per event. | -| GET | `/api/events/all` | staff+ | All events including hidden/past (`?includePast=true`, `?includeInactive=true`) | -| GET | `/api/events/admin/all` | admin | Admin view of all events | -| GET | `/api/events/:id` | public | Full event detail — options, variants, earlyBirdTiers, attachments, form, availableCount per option/variant | -| GET | `/api/events/by-alias/:redirectUrl` | public | Get event by URL alias | -| POST | `/api/events` | supervisor+ | Create event | -| PUT | `/api/events/:id` | supervisor+ | Update event | -| POST | `/api/events/:id/copy-from` | supervisor+ | Copying an event: copy `fromEventId`'s allocation sets/groups (not kids rooms) and, for admins, planned costs into this new event (409 once it has registrations or groups) | -| DELETE | `/api/events/:id` | admin | Delete event | -| POST | `/api/events/:id/email-attendees` | supervisor+ | Bulk email attendees (`dryRun: true` to preview) | -| POST | `/api/events/:id/email-attendees/schedule` | supervisor+ | Schedule bulk email | -| POST | `/api/events/:id/whatsapp-attendees` | supervisor+ | Bulk WhatsApp to attendees (`dryRun: true` to preview) | -| POST | `/api/events/:id/whatsapp-attendees/schedule` | supervisor+ | Schedule bulk WhatsApp | -| GET | `/api/events/attachments/status` | admin | Attachment manifest sync status | -| POST | `/api/events/attachments/sync` | admin | Re-sync attachment manifests to DB | - -### isSoldOut logic (`GET /api/events`) -`isSoldOut` is `true` when every option on the event that has `stockLimit > 0` has sold out its full allocation (computed from non-cancelled `RegistrationOption` quantities). Events with no limited options are never marked sold out. - -### POST /api/events -```json -{ - "title": "Family Camp 2025", - "description": "Annual family camp at the farm.", - "startDate": "2025-07-10T08:00:00.000Z", - "endDate": "2025-07-14T17:00:00.000Z", - "registrationDeadline": "2025-07-01T00:00:00.000Z", - "goLiveAt": "2025-05-01T00:00:00.000Z", - "price": 450, - "picture": "/uploads/events/camp.jpg", - "redirectUrl": "camp2025", - "isHidden": false, - "requiresAuth": true, - "form": { - "isRequired": true, - "fields": [ - { "type": "text", "label": "Dietary requirements", "isRequired": false, "order": 0 } - ] - } -} -``` - -A copy made with "Copy" on the Events page is an ordinary `POST /api/events` from the event form, -with `clonedFromId` (the source event, noted in the `event_created` audit entry), followed by the -options, feedback form, sections and recipients as for a new event, then `POST /api/events/:id/copy-from`. - ---- - -## Event Options & Variants - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/events/:id/options` | supervisor+ | Add option to event | -| PUT | `/api/events/options/:id` | supervisor+ | Update option (name, price, stockLimit, variants, earlyBirdTiers) | -| DELETE | `/api/events/options/:id` | admin | Delete option (fails if registrations exist) | -| POST | `/api/events/options/:id/variants` | supervisor+ | Add variant to option | -| PUT | `/api/events/variants/:id` | supervisor+ | Update variant | -| DELETE | `/api/events/variants/:id` | admin | Delete variant | - -### POST /api/events/:id/options -```json -{ - "name": "Adult", - "price": 450, - "isMainTicket": false, - "stockLimit": 100 -} -``` - -### PUT /api/events/options/:id — with variants and early-bird tiers -```json -{ - "name": "Adult", - "price": 450, - "stockLimit": 100, - "variants": [ - { "name": "Standard", "price": null, "stockLimit": 60, "order": 0 }, - { "name": "VIP", "price": 600, "stockLimit": 40, "order": 1 } - ], - "earlyBirdTiers": [ - { "deadline": "2025-06-01T00:00:00.000Z", "price": 350, "stockLimit": 30, "order": 0, "variantId": null } - ] -} -``` - -`stockLimit: 0` means unlimited. Early-bird tiers can be option-level (`variantId: null`) or variant-level (`variantId: ""`). - ---- - -## Event Attachments - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/events/:id/attachments` | public | List attachments for event | -| POST | `/api/events/:id/attachments` | supervisor+ | Upload attachment (`multipart/form-data`, field `file`) | -| DELETE | `/api/events/:eventId/attachments/:id` | supervisor+ | Delete attachment | - -Accepted file types: `.pdf`, `.doc`, `.docx`, `.xls`, `.xlsx`, `.ppt`, `.pptx`, `.txt`, `.csv`, `.zip`. Max 10 MB. - ---- - -## Registrations - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/registrations` | optional | Create registration | -| GET | `/api/registrations/myregistrations` | user+ | Own registrations | -| GET | `/api/registrations/:id` | optional | Get registration by ID | -| PUT | `/api/registrations/:id/options` | user+ | Update selected options | -| DELETE | `/api/registrations/:id` | user+ | Cancel registration (blocked if positive payments exist unless admin) | -| GET | `/api/registrations/:id/forms/draft` | optional | Get form draft | -| PUT | `/api/registrations/:id/forms/draft` | optional | Save form draft | -| POST | `/api/registrations/:id/forms/responses` | optional | Submit form responses | -| PUT | `/api/registrations/:id/forms/responses` | supervisor+ | Replace form responses | -| GET | `/api/registrations?page=&limit=&unpaid=1&userId=` | staff+ | All registrations (a plain array; paged `{ data, total, page, limit, pages }` when `page` or `limit` is given). `unpaid=1`: still owing (pending, confirmed, partially paid); `userId`: one person's | -| PUT | `/api/registrations/:id` | staff+ | Update registration status | -| GET | `/api/registrations/event/:eventId` | staff+ | Registrations for an event | -| POST | `/api/registrations/manual` | supervisor+ | Manual registration (accepts `couponCode`) | -| PUT | `/api/registrations/:id/attendees` | user+ | Replace the named attendees (`{ attendees: [{ id?, eventOptionId, variantId?, name, email?, phone? }], ticketDelivery? }`); owner or staff | -| POST | `/api/registrations/:id/attendees/:attendeeId/send-form-link` | user+ | Email/WhatsApp an attendee the link to their own form | -| POST | `/api/registrations/:id/coupon` | user+ | Apply a code to an existing registration (owner, or staff on someone's behalf) | -| DELETE | `/api/registrations/:id/coupon` | staff+ | Remove the code (refused once a ticket on a paid registration has been scanned) | - -### POST /api/registrations -```json -{ - "eventId": "ev-uuid-...", - "options": [ - { "eventOptionId": "opt-uuid-...", "quantity": 2 }, - { "eventOptionId": "opt-uuid-...", "quantity": 1, "variantId": "variant-uuid-..." } - ] -} -``` -Add `"couponCode": "STAFF50"` to apply a discount code. The code is checked before anything is saved (400 with the reason if it can't be used). If the last use is taken by someone else in the moment between checking and saving, the registration is still created at full price and the response includes `couponError`. - -**Group tickets:** on events with `allowNamedAttendees`, `POST /api/registrations` and `/manual` accept `attendees: [{ eventOptionId, variantId?, name, email?, phone? }]` (main-ticket places only, no more than the places bought) and `ticketDelivery: "payer" | "each"`. -- Each named attendee gets their own quantity-1 ticket; unnamed places share one quantity ticket. -- An attendee whose email/phone matches one existing account is linked to it, so the ticket also appears in that person's `GET /api/tickets/mytickets`. -- With `"each"`, tickets are emailed/WhatsApped to attendees directly, falling back to the payer. -- Form responses can carry `attendeeId`. - -Registration responses include `discountTotal` (the coupon discount), `subtotalComputed` (items before the discount), `totalDueComputed` (after it) and `couponRedemptions` (the active code). - -For unauthenticated (guest) registration on events with `requiresAuth: false`: -```json -{ - "eventId": "ev-uuid-...", - "options": [...], - "guestName": "Jane Smith", - "guestEmail": "jane@example.com", - "guestPhone": "+27821234567" -} -``` - -### Cancellation rules - -| Actor | Condition | Result | -|-------|-----------|--------| -| Owner | No positive payments | 200 — status set to `cancelled` | -| Owner | Any positive payment exists | 403 — must contact organisation | -| Admin | Any state | 200 — always allowed | -| Anyone | Already cancelled | 400 | - ---- - -## Background jobs - -Timed jobs run on a pg-boss queue in Postgres (schema `pgboss`, created on first start) — -see `backend/src/jobs/index.js`. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/admin/jobs` | admin | `{ mode: "queue" \| "timers" \| "off", timezone, jobs: [{ name, label, cron, enabled, envFlag, nextRun, recent: [{ state, startedOn, completedOn, output }] }] }` | -| POST | `/api/admin/jobs/:name/run` | admin | Run a job now: `{ queued: true, id }` (or `{ queued: false, output }` in timer mode). Audit-logged as `job_run_manual` | - -Env: `JOBS_ENABLED=false` turns every job off; each job's own flag (`WAITLIST_JOB_ENABLED`, …) -turns it off; `JOB_SCHEDULE_` (e.g. `JOB_SCHEDULE_DAILY_SUMMARY="0 6 * * *"`) changes its -cron schedule; times are in `APP_TIMEZONE` (default Africa/Johannesburg). - ---- - -## Impersonation - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/admin/impersonate/:userId` | admin (2FA on) | `{ reason }` → `{ token, session }`. The token acts as the user, is read-only, and lasts 30 minutes. Refused for admins and inactive users | -| POST | `/api/admin/impersonate/end` | impersonation token | End the session | -| POST | `/api/admin/impersonate/log` | impersonation token | `{ path }` — page viewed (audit trail) | -| GET | `/api/admin/impersonate/current` | impersonation token | The live session | -| GET | `/api/admin/impersonation-sessions` | admin | Sessions with their request trail | - -Read-only enforcement: -- A guard mounted before every route returns `403 { code: "IMPERSONATION_READ_ONLY" }` for any non-GET/HEAD/OPTIONS request made with an impersonation token. The only exceptions are `end` and `log`. Blocked attempts are logged. -- An ended or expired session gets `401 { code: "IMPERSONATION_ENDED" }`. -- GET handlers skip side-effect writes (pricing refresh) while `req.readOnly` is set. - -## Registration funnel - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/analytics/track` | public (rate-limited) | `{ sessionId, eventId, stage: 'view'\|'start', source? }` → always `204`. Bots are ignored; device type comes from the User-Agent | -| GET | `/api/analytics/funnel?eventIds=&from=&to=` | supervisor+ | `{ totals, conversion, trend, bySource, byDevice, byOption, perEvent }` | - -How the stages are recorded: -- `POST /api/registrations` accepts `analyticsSessionId`. It's stored on the registration and records the `submit` stage. -- `paid` is read from that registration's status. -- Counts are sessions that reached a stage or a later one. - -Data handling: -- Sessions inactive for 90 days are rolled up into `AnalyticsDaily` by a daily job (`ANALYTICS_ROLLUP_ENABLED`). -- `/api/stats/overview` now includes `funnel: { views, paid, conversion }` for live events over the past 30 days. - -## Post-event feedback - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/feedback/event/:eventId` | supervisor+ | The event's feedback form (with `invited` / `responses` counts), or null | -| PUT | `/api/feedback/event/:eventId` | supervisor+ | `{ sendAt, audience: 'checked_in'\|'all', anonymous, intro, fields[] }` — fields can't change once answered (409) | -| DELETE | `/api/feedback/event/:eventId` | supervisor+ | Remove the form | -| POST | `/api/feedback/event/:eventId/send-now` | supervisor+ | Send now (also invites anyone not yet invited) | -| GET / POST | `/api/feedback/public/:token` | link holder | Load the form / submit `{ answers: { fieldId: value } }` once | -| GET | `/api/feedback/summary?eventIds=a,b` | supervisor+ | Per event: invited, responses, response rate, and per question: rating average + distribution, choice counts, text answers (names only when not anonymous) | - -Notes: -- New field types `rating` (answers `"1"`–`"5"`) and `multiple_choice` (`options`: array of strings). They can be used on attendee forms too. -- Only HMACs of link tokens are stored, and a reminder issues a new link. -- A job every 15 minutes (`feedback` job; `FEEDBACK_JOB_ENABLED`, `JOB_SCHEDULE_FEEDBACK`) sends due forms, and sends one reminder 3 days later to people who haven't answered. - -## Sponsor a spot - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/sponsorships/event/:eventId` | public | `{ enabled, open, spotPrice, showProgress, goalSpots, spotsFunded, sponsors }` — never recipients | -| POST | `/api/sponsorships/checkout` | public (optional login) | `{ eventId, spots? \| amount?, anonymous?, sponsorName?, message?, name?, email? }` → Yoco `redirectUrl`. Guests give a name and email | -| GET | `/api/sponsorships/event/:eventId/pool` | supervisor+ | `{ received, assigned, remaining, sponsors, spotsFunded, spotPrice, goalSpots }` | - -How the money is handled: -- A spot costs the cheapest paid main ticket. -- Yoco checkout metadata carries `type: 'sponsorship'`. The webhook records the payment as `isDonation` + `isSponsorship` against the event, together with `sponsorName`, `sponsorMessage` and `sponsorAnonymous`. -- Pool funds are assigned with `PUT /api/payments/assign-donation`. - -Other changes: -- Event fields: `allowSponsorships`, `sponsorshipGoalSpots`, `showSponsorshipProgress`. -- `POST /api/events/:id/email-attendees` accepts `filter.audience: 'sponsors'`. -- `POST /api/automations/schedule` jobs accept `audience: 'sponsors'`. - -## Rooms & groups - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/allocations/event/:eventId` | supervisor+ | Board: sets (groups, assignments), named attendees, possible leaders, unnamed places | -| POST | `/api/allocations/sets` | supervisor+ | `{ eventId, name, showOnTicket? }` | -| PUT / DELETE | `/api/allocations/sets/:id` | supervisor+ | Rename / show on tickets; delete | -| POST | `/api/allocations/sets/:id/groups` | supervisor+ | `{ name, capacity?, gender? ('male'\|'female'), leaderUserId? }` | -| PUT / DELETE | `/api/allocations/groups/:id` | supervisor+ | Edit (can't drop below current members or break gender); delete (members become unassigned) | -| PUT | `/api/allocations/sets/:id/assignments` | supervisor+ | `{ attendeeId, groupId }` (null unassigns); enforces capacity and gender | -| DELETE | `/api/allocations/sets/:id/assignments` | supervisor+ | Clear the set | -| POST | `/api/allocations/sets/:id/auto` | supervisor+ | `{ mode: 'together' \| 'split' }` — places everyone not yet placed | -| GET | `/api/allocations/sets/:id/lists?medical=true` | supervisor+ | Groups with members for printing (medical view is audited) | -| GET | `/api/allocations/my-groups` | staff+ | Groups the caller leads (medical details for supervisors only) | - -Related changes: -- `Event.collectGender` makes a gender (`male` / `female`) required for each named attendee. -- Email and WhatsApp attendees accept `filter.allocationGroupId`. - -## Ticket transfer - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/tickets/:id/transfer` | payer, holder or supervisor+ | `{ name, email?, phone?, dateOfBirth?, gender?, parentName?, parentEmail?, parentPhone? }` → `201`. Creates an offer and sends a link to the details given. **Nothing changes on the ticket yet.** A new offer replaces an open one | -| DELETE | `/api/tickets/:id/transfer` | payer, holder or supervisor+ | Withdraw the open offer | -| GET | `/api/tickets/transfer-offer/:token` | link holder | `{ status, toName, fromName (first name), event, option, expiresAt }` | -| POST | `/api/tickets/transfer-offer/:token/accept` | link holder | Accept — the transfer happens now (all checks run again) | -| POST | `/api/tickets/transfer-offer/:token/decline` | link holder | Decline | -| GET | `/api/tickets/:id/transfers` | payer, holder or staff+ | Transfer history | - -Privacy: -- There is no user search. The sender's request is checked (rules, required fields) without looking up any account, and no response reveals whether the email/phone belongs to an account. -- Offers expire after 7 days or when the event starts. -- Only an HMAC of the link token is stored. - -Rules: -- Only before the event starts, and only for tickets that have never been scanned. -- `Event.allowTicketTransfer` turns it off for non-supervisors. - -What a transfer does: -- The new holder becomes the ticket's attendee and gets a new QR code. A shared ticket for several places has one place split off into its own ticket. -- An account is matched by email/phone, or created inactive with an activation link. -- The previous holder's attendee form answers are deleted, and the medical details on their consent are cleared. A minor on a youth event gets a new consent request. - -Old QR codes: -- `scan-preview` and `scan` return `410 { code: "TICKET_TRANSFERRED" }`. -- Offline sync reports them as `transferred`. -- Each transfer is audited as `ticket_transferred`. - -## Offline scanning - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/scan-locks?eventId=` | staff+ | Active offline locks for an event | -| POST | `/api/scan-locks` | staff+ | Lock `{ eventId, sectionId?, deviceId, deviceName? }` to this device (409 if the scope is held elsewhere) | -| GET | `/api/scan-locks/:id/snapshot?deviceId=` | staff+ | Tickets valid in the lock's scope (lock holder only) | -| POST | `/api/scan-locks/:id/sync` | staff+ | `{ deviceId, scans: [{ clientScanId, qrCode, qty, scannedAt }] }` — idempotent; returns accepted, duplicates, conflicts | -| DELETE | `/api/scan-locks/:id` | staff+ | Release (`{ deviceId }`, lock holder only) | -| POST | `/api/scan-locks/:id/force-release` | supervisor+ | Release a lost device's lock | -| GET | `/api/scan-locks/reports?eventId=&unreviewed=` | supervisor+ | Sync reports | -| POST | `/api/scan-locks/reports/:id/review` | supervisor+ | Mark a report reviewed | - -How locks work: -- One device per scope. A whole-event lock (`sectionId` null) clashes with every section lock on that event. -- `POST /api/tickets/scan/:qrCode` now accepts `sectionId` and `deviceId`. It enforces the section on the server, and returns `423 { code: "SCAN_LOCKED" }` when another device holds a lock covering the ticket. - -How syncing works: -- Synced scans never redeem more than is left on a ticket. -- Conflicts are recorded in the sync report: `not_found`, `cancelled`, `wrong_scope`, `already_used`, `partly_used` and `consent`. -- Check-in messages are sent after the sync. -- Locks, releases, force-releases and syncs are written to the admin audit log. - -## Multi-day events & attendance - -An event with `scheduleType: "sessions"` runs on several dates (e.g. every Wednesday for -5 weeks). People register and pay once and get one ticket; check-in is per session. -`startDate`/`endDate` always follow the first and last active session. - -Create/update fields (`POST`/`PUT /api/events`): - -| Field | Notes | -|-------|-------| -| `scheduleType` | `single` (default) or `sessions`. Switching back to `single` is refused once there are session check-ins | -| `attendanceMode` | `whole` (default) or `pick` — people choose sessions. Not allowed with `requiresParentalConsent` | -| `sessions` | `[{ id?, label?, startsAt, endsAt, location?, cancelled?, capacity? }]` — the full list. Rows left out are deleted (refused when they have check-ins — send `cancelled: true` instead). The event and its sessions save together, so a refused change saves nothing | -| `lateJoinEnabled`, `lateJoinUntilSessionIndex` | Registration stays open until that session (index into the sent list, sorted by start) starts; otherwise it closes when the first session starts | -| `latePricing`, `lateFixedPrice` | `full`, `prorata` (price × sessions left ÷ sessions, nearest R10, at least R10) or `fixed` (only ever lowers the price). Main tickets only | -| `checkInWindow` | `whole_day` (default — any time on the session's date, in `APP_TIMEZONE`, default Africa/Johannesburg) or `session_only` (2 h before start until the end) | -| `sessionReminders` | `null` (off) or `{ offsets: [60 \| 180 \| 1440], channels: ["email", "whatsapp"] }` | -| `certificatesEnabled`, `certificateConfig` | `{ template: classic \| modern \| church \| kids, title, body ({name} {event} {sessionsAttended} {totalSessions} {endDate}), signatureName, signatureRole, signatureImage, rule: { type: all \| count \| percent, value }, sendOnIssue }` | - -Event options take `sessionMode: "all" | "pick"` (`POST /api/events/:id/options`, `PUT /api/events/options/:id`). -In a pick-mode event, a `pick` option is bought per session: registration lines send -`sessionIds: [...]` (`POST /api/registrations`, `/manual`, coupon/bundle quotes), and each -session becomes its own registration line (`RegistrationOption.sessionId`) and ticket. -Capacity counts picked places plus whole-course main tickets; a pick option's -`stockLimit` is per session. `PUT /api/registrations/:id/options` refuses pick options and -leaves picked lines untouched. An `all` option in a pick-mode event may also send -`sessionIds`: it stays one line and one ticket at one price, with the sessions kept in -`RegistrationOption.sessionIds` (empty = every session). That ticket only scans on those -sessions, and capacity, reminders, the register and certificates follow them; adding more -of the same ticket to a registration merges the sessions. Pick-mode events stay open until the last session starts -(`wholeCourseClosesAt` gives when whole-course tickets stop). Single-event responses add -`booked` and `placesLeft` per session and `sessionAvailability` per pick option. - -Responses for events include `sessions[]` (with `cancelled` and `hasCheckIns`), -`registrationClosesAt`, `nextSession` and `lateJoin: { active, mode, sessionsLeft, totalSessions, fixedPrice }`. -`PUT` also returns `sessionChanges: { added, moved, cancelled, restored, removed }`. - -Scanning: `GET /api/tickets/scan-preview/:qr?sessionId=` and `POST /api/tickets/scan/:qr` -(`{ sessionId? }`) default to today's session and return `session` plus `remaining` for it; -`sessionError` / 400 `NO_SESSION` when no session is open for check-in. Offline snapshots -are for the session running when downloaded; synced scans count for the session at their scan time. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/attendance/:eventId` | staff+ | Register: `columns` (sessions), `rows` (one per main ticket: `checkIns` per session, `attended`, `total`, `completed`, `certificate`), `totals` | -| GET | `/api/attendance/:eventId/export?format=xlsx\|pdf` | staff+ | Download the register | -| POST | `/api/attendance/:eventId/mark` | supervisor+ | `{ ticketId, sessionId, present }` — single-date events use `sessionId: "event"` | -| POST | `/api/attendance/:eventId/certificates` | supervisor+ | Issue now to everyone eligible, or `{ ticketId }` for one (even if not eligible) | -| POST | `/api/attendance/:eventId/certificates/send` | supervisor+ | Send unsent certificates, or `{ certificateId }` | -| GET | `/api/attendance/:eventId/certificates.pdf` | supervisor+ | All certificates in one PDF | -| POST | `/api/attendance/certificates/preview` | supervisor+ | Sample PDF: `{ title, config }` | -| POST | `/api/attendance/certificates/:id/revoke` | supervisor+ | Revoke (never re-issued automatically) | -| GET | `/api/attendance/certificates/mine` | user+ | My certificates | -| GET | `/api/attendance/certificates/:id/pdf` | user+ | Download one (its person, the booker, or a supervisor) | -| GET | `/api/attendance/certificates/verify/:code` | public | `{ valid, revoked?, name, event, completedOn, issuedAt }` | - -A job every 5 minutes (`sessions` job; `SESSION_JOBS_ENABLED`, `JOB_SCHEDULE_SESSIONS`) sends due session -reminders (each once; when several are due at once only the closest is sent) and issues -certificates for events with certificates on that ended in the last 14 days. - ---- - -## Waitlist - -Events with `waitlistEnabled` (plus `waitlistOfferHours`, default 24, and `waitlistPartialOffers`, default true) take a queue for sold-out lines. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/waitlist` | optional | Join: `{ eventId, eventOptionId, variantId?, sessionId?, quantity }` (+ `guestName`, `guestEmail`, `guestPhone` when not logged in on a guest event). Only when the line can't cover the quantity. `sessionId` is required for a pick-sessions option (one session per entry) and refused otherwise | -| GET | `/api/waitlist/mine` | user+ | My active entries | -| DELETE | `/api/waitlist/:id` | user+ | Leave (an open offer moves on) | -| GET | `/api/waitlist/claim/:token` | public | What a claim link offers (with `sessionId`, `sessionName`, `lineName` for a per-session offer; `eventStart` is the session's start) | -| GET | `/api/waitlist/events/:eventId` | staff+ | The queue for an event | -| POST | `/api/waitlist/:id/offer` | supervisor+ | Offer now (`{ quantity? }`), even over the stock limit | -| POST | `/api/waitlist/:id/move` | supervisor+ | `{ direction: "up" \| "down" }` | -| POST | `/api/waitlist/:id/remove` | supervisor+ | Take someone off | - -How offers work: -- Places held for a live offer count as taken everywhere stock is counted: `availableCount`, `isSoldOut` and registration stock checks. -- Offers are made automatically when places free up: a cancellation, a smaller booking, or a raised stock limit. -- A job every 10 minutes (`waitlist` job; `WAITLIST_JOB_ENABLED`, `JOB_SCHEDULE_WAITLIST`) expires unclaimed offers and re-offers. -- Claiming means registering with `POST /api/registrations` plus `waitlistToken`. The token stands in for logging in, and the held places are released to the claimer. -- Manual registration and adding places to an existing booking are now checked against stock too. -- Pick-sessions options are waited for per session: free places are that session's (stock per session and session capacity), an offer expires no later than the session's start, and sessions that started or were cancelled aren't offered. For main tickets, free places also take session capacity into account, and held places count towards it. - -## Parental consent - -Youth events (`requiresParentalConsent`, plus `consentText`, `consentCollectMedical`, `consentCollectEmergency` and `consentCollectPhoto` on the event) need every main place named with a `dateOfBirth`. Attendees under 18 on the start date also need `parentName`, `parentEmail` and `parentPhone`. Changing `consentText` bumps `consentTextVersion`. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/consent/:token` | public | What the parent sees: attendee, event, consent text, fields to fill in | -| POST | `/api/consent/:token` | public | `{ decision: "give"\|"decline", signedName, isGuardian: true, medical?, emergency?, photoConsent? }` | -| GET | `/api/consent/events/:eventId` | staff+ | Consent status per attendee, with counts | -| POST | `/api/consent/requests/:id/resend` | user+ | Re-send one request with a new link (registrant or staff) | -| POST | `/api/consent/events/:eventId/resend-pending` | supervisor+ | Re-send every pending request | -| POST | `/api/consent/events/:eventId/rerequest` | supervisor+ | New requests for consent given on older text, and minors with none | -| GET | `/api/consent/events/:eventId/medical` | supervisor+ | Decrypted medical & emergency list (audited as `medical_list_viewed`) | - -How requests work: -- Requests go to the parent by both email and WhatsApp, whatever anyone's notification preference. -- Links are random tokens; only an HMAC is stored. They expire when the event ends. -- The answer stores the signed name, time, IP, device, and the exact text and version shown. -- Medical and emergency details are AES-256-GCM encrypted. A daily job (09:00, `CONSENT_JOBS_ENABLED=false` to disable) sends reminders (day 2, then every 3 days) and deletes them `consent_medical_retention_days` (default 30) after the event. - -Check-in rules: -- `GET /api/tickets/scan-preview/:qrCode` returns `consentStatus` (`not_required`, `missing`, `pending`, `given` or `declined`). -- `POST /api/tickets/scan/:qrCode` returns `403 { code: "CONSENT_REQUIRED" }` unless consent is given. -- Supervisors can pass `overrideConsent: true`, which is audited as `consent_override`. - -## Privacy (POPIA) - -The data subject's tools, unsubscribe links and the admin data-requests inbox (`src/utils/privacy.js`, `src/controllers/privacyController.js`). - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/privacy/me` | user | `{ news: { email, whatsapp }, newsAskedAt, canWhatsApp, notificationPreference, history, requests }` | -| PUT | `/api/privacy/me/news` | user | `{ email?: bool, whatsapp?: bool, source?: "prompt" }` — change the news opt-in (WhatsApp needs a valid phone). Logged in `CommunicationConsent`; `source: "prompt"` is the one-time question after login | -| GET | `/api/privacy/me/export` | user | Download my data as JSON (`?format=pdf` for a readable PDF). Recorded as a completed self-service `access` request. 403 while impersonating; rate-limited | -| POST | `/api/privacy/me/requests` | user | `{ type: "correction", details }` or `{ type: "deletion", password, details? }`. Deletion closes the account at once (deactivated, sessions revoked, news off). 409 if one of that type is already open. Emails the Information Officer + admins | -| GET | `/api/privacy/unsubscribe/:token` | public (signed token) | What the link is for: an account (masked email, news state) or an address | -| POST | `/api/privacy/unsubscribe/:token` | public (signed token) | `{ channels?: ["email","whatsapp"] }` — turn news off (default both) | -| POST | `/api/privacy/unsubscribe/:token/one-click` | public (signed token) | RFC 8058 one-click (from the `List-Unsubscribe` header) — email news off. GET redirects to `/unsubscribe` | -| GET | `/api/privacy/requests?status=open\|closed\|all&search=&page=&limit=` | admin | Data requests (not self-service downloads), 50 a page (`total`, `pages`), with `overdue` and, for open deletions, `blockers` (registrations for events that haven't ended). `search` matches name or email | -| POST | `/api/privacy/requests/:id/complete` | admin | `{ response? }` (required for corrections; emailed). Deletion: anonymises the account — 409 while it has blockers. Audited as `data_request_completed` (+ `user_anonymised`) | -| POST | `/api/privacy/requests/:id/reject` | admin | `{ response, cancelled?: bool }` — reject (or mark withdrawn); a deletion reopens the account. Audited as `data_request_rejected` | - -Privacy notice, operators and logs (`src/utils/privacyNotice.js`, `src/utils/accessLog.js`, `src/controllers/privacyAdminController.js`): - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/privacy/notice?version=N` | public | The notice (current, or version N) with placeholders filled in: `{ version, builtIn, current, effectiveDate, changeSummary, sections: [{ id, title, body }], versions }`. Version 0 = the built-in notice, only while nothing is published | -| POST | `/api/privacy/me/notice/accept` | user | Accept the current version (recorded in `NoticeAcceptance`, `User.noticeVersionAccepted`). 403 while impersonating | -| GET | `/api/privacy/notice/draft` | admin | Editor state: `sections` (raw, with placeholders), `rendered`, `isDraft`, `savedAt`, `versions` (with acceptance counts), `builtIn` (the built-in sections), `placeholders` | -| PUT | `/api/privacy/notice/draft` | admin | `{ sections }` — save the draft (AppSetting `privacy_notice_draft`) | -| DELETE | `/api/privacy/notice/draft` | admin | Discard the draft | -| POST | `/api/privacy/notice/publish` | admin | `{ sections, changeSummary?, requiresAcceptance? }` — publish the next version and clear the draft. `requiresAcceptance` needs a `changeSummary`. Audited as `privacy_notice_published` | -| GET / POST | `/api/privacy/operators` | admin | The operator register / add one `{ name, purpose, dataShared?, location?, website?, active? }` | -| PUT / DELETE | `/api/privacy/operators/:id` | admin | Change / remove an operator (audited as `operator_*`) | -| GET | `/api/privacy/consent-log?type=news\|notice\|parental&q=&page=` | admin | News opt-in changes, notice acceptances, or parental consent answers (50 per page) | -| GET | `/api/privacy/access-log?action=&actorId=&from=&to=&page=` | admin | Bulk exports/views of personal information, with `actions` (labels) and `actors` for the filters | -| GET | `/api/privacy/readiness` | admin | `{ score, passed, total, checks: [{ key, label, ok, detail, href, applies }] }` | -| GET | `/api/privacy/retention` | admin | `{ policies, definitions, reviewedAt, reviewedBy, preview, lastRun, related }` — `preview` is what the next run would affect | -| PUT | `/api/privacy/retention` | admin | `{ policies: { inactive_accounts\|form_answers\|login_history\|payment_details\|audit_logs: { enabled, months } } }` — all five required. Audited as `retention_policies_updated` | -| POST | `/api/privacy/retention/run` | admin | Run the retention job now: `{ result, state }` | -| GET / POST | `/api/privacy/breaches` | admin | The breach register / record one `{ title, discoveredAt, description, dataAffected, occurredAt?, peopleAffected?, whoAffected?, consequences?, actionsTaken?, adviceToPeople?, causedBy? }` | -| PUT | `/api/privacy/breaches/:id` | admin | Change any of those, `status` (open\|contained\|closed), `regulatorNotifiedAt`, `peopleNotifiedAt`. Audited as `breach_updated` | - -The `retention` job (03:30, `RETENTION_JOBS_ENABLED=false` to disable) works through each switched-on policy. Inactive accounts: role `user`, not anonymised, whose latest of created / last login (`User.lastLoginAt`) / registration or its event's end / named as attendee / payment is older than the period. Those within 30 days of it are warned (email, else WhatsApp; `User.inactivityWarnedAt`), and those warned at least 30 days ago — after their last activity — are anonymised unless they have a registration for an upcoming event. Logging in clears the warning. At most 300 warnings and 200 anonymisations per run. Payment details: `ProviderTransaction.raw` and `ProviderCheckout.request` older than the period are scrubbed and marked `_scrubbed`. Access log rows carry `sensitive` (medical lists, and anything for an event with `requiresParentalConsent`); `?sensitive=true` filters them. - -Placeholders in notice sections: `{org}`, `{orgEmail}`, `{website}`, `{ioName}`, `{ioEmail}`, `{medicalRetentionDays}`, and — each on a line of its own — `{operators}` (one bullet per active operator) and `{retention}` (one bullet per retention period). Login and `GET /api/users/profile` return `noticePromptPending` — true when a version with `requiresAcceptance` is newer than the one the person accepted. Sign-up records an acceptance of the current version (source `signup`). - -Access log actions (`DataAccessLog.action`): `report_pdf`, `report_excel`, `report_email`, `report_whatsapp` (`/api/reports/*`, with the row count), `attendance_export`, `certificates_download`, `group_lists` (or `medical_list` with `?medical=true`), `form_responses` (first page of a list), `consent_list`, `medical_list`, `backup_download`, `impersonation`. - -Notes: -- Requests are due 30 days after they're made. The `privacy` job (08:00, `PRIVACY_JOBS_ENABLED=false` to disable) emails the Information Officer (`legal_io_email`) and admins about open requests due within 7 days or overdue. -- **Anonymising** (also `POST /api/users/:id/anonymize`) keeps payments, registrations, tickets and check-ins, and removes: the account's name/email/phone/password, the details of attendees on their registrations and their own attendee rows elsewhere, parental-consent details, form answers and drafts, feedback authorship and invites, waiting waitlist places, pending transfer requests, names on transfers and certificates, sponsor names/messages, login history, password resets and 2FA challenges, and payer fields in provider webhook payloads and checkouts. -- Sign-up (`POST /api/users`) takes `newsOptIn: bool`. Login and `GET /api/users/profile` return `newsPromptPending` (never answered the opt-in question). - -## Coupons - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/coupons/validate` | optional | Check a code against a basket (`{ code, eventId, options, forUserId? }`) | -| GET | `/api/coupons` | supervisor+ | List codes with use counts and total discount | -| POST | `/api/coupons` | supervisor+ | Create a code | -| GET | `/api/coupons/:id` | supervisor+ | One code with its uses | -| PUT | `/api/coupons/:id` | supervisor+ | Edit or turn off a code | -| GET | `/api/coupons/redemptions` | supervisor+ | Uses for the Discounts report (`eventIds`, `from`, `to`) | - -- **Types:** `percent` (value 1–100), `fixed` (rand amount), `comp` (free). -- **Scope:** `eventIds` (none = every event) and `options: [{ eventOptionId, variantId? }]` (none = the whole registration). -- **Restrictions:** `userIds`, `restrictRoles` and `restrictDomain`. A match on any one is enough, and restricted codes need a known account. -- **Limits:** `validFrom`, `validUntil`, `maxUses`, `maxUsesPerUser` (default 1) and `minQuantity`. -- **Early-bird:** `stackEarlyBird: false` means the better price wins; `true` discounts the early-bird price. -- **Locked amount:** the discount is locked when applied. Editing items recalculates percentage and comp codes, but fixed codes keep their amount. Cancelling releases the use. - -Options and variants also accept an optional `staffPrice`, charged automatically to Staff and above when it's lower than the normal price. - -## Payments - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/payments` | supervisor+ | Record manual payment (cash/EFT) | -| POST | `/api/payments/checkout` | user+ | Start an online checkout (also `/api/payments/yoco-checkout`); `provider` optional (default: first enabled provider); at least R15; re-evaluates early-bird pricing first — returns `{ priceUpdated: true, newTotal }` if prices changed | -| POST | `/api/payments/checkout/send` | supervisor+ | Send a generated payment link by email or WhatsApp (also `/api/payments/yoco-checkout/send`) | -| GET | `/api/payments/providers` | public | Providers people can pay with now (enabled and set up), in order: `{ providers: [{ id, label }], minimumAmount: 15 }` | -| GET | `/api/payments/providers/settings` | admin | Every provider with `enabled`, `configured` and `capabilities` (`refund`, `getTransaction`, `listTransactions`) | -| GET | `/api/payments/pay/:id` | public (checkout id) | The payer's page for a checkout: `{ status: open\|paid, amount, description, provider, providers, cancelUrl, redirectUrl, form }`. `form` (`{ action, fields }`) is set once a form provider (PayFast) is chosen — the page posts it | -| POST | `/api/payments/pay/:id` | public (checkout id) | `{ provider }` → starts the checkout with that provider: `{ provider, redirectUrl }` (Yoco) or `{ provider, form }` (PayFast). 409 when already paid | -| GET | `/api/payments/checkouts/open` | supervisor+ | Online checkouts from the last 14 days with no payment yet: `{ checkouts: [{ id, provider, providerLabel, canCheck, amount, description, type, registrationId, payer, createdAt }], days }` | -| POST | `/api/payments/checkouts/check` | supervisor+ | `{ ids? }` (default: every open one) → asks each provider and records payments it received: `{ results: { [checkoutId]: { status: paid\|recorded\|needs_review\|not_paid\|cant_check, note? } }, recorded, message }`. PayFast: transaction history (API); Yoco: `cant_check` | -| PUT | `/api/payments/providers/settings` | admin | `{ providers: [{ id, enabled }] }` in display order. Audit logged (`payment_providers_updated`) | -| GET | `/api/payments/mypayments` | user+ | Own payments | -| GET | `/api/payments/:id` | user+ | Payment by ID | -| GET | `/api/payments/registration/:registrationId` | user+ | Payments for a registration | -| GET | `/api/payments?page=&limit=&userId=&from=&donations=1` | supervisor+ | Payments, newest first, paged (`limit` up to 200). `userId`: one person's; `from`: created on/after (ISO); `donations=1`: donations and the legs applying them | -| GET | `/api/payments/event/:eventId` | staff+ | Payments for an event | -| PUT | `/api/payments/assign-donation` | supervisor+ | Assign a donation payment to a registration | -| POST | `/api/payments/refund` | supervisor+ | Create refund record | -| GET | `/api/payments/admin/stats` | admin | Payment statistics | - -### POST /api/payments (manual) -```json -{ - "registrationId": "reg-uuid-...", - "amount": 450, - "method": "cash", - "note": "Paid at the door" -} -``` - -### POST /api/payments/checkout -```json -{ - "registrationId": "reg-uuid-...", - "successUrl": "https://events.yourchurch.org/payment/success", - "cancelUrl": "https://events.yourchurch.org/payment/cancel", - "failureUrl": "https://events.yourchurch.org/payment/failure" -} -``` -Returns: `{ redirectUrl }` or `{ priceUpdated: true, newTotal, message }` if early-bird prices changed. - ---- - -## Tickets - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/tickets/mytickets` | user+ | Own tickets (excludes cancelled registrations) | -| GET | `/api/tickets/:id` | user+ | Ticket by ID | -| POST | `/api/tickets/email` | user+ | Email own tickets as PDF | -| POST | `/api/tickets/send-to` | staff+ | Send tickets to a specific user | -| GET | `/api/tickets/scan-preview/:qrCode` | staff+ | Preview scan (no mark) | -| GET | `/api/tickets/qr/:qrCode` | staff+ | Ticket by QR code | -| POST | `/api/tickets/scan/:qrCode` | staff+ | Scan/redeem ticket | -| GET | `/api/tickets/event/:eventId` | staff+ | All tickets for an event | -| GET | `/api/tickets/scans/recent` | staff+ | Recent scan activity | -| GET | `/api/tickets/scans/stats` | staff+ | Scan statistics | -| POST | `/api/tickets/generate` | supervisor+ | Generate tickets for a registration | -| GET | `/api/tickets` | supervisor+ | All tickets | -| PUT | `/api/tickets/email-sent` | admin | Bulk mark tickets as emailed | - ---- - -## Broadcasts (Email) - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/broadcasts/preview` | supervisor+ | Dry-run — returns recipient count and sample | -| POST | `/api/broadcasts/send` | supervisor+ | Send email broadcast immediately | -| POST | `/api/broadcasts/schedule` | supervisor+ | Schedule email broadcast | - -### POST /api/broadcasts/send -```json -{ - "subject": "Camp 2025 — Final reminder", - "body": "Hi {{name}}, just a reminder that camp starts tomorrow at 08:00.", - "userIds": ["user-uuid-1", "user-uuid-2"], - "extraEmails": ["extra@example.com"] -} -``` - -Dynamic placeholders: `{{name}}`, `{{event.title}}`, `{{event.start}}`, `{{event.link}}`, `{{balance}}`, `{{promo.title}}`, `{{promo.link}}` - -**Message kind (POPIA).** Every bulk send — these broadcasts, WhatsApp broadcasts, and `POST /api/events/:id/email-attendees` / `whatsapp-attendees` (and their `/schedule`) — takes `kind`: `"update"` or `"news"`. Broadcasts default to `news`, attendee messages to `update`; `promoEventId` (the next-event promo automation) forces `news`, `template: "tickets"` forces `update`. `news` goes only to accounts opted in on that channel (`User.newsEmail` / `newsWhatsApp`) and skips addresses in `MessagingOptOut`; it gets an unsubscribe link (email: plus `List-Unsubscribe` / `List-Unsubscribe-Post` headers; WhatsApp: "Reply STOP"). `update` emails get a footer saying why they were sent. Responses (and dry runs) include `kind` and `skipped`. See [Privacy](#privacy-popia). - ---- - -## WhatsApp Broadcasts - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/whatsapp-broadcasts/preview` | supervisor+ | Dry-run | -| POST | `/api/whatsapp-broadcasts/send` | supervisor+ | Send WhatsApp broadcast immediately | -| POST | `/api/whatsapp-broadcasts/schedule` | supervisor+ | Schedule WhatsApp broadcast | - ---- - -## Scheduled Messages - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/scheduled-emails` | supervisor+ | List all queued/scheduled jobs | -| PATCH | `/api/scheduled-emails/:id` | supervisor+ | Edit scheduled job (reschedule, update content) | -| DELETE | `/api/scheduled-emails/:id` | supervisor+ | Cancel a queued job | - ---- - -## Automations - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/automations/schedule` | supervisor+ | Schedule event lifecycle automations (pre-event reminder, thank-you, promo, etc.) | - ---- - -## Reports - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/reports/pdf` | user+ | Generate and download PDF attendance/payment report | -| POST | `/api/reports/email` | user+ | Email PDF report to current user | - ---- - -## Uploads - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/uploads/event-image` | supervisor+ | Upload event cover image (`multipart/form-data`, field `image`). Returns `{ url }`. Max 5 MB. Formats: jpg, jpeg, png, webp, gif. | -| POST | `/api/uploads/logo` | admin (or unauthenticated during setup) | Upload site logo (`multipart/form-data`, field `image`). Returns `{ url }`. Max 2 MB. Formats: jpg, jpeg, png, webp, svg. | - ---- - -## Sections - -Groups of event options shown as labelled sections on the registration page (e.g. "Tickets", "Add-ons", "Accommodation"). - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/sections` | staff+ | List sections | -| POST | `/api/sections` | supervisor+ | Create section | -| PUT | `/api/sections/:id` | supervisor+ | Update section | -| DELETE | `/api/sections/:id` | admin | Delete section | - -### POST /api/sections -```json -{ - "eventId": "ev-uuid-...", - "name": "Accommodation", - "allowedOptionIds": ["opt-uuid-1", "opt-uuid-2"] -} -``` - ---- - -## Banner - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/banner` | public | Get current site-wide banner (text, colour, active flag) | -| POST | `/api/banner` | supervisor+ | Set site banner | - -### POST /api/banner -```json -{ - "text": "Camp registrations close Friday!", - "color": "#f59e0b", - "isActive": true -} -``` - ---- - -## Forms - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/forms/responses` | staff+ | List all submitted form responses across all events; supports filtering | - ---- - -## Provider Transactions - -Transactions payment providers sent by webhook (`ProviderTransaction`, one per provider + external id). Used for reconciling payments that weren't matched automatically. Each item has `provider`, `providerLabel` and the checkout `metadata`. Also served at `/api/yoco-transactions` (the older name). - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/provider-transactions` | supervisor+ | All transactions (`?provider=yoco&reconciled=&ignored=`) | -| GET | `/api/provider-transactions/unreconciled` | supervisor+ | Transactions not yet matched to a payment (`?provider=`) | -| POST | `/api/provider-transactions/:id/reconcile` | supervisor+ | Record it as a payment on a registration (`{ registrationId }`) or a donation (`{ eventId, userId? }`); the payment gets the transaction's provider | -| POST | `/api/provider-transactions/:id/ignore` | supervisor+ | Mark transaction as intentionally ignored | - ---- - -## WhatsApp Admin - -Manages the WAWP WhatsApp API instance. Credentials are stored in `AppSetting` (preferred) or `.env` (fallback). - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/whatsapp/config` | admin | Get current WAWP credentials, and `webhookUrl` (with its secret) to paste into WAWP | -| POST | `/api/whatsapp/config` | admin | Save WAWP credentials to DB | -| GET | `/api/whatsapp/status` | admin | WAWP session status | -| GET | `/api/whatsapp/qr` | admin | QR code for WhatsApp device linking | -| POST | `/api/whatsapp/create-instance` | admin | Create a new WAWP instance | -| POST | `/api/whatsapp/delete-instance` | admin | Delete WAWP instance | -| POST | `/api/whatsapp/request-code` | admin | Request pairing code (alternative to QR) | -| POST | `/api/whatsapp/logout` | admin | Logout current WAWP session | -| POST | `/api/whatsapp/start` | admin | Start WAWP instance | -| POST | `/api/whatsapp/restart` | admin | Restart WAWP instance | - ---- - -## Hub and licence - -The connection to the Cross Events Hub (`src/hub/`, protocol in `docs/hub-protocol.md`). - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/health` | public | `{ status, version, db, jobs, lastBackupAt }` — 503 when the database is down | -| GET | `/api/hub/status` | admin | `{ state: active\|grace\|suspended\|revoked\|unlicensed, readOnly, daysLeft, endsAt, graceEndsAt, licence, connected, keyConfigured, hubUrl, lastHeartbeatAt, lastError, version, latestVersion, updateAvailable, urgentUpdate, updateSnoozed, releases: [{ version, releasedAt, urgent, notes }], updateRequest, notices }` — `releases` is what's new in each version newer than this one (from the Hub) | -| POST | `/api/hub/connect` | admin (incl. the `/setup` token) | `{ licenceKey }` — registers with the Hub; stores the install id, encrypted secret and licence token. Hub errors pass through with their `code` (`LICENCE_NOT_FOUND`, `LICENCE_IN_USE`, `LICENCE_REVOKED`, `HUB_UNREACHABLE`, …). Audited as `hub_connected` | -| POST | `/api/hub/heartbeat` | admin | Check in now; returns the status | -| POST | `/api/hub/update-request` | admin | Ask the Hub for this site to be updated (protocol §3a); the provider is told, nothing runs on the site. Returns the status with `updateRequest: { requestedAt, version }` until the site runs that version. `409 UP_TO_DATE`; audited as `hub_update_requested` | -| POST | `/api/hub/update-request/cancel` | admin | Withdraw the update request; the Hub tells the provider. Returns the status. Audited as `hub_update_request_withdrawn` | -| POST | `/api/hub/update-snooze` | admin | `{ snooze }` — "Not now": `updateSnoozed` is true (no banner) until a newer version than the one put off is out. `400` when there's no update or it's urgent (security/serious fix). `{ snooze: false }` turns reminders back on. Audited as `hub_update_snoozed` / `hub_update_unsnoozed` | -| GET | `/api/hub/notices` | supervisor | The provider's notices showing now: `[{ id, level: info\|maintenance\|warning, title, message, startsAt, endsAt, updatedAt }]`, from the last heartbeat | - -**Read-only mode** (licence suspended, revoked, or past its grace period): `403 { code: "LICENCE_READ_ONLY" }` on `POST /api/events`, event options and variants, `POST /api/registrations` (and `/manual`), `PUT /api/registrations/:id/options`, `POST /api/payments`, `/payments/checkout` (`/send`), `/payments/yoco-checkout` (`/send`), `/payments/pay/:id`, `POST /api/waitlist`, `POST /api/coupons`, `POST /api/bundles/event/:id`. Everything else — scanning, exports, refunds, cancellations, privacy requests, settings — keeps working, and payment webhooks for payments already started are still processed. - -## Campuses - -Multi-campus (`src/utils/campuses.js`), off by default. While off, every campus field and filter -below is ignored and `GET /api/campuses` returns `{ enabled: false, campuses: [] }`. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/campuses` | public | `{ enabled, campuses }` — active campuses in order | -| GET | `/api/campuses/by-slug/:slug` | public | One active campus (its `/campus/` page); 404 when archived or off | -| GET | `/api/campuses/admin` | admin | All campuses incl. archived, with `notifyRecipients` and `_count { events, homeOf }` | -| PUT | `/api/campuses/settings` | admin | `{ enabled }` — audited as `campuses_toggled` (the `campuses_enabled` setting can't be changed through `PUT /api/settings`) | -| POST | `/api/campuses` | admin | `{ name, slug?, address?, contactName?, contactEmail?, contactPhone?, colour? (#rrggbb), logoUrl?, defaultLocation? }`; 409 when the slug is taken | -| PUT | `/api/campuses/:id` | admin | Same fields, plus `notifyRecipientIds` (staff only) and `archived` | -| PUT | `/api/campuses/order` | admin | `{ ids: [...] }` | -| DELETE | `/api/campuses/:id` | admin | Only without events — otherwise `409 CAMPUS_HAS_EVENTS` (archive instead) | -| GET | `/api/campuses/:id/audience` | supervisor+ | `{ campus, users }` — home campus, plus `?registrants=true` people registered for its events in the last 12 months (not cancelled). Broadcasts send to these ids as usual, so news consent still applies | - -**Campus-scoped staff (1.44.0):** a supervisor or staff member with campus limits -(`PUT /api/users/:id { scopedCampusIds }`, admin; `GET /api/users/:id` returns `scopedCampuses`; -`GET /api/users/profile` returns `campusScope`, null when unscoped or campuses are off) only sees -their campuses' events plus church-wide ones on every staff/supervisor endpoint -(`src/utils/campusScope.js`). Responses for out-of-scope records: -- `404 { message: "Not found" }` — another campus's event or record (nothing leaks). -- `403 { code: "OTHER_CAMPUS" }` — the scanner (`/api/tickets/scan-preview|qr|scan/:qrCode`), naming the ticket's campus. -- `403 { code: "CHURCH_WIDE_EVENT" }` — changing, cashing up or refunding an event for all campuses. -- `403 { code: "CAMPUS_SCOPED" }` — banner, payment reconciliation, open checkouts, unlinked donations, typed-in broadcast addresses or recipients outside their campuses. -- `409 { code: "CAMPUS_HAS_SCOPED_STAFF" }` on `DELETE /api/campuses/:id` while staff are limited to it. - -**Campus on other endpoints:** -- Events carry `campusId` (null = all campuses) and `campus { id, name, slug, colour }`. `POST`/`PUT /api/events` take `campusId` (`''`/`null` = all campuses; an archived campus can stay but can't be newly chosen); moving an event is audited as `event_campus_changed`. -- `GET /api/events?campus=` — that campus's events plus church-wide ones. `GET /api/events/all?campus=` — one campus, or church-wide only. -- `GET /api/stats/overview?campus=`. -- `PUT /api/users/profile` takes `homeCampusId`; `GET` returns it. - -## Kids check-in - -Kids check-in (1.45.0, `src/utils/kids.js`). An event has it when `kidsCheckIn` is true with a -`kidsOptionId` (main ticket covering the whole event) and `kidsRoomSetId` (allocation set whose -groups are the rooms; groups take `minAge`, `maxAge`, `ratio` on `POST /api/allocations/sets/:id/groups` -and `PUT /api/allocations/groups/:id`). The **occasion** is today's session on a multi-session event, -or the day (`YYYY-MM-DD`, `APP_TIMEZONE`) on a single-date one; pickup codes are per family per occasion. -Allergies, medical and custody notes are stored encrypted. Staff routes are campus-scoped. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/kids/me` | user | `{ family, qrToken, codes, pages }` — my family (or null), live pickup codes (`{ code, qr, event, children }`) and pages from the last 24 h | -| POST / PUT / DELETE | `/api/kids/me` | user | Start my family `{ name }` / rename it / leave it (the last parent leaving deletes it and its children) | -| POST, PUT, DELETE | `/api/kids/me/children[/:id]` | user | `{ firstName, lastName?, dateOfBirth?, gender?, allergies?, medicalNotes?, custodyNotes? }`; custody changes audited as `kids_custody_notes_changed` | -| POST, PUT, DELETE | `/api/kids/me/adults[/:id]` | user | Authorised adults `{ name, phone?, relationship? }` (up to 10) | -| GET | `/api/kids/setup-events` | supervisor+ | Upcoming events for the setup page | -| GET / PUT | `/api/kids/events/:eventId/settings` | supervisor+ | `{ enabled?, optionId?, roomSetId? }` — `'new'` makes a free "Kids check-in" main ticket or a "Kids rooms" set; switching on needs both. Audited as `kids_settings_updated`; PUT needs a campus the supervisor manages | -| GET | `/api/kids/events` | staff+ | Events with kids check-in, from the last week on, with their sessions | -| GET | `/api/kids/events/:eventId/board?sessionId=&log=1` | staff+ | `{ event, occasion, sessionId, rooms, checkIns, alerts }`. Rooms carry `children`, `leaders`, `leadersNeeded`, `full`, `overRatio`; check-ins carry `code`, allergies, medical and custody notes, the family's parents and adults, and `sticker`. `log=1` writes the access log (`kids_rooms`) | -| GET | `/api/kids/events/:eventId/families?q=` | staff+ | Families by family, child or parent name, email or phone (min. 2 characters) | -| POST | `/api/kids/events/:eventId/families` | staff+ | `{ name?, parent: { name, phone?, email? }, children? }` — the parent's account is matched by email/phone or created inactive; an existing family is reused | -| GET | `/api/kids/events/:eventId/families/qr/:token` | staff+ | The family for a family QR (`FAMILY-`) | -| GET | `/api/kids/events/:eventId/families/:familyId` | staff+ | One family | -| POST | `/api/kids/events/:eventId/families/:familyId/parents` | staff+ | Add a parent (409 if they're in another family) | -| POST, PUT | `/api/kids/events/:eventId/families/:familyId/children[/:childId]` | staff+ | Add/change a child — custody notes only from supervisors and admins | -| POST | `/api/kids/events/:eventId/families/:familyId/adults` | staff+ | Add an authorised adult | -| POST | `/api/kids/events/:eventId/check-in` | staff+ | `{ familyId, sessionId?, children: [{ childId, roomId? }], sendToAdultId? }` → `201 { code, qr, occasion, family, checkIns: [{ id, name, firstName, room, already, sticker }] }`. Messages the parents (and the adult) | -| GET | `/api/kids/events/:eventId/code/:code?sessionId=` | staff+ | `{ code, found, family, children }` for a pickup code (`KIDS-` prefix and case ignored) | -| POST | `/api/kids/events/:eventId/check-out` | staff+ | `{ code, checkInIds?, collectedBy, roomId?, sessionId? }` → `{ checkedOut }`. `404 WRONG_CODE` (alert + audit `kids_wrong_code`) or `404 NOTHING_TO_COLLECT` | -| POST | `/api/kids/check-ins/:id/override` | staff+ | `{ collectedBy, reason }` — check out without the code; audited as `kids_checkout_override` | -| POST | `/api/kids/check-ins/:id/page` | staff+ | `{ message? }` → `{ sent: ['whatsapp'\|'email'], text }` — "Please come to the … room" | -| PUT | `/api/kids/check-ins/:id/room` | staff+ | `{ roomId }` | -| POST | `/api/kids/events/:eventId/duty` | staff+ | `{ roomId, on, sessionId? }` — "I'm on duty" (one room at a time) | -| POST | `/api/kids/alerts/:id/resolve` | staff+ | Mark an alert dealt with | -| GET | `/api/kids/events/:eventId/offline?deviceId=&sessionId=` | staff+ | Offline snapshot: board plus `families` and `codes` (20 reserved for the device). Access log `kids_offline` | -| POST | `/api/kids/events/:eventId/sync` | staff+ | `{ deviceId, occasion, checkIns: [{ clientId, familyId, childId, roomId, code, at }], checkOuts: [{ clientId, collectedBy, at }] }` → `{ checkedIn, checkedOut, conflicts }`; idempotent by `clientId`; audited as `kids_offline_sync` | - -Since 1.46.0 board rooms also carry `rostered: [{ userId, name, checkedIn }]` (volunteers on a serving -role linked to the room); checked-in ones are counted in `leaders`. - -## Saved filters - -Per person, on list pages `registrations`, `users`, `events`, `reports` (staff+; your own only — someone -else's id answers 404). - -| Method | Path | Description | -|--------|------|-------------| -| GET | `/api/saved-filters?page=` | Mine for the page, default first | -| POST | `/api/saved-filters` | `{ page, name, params, isDefault? }` — params: strings, numbers, booleans, lists of strings (≤ 4 KB); same name replaces; ≤ 30 per page | -| PUT | `/api/saved-filters/:id` | `{ name?, isDefault? }` (one default per page) | -| DELETE | `/api/saved-filters/:id` | Delete | - -## Bulk actions on registrations - -`POST /api/registrations/bulk` (supervisor+): `{ action, registrationIds: [...] (≤ 500), ...params }` → -`{ action, done, skipped, failed, results: [{ id, ok, skipped?, message }] }`. Every id is campus-checked. - -| action | params | What happens | -|--------|--------|--------------| -| `markPaid` | `method`: cash/eft/card/other, `paidAt?` | A payment for what's still owed (as `POST /api/payments`); refused in licence read-only mode | -| `cancel` | — | As cancelling one registration (coupons released, waitlist offered); no refund | -| `moveOption` | `fromOptionId`, `toOptionId` (same event) | The lines, tickets and attendees move to the new ticket, repriced; status recalculated; places checked; refused in read-only mode | -| `allocate` | `setId`, `groupId` | Each named person placed, as `PUT /api/allocations/sets/:id/assignments` | -| `message` | `channel`: email/whatsapp, `subject` (email), `text` | Per event, as `POST /api/events/:id/email-attendees` / `whatsapp-attendees` with `filter.registrationIds`, kind "update" | - -## Dashboard and command palette - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/dashboard/today` | staff+ | `{ events: [{ id, title, startsAt, endsAt, sessionLabel, places, checkedIn, kidsIn, volunteers }], money: { today, todayCount, week } \| null, pending: [{ key, label, count, href, tone }] }` — money and pending for supervisors/admins; campus-scoped | -| GET | `/api/dashboard/search?q=` | staff+ | `{ results: [{ type: event\|payment\|person\|registration, id, title, subtitle, href }] }` — payments by amount for supervisors, people and registrations for admins | - -## Event series - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/series` | supervisor+ | Every series with `followers`, `eventCount` and its events (campus-scoped: their campuses' events only) | -| POST | `/api/series` | supervisor+ | Create: `{ name, slug?, description?, picture? }` (slug made from the name). 409 when the slug is taken | -| PUT | `/api/series/:id` | supervisor+ | Change any of those fields | -| DELETE | `/api/series/:id` | admin | Delete; events stay without a series, followers dropped | -| GET | `/api/series/by-slug/:slug` | public | `{ id, name, slug, description, picture, upcoming, past, following }` — public events only | -| POST / DELETE | `/api/series/:id/follow` | user | Follow / unfollow | -| GET | `/api/series/:id/compare` | supervisor+ | Year on year: `{ series, events: [{ eventId, title, startDate, registrations, tickets, income, checkedIn, attendanceRate, sessions, change }] }`, oldest first; `change` is % against the event before. Scoped staff: their campuses' events only | - -Events take `seriesId` (null = none) on create and update; `GET /api/events?series=` lists one -series; `GET /api/events/:id` includes `series` and `nextInSeries`. The `series` job emails -followers once per event (`Event.seriesAnnouncedAt`) when it is public and hasn't started. - -## Outbound webhooks - -Admin only. Endpoints receive `POST` JSON `{ id: "evt_…", type, createdAt, data }` with headers -`X-CrossEvents-Event`, `X-CrossEvents-Delivery` and `X-CrossEvents-Signature: t=,v1=` -where v1 = HMAC-SHA256(secret, `.`). Answer 2xx within 10 s; anything else is retried -(1 min, 5 min, 30 min, 2 h, 12 h). The same `id` can arrive more than once — de-duplicate on it. - -| Type | `data` | -|------|--------| -| `registration.created` / `.paid` / `.cancelled` | `registration { id, status, totalDue, amountPaid, items[], seasonPassPurchaseId }`, `event`, `person` | -| `payment.received` / `payment.refunded` | `payment { id, amount, method, provider, isDonation, registrationId }`, `event`, `person` | -| `ticket.checked_in` | `checkIn { id, scannedAt, people, manual, offline, session }`, `ticket`, `event`, `person` | -| `user.created` | `person { id, name, email, phone, role, createdAt }` | -| `event.published` | `event { id, title, description, startDate, endDate, location, price, goLiveAt, url, campus, series }` | -| `webhook.test` | `{ message }` (Send test) | - -| Method | Path | Description | -|--------|------|-------------| -| GET | `/api/outbound-webhooks` | Endpoints with last-week counts, and the event types (each with an `example` of its `data`) | -| POST | `/api/outbound-webhooks` | `{ name, url, events }` → endpoint plus `secret` (only here) | -| PUT | `/api/outbound-webhooks/:id` | `{ name?, url?, events?, isActive? }` | -| DELETE | `/api/outbound-webhooks/:id` | Endpoint and its deliveries | -| POST | `/api/outbound-webhooks/:id/rotate-secret` | `{ secret }` | -| POST | `/api/outbound-webhooks/:id/test` | `{ status, statusCode, error }` | -| GET | `/api/outbound-webhooks/:id/deliveries?status=&limit=&before=` | Delivery log, newest first; `before` (a `createdAt`) loads older ones | -| POST | `/api/outbound-webhooks/deliveries/:id/resend` | Send again now | - -## Season passes - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/season-passes?seriesId=` | supervisor+ | Passes with events, normal prices, `share` per event, `sold`, `unpaid` | -| POST | `/api/season-passes` | supervisor+ | `{ seriesId, name, description?, price, saleEndsAt?, isActive?, items: [{ eventId, eventOptionId, variantId? }] }` | -| PUT | `/api/season-passes/:id` | supervisor+ | Change it; events and price only while unsold (409) | -| DELETE | `/api/season-passes/:id` | supervisor+ | Only while unsold | -| POST | `/api/season-passes/:id/buy` | user | `{ quantity }` → `{ purchaseId, total, paid, redirectUrl, message }`; 409 when not on sale or too few places | -| POST | `/api/season-passes/purchases/:id/checkout` | user (buyer) | A new checkout for what is still owed | -| GET | `/api/season-passes/mine` | user | My purchases with their registrations | - -A purchase creates one `Registration` per event (`seasonPassPurchaseId`), its line priced at the -event's share. The checkout's metadata is `{ type: 'season_pass', purchaseId }`; the webhook records -one `Payment` per registration (`seasonPassPurchaseId`; only the first carries `externalId`). -`PUT /api/registrations/:id/options` and `POST /api/registrations/:id/coupon` answer 409 for pass -registrations. - -## Volunteer rosters - -Volunteer rosters (1.46.0, `src/utils/volunteers.js`). A **serving role** belongs to an event, or to -one session of a multi-session event (`sessionId` required there), with `needed` people and optional -`startsAt`/`endsAt` (default: the session's or event's times). A **slot** is a person on a role; -nobody can hold two slots whose shifts overlap (`409 SHIFT_CLASH`). When `Event.volunteerOptionId` -is set, each volunteer without a ticket gets a free place on it (cancelled when they leave, moved -with a swap). `volunteerOptionId` and `kidsOptionId` are left out of public event pages -(`GET /api/events`, `GET /api/events/:id` for non-staff) and refused on public registration. Staff -routes are campus-scoped. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/volunteers/me` | user | `{ slots, cover, events }` — my shifts (upcoming and the last week; `canCheckIn`, `swapId`, `hasTicket`), open cover requests I could take, and public events with roles | -| GET | `/api/volunteers/events/:eventId` | user | `{ event, sessions, roles, totals }` — each role with `shift`, `needed`, `filled`, `full`, `mine`, `coverNeeded` (no names) | -| POST | `/api/volunteers/roles/:id/sign-up` | user | `201 { slotId, ticket }`; `409 ROLE_FULL`, `409 SHIFT_CLASH`. Blocked in licence read-only mode | -| DELETE | `/api/volunteers/slots/:id` | user | Withdraw (not after check-in or once the shift is over); the event's notify recipients are emailed | -| POST | `/api/volunteers/slots/:id/swap` | user | `{ note? }` → `{ swapId }` — "can't make it"; the event's other volunteers are told | -| DELETE | `/api/volunteers/swaps/:id` | user | Cancel my cover request | -| POST | `/api/volunteers/swaps/:id/accept` | user | Take the place over at once → `{ slotId, role, event }`; `409 SWAP_CLOSED` if someone was first. Both volunteers and the event's notify recipients are told | -| POST | `/api/volunteers/check-in` | user | `{ qr }` (`SERVE-`) → `{ event, checkedIn: [{ role, kidsRoom }], already }` for my shifts on today. `404 BAD_QR`, `404 NOT_ROSTERED`, `400 NOT_TODAY`. A kids-room role starts a `KidsRoomDuty` (`fromRoster`) | -| GET | `/api/volunteers/manage/events?all=1` | staff+ | Events with roles from the last 30 days on; `all=1` (supervisors) every upcoming event | -| GET | `/api/volunteers/manage/events/:eventId?log=1` | staff+ | The roster with `volunteers: [{ slotId, name, phone, email, checkedInAt, checkInMethod, swapOpen, hasTicket }]` per role, and `totals: { needed, filled, checkedIn, fillRate }`. `log=1` writes the access log (`volunteer_roster`) | -| GET | `/api/volunteers/manage/events/:eventId/qr` | staff+ | `{ token, qr }` — the check-in QR value (the page encodes `/serve/check-in?code=`) | -| POST | `/api/volunteers/manage/slots/:id/check-in` | staff+ | `{ undo? }` — check in by hand (or undo, which ends rostered kids-room duty). Audited as `volunteer_checked_in_manual` | -| GET / PUT | `/api/volunteers/manage/events/:eventId/settings` | supervisor+ | `{ optionId }` — the volunteer ticket: a main ticket covering the whole event, `'new'` for a free "Volunteer" ticket, `null` = off (default). Also returns the event's `kidsRooms`. Audited as `volunteer_settings_updated` | -| POST | `/api/volunteers/manage/events/:eventId/roles` | supervisor+ | `{ name, needed, sessionId?, startsAt?, endsAt?, description?, kidsRoomId? }`. Audited as `volunteer_roles_changed`; blocked in read-only mode | -| PUT / DELETE | `/api/volunteers/manage/roles/:id` | supervisor+ | Change / delete a role (delete refused once someone checked in; its volunteers are told) | -| POST | `/api/volunteers/manage/roles/:id/assign` | supervisor+ | `{ userId }` — allowed beyond `needed`; the person is told. Audited as `volunteer_assigned` | -| DELETE | `/api/volunteers/manage/slots/:id` | supervisor+ | Take someone off (not after check-in); they're told. Audited as `volunteer_removed` | -| GET | `/api/volunteers/manage/hours?eventId=&from=&to=` | supervisor+ | `[{ userId, name, shifts, hours, events }]` — checked-in shifts × shift length, most first | - -## Webhooks - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/webhooks/payfast` | PayFast ITN | Form-encoded. Checked as PayFast requires: signature (every posted field + passphrase), sender is a PayFast host (`PAYFAST_SKIP_IP_CHECK=true` turns this off for tunnels; behind a proxy set `TRUST_PROXY`), PayFast answers VALID at `/eng/query/validate`, and `amount_gross` equals the checkout (otherwise held for review with a `note`). `COMPLETE` records the payment (`provider: "payfast"`) | -| POST | `/api/webhooks/yoco` | HMAC-verified | Yoco payment webhook — verifies the `webhook-signature` header (src/payments/providers/yoco.js), creates `Payment` (`provider: "yoco"`) + `ProviderTransaction`, updates registration status, generates tickets (src/payments/webhook.js). Processed even when Yoco is switched off, so checkouts already started complete | -| POST | `/api/whatsapp/webhook?secret=…` | secret in URL | WAWP events (the URL to paste into WAWP is on `GET /api/whatsapp/config` as `webhookUrl`). `session.status` FAILED → automatic session recovery (works without the secret). `message` → a STOP/unsubscribe reply turns off WhatsApp news for that number and sends a confirmation; only with a matching secret, since WAWP doesn't sign webhooks. Senders identified only by a WhatsApp LID (no phone number) are ignored | -| POST | `/api/webhooks/whatsapp` | — | Old placeholder, does nothing — use `/api/whatsapp/webhook` | - ---- - -## Settings - -Runtime configuration stored in the `AppSetting` table. Sensitive values (SMTP credentials, Yoco secrets) are stored AES-256-GCM encrypted. Yoco secrets are never returned by `/api/settings/all` and can't be written through `PUT /api/settings`; use `/api/yoco` below. - -For what each individual setting key defaults to when it's never been saved, see [`SETTINGS.md`](../SETTINGS.md) at the repo root. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/settings` | public | Public settings (org name, tagline, colour, logo, legal keys) | -| GET | `/api/settings/all` | admin | All settings — `smtp_pass` masked as `••••••••`, `smtp_user` decrypted | -| GET | `/api/settings/needs-setup` | public | `{ needsSetup: bool }` — true until setup wizard completes | -| PUT | `/api/settings` | admin | Upsert settings; `smtp_user`/`smtp_pass` encrypted before storage; sending `••••••••` for `smtp_pass` keeps existing value | -| POST | `/api/settings/test-smtp` | admin | Test SMTP with provided credentials; sends real test email to admin on success. The admin JWT returned by `POST /api/setup/register` also qualifies during the setup wizard. | - -## Yoco - -Managed from Admin → Site Settings → Payments. - -PayFast: `GET /api/payfast/config` (admin) → `{ merchantId, merchantKey, passphraseMasked, hasPassphrase, mode, notifyUrl, notifyUrlProblem, configured }`; `PUT /api/payfast/config` (admin) `{ merchantId?, merchantKey?, passphrase?, mode? }` ('' clears; the passphrase is stored encrypted; audit logged as `payfast_config_updated`); `POST /api/payfast/test` (admin) checks the saved settings with a signed PayFast API ping. - -Every checkout is stored as a `ProviderCheckout` (amount, metadata, request): `POST /api/payments/checkout` returns `checkoutId` (ours) and a `redirectUrl` — the provider's page, or `/pay/` when the payer must choose or a form has to be posted. Registrations keep that `checkoutId`; webhooks find the checkout by our id or the provider's. `YOCO_SECRET_KEY` / `YOCO_WEBHOOK_SECRET` in `.env` are fallbacks used only when the database has no value. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| GET | `/api/yoco/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 | `/api/yoco/config` | admin | Save `secretKey` and/or `webhookSecret` (AES-256-GCM encrypted). A new key is checked with Yoco first; `''` clears a value | -| GET | `/api/yoco/webhooks` | admin | Webhooks on the Yoco account, flagged `isActive` (its secret is the stored one) and `pointsHere` | -| POST | `/api/yoco/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 | `/api/yoco/webhooks/:id` | admin | Delete a webhook at Yoco; clears the stored secret if it was the active one | - -### POST /api/settings/test-smtp -```json -{ - "host": "smtp.office365.com", - "port": 587, - "secure": false, - "user": "noreply@yourchurch.org", - "pass": "app-password-here", - "from": "noreply@yourchurch.org" -} -``` - -**Success (200):** -```json -{ "message": "SMTP connection verified — a test email has been sent to admin@yourchurch.org" } -``` - -**Failure (400):** -```json -{ - "message": "Authentication failed — check your SMTP username and password.", - "raw": "530 5.7.57 Client not authenticated to send mail. [JN3P275CA0121...]" -} -``` - -The `message` field is always a human-readable sentence. The `raw` field is included on errors only and contains the original SMTP error for debugging. Error code 530 (Microsoft "Client not authenticated") maps to the authentication-failure message. - ---- - -## Setup - -One-time first-run wizard. Both endpoints are blocked once any user exists and setup is complete. - -| Method | Path | Auth | Description | -|--------|------|------|-------------| -| POST | `/api/setup/register` | public (one-time) | Create the first admin account; returns a short-lived setup JWT | -| POST | `/api/setup` | setup token or admin | Save initial site settings (org name, branding, SMTP) | - ---- - -## Static Files - -| Path | Description | -|------|-------------| -| `/uploads/events/*` | Event cover images | -| `/uploads/branding/*` | Site logo | -| `/uploads/event-files/*` | Event attachments (PDFs, docs, etc.) | -| `/uploads/tickets-temp/*` | Temporarily hosted ticket PDFs for WhatsApp delivery (auto-deleted after 5 min) | - ---- - -## Auth error responses - -| Status | Body | Meaning | -|--------|------|---------| -| 401 | `{ message: "Not authorised, no token" }` | Missing or malformed `Authorization` header | -| 401 | `{ message: "Not authorised, token failed" }` | Invalid or expired JWT | -| 401 | `{ message: "Session has been revoked" }` | Token version mismatch (sessions revoked) | -| 403 | `{ message: "Not authorised as an admin" }` | Insufficient role | - ---- - -*For full interactive docs with expandable examples visit `GET /docs?token=` on the running backend.* \ No newline at end of file +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`). diff --git a/apps/events/backend/package-lock.json b/apps/events/backend/package-lock.json index 6416379..48899ee 100644 --- a/apps/events/backend/package-lock.json +++ b/apps/events/backend/package-lock.json @@ -1,15 +1,16 @@ { "name": "event-management-backend", - "version": "1.52.3", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "event-management-backend", - "version": "1.52.3", + "version": "2.0.0", "hasInstallScript": true, "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", @@ -23,7 +24,6 @@ "ics": "^3.12.0", "jsonwebtoken": "^9.0.3", "multer": "^2.5.0", - "node-fetch": "^2.7.0", "nodemailer": "^10.3.0", "pdfkit": "^0.17.1", "pg-boss": "^11.1.2", @@ -1729,6 +1729,238 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@node-rs/argon2": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2/-/argon2-2.2.2.tgz", + "integrity": "sha512-NtdlPPWtR5U4BxX5EGJYza+UklNaoWORmkaKCMqf/nyKeXWKVwNt8KfQoRpNT7OB1DcEwmePafO4wZyW+sbfCQ==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@node-rs/argon2-android-arm-eabi": "2.2.2", + "@node-rs/argon2-android-arm64": "2.2.2", + "@node-rs/argon2-darwin-arm64": "2.2.2", + "@node-rs/argon2-darwin-x64": "2.2.2", + "@node-rs/argon2-freebsd-x64": "2.2.2", + "@node-rs/argon2-linux-arm-gnueabihf": "2.2.2", + "@node-rs/argon2-linux-arm64-gnu": "2.2.2", + "@node-rs/argon2-linux-arm64-musl": "2.2.2", + "@node-rs/argon2-linux-x64-gnu": "2.2.2", + "@node-rs/argon2-linux-x64-musl": "2.2.2", + "@node-rs/argon2-win32-arm64-msvc": "2.2.2", + "@node-rs/argon2-win32-ia32-msvc": "2.2.2", + "@node-rs/argon2-win32-x64-msvc": "2.2.2" + } + }, + "node_modules/@node-rs/argon2-android-arm-eabi": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm-eabi/-/argon2-android-arm-eabi-2.2.2.tgz", + "integrity": "sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-android-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-android-arm64/-/argon2-android-arm64-2.2.2.tgz", + "integrity": "sha512-dpMYIoxhN/wY6hFH+3MM5kQErcH3luMekkszbkDF3NKqhB1kFRntkOLDpFY87oItBSHJrsoYkXC3vBRhjYoCjQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-darwin-arm64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-arm64/-/argon2-darwin-arm64-2.2.2.tgz", + "integrity": "sha512-vxVAXcIG0iiHizkCuImmzVhOFsRnU4Z79xiOxdISLyI+QhOAWbbTaVSXw0PNfThB3zAdkzzDJ/WWu52Hs/qHGg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-darwin-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-darwin-x64/-/argon2-darwin-x64-2.2.2.tgz", + "integrity": "sha512-r7GbSFpFZZ9EAV9cvIm9prUjOupK7QQXTyP+FJ6bWSMq0h+qRDBlUOXQXduDIIrLEGoBVelixKUtf4ksZ0ljoQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-freebsd-x64": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-freebsd-x64/-/argon2-freebsd-x64-2.2.2.tgz", + "integrity": "sha512-AmWxDSmQgprilD6NX3jmxCgcDvWAW7kGJnnWQo+0qav6nfMXdPZYgSezK/skmw1GBWipr4yZMIUzpeNHnVpMxg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm-gnueabihf": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm-gnueabihf/-/argon2-linux-arm-gnueabihf-2.2.2.tgz", + "integrity": "sha512-M1gnPBTr9GFeEUWkQ53qCJeTsX03C3kcUeHnDbN7dU2xkI58wMP4Z1sEBN7WmKJ/fTHYEgti4truz7r4A82DLg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm64-gnu": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-gnu/-/argon2-linux-arm64-gnu-2.2.2.tgz", + "integrity": "sha512-4CYDlIdITlLSVcAXYUtEoGUahRaayPXM+4Rcfg3BZx9WGi6UB8HUycs6GNMTPYXV5kVXCpyE2u1HmYUpgmIzOQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-arm64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-arm64-musl/-/argon2-linux-arm64-musl-2.2.2.tgz", + "integrity": "sha512-FYlfj3XgQ1xrx6HzQbKbUcKiYMG/3iSi/X81KyhHaItTJ7vZlMwrbVLl9yqDmvotKUF6VjrhrlZ8KRbbzchseA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-x64-gnu": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-gnu/-/argon2-linux-x64-gnu-2.2.2.tgz", + "integrity": "sha512-ULXLs8UFYZANlwiROM7AeccxZndr2Xk3IstADq3jAUhnwV2W75mxMBTABUZ+7AdKRhPLOrxU77OgnMWlDkYJQg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-linux-x64-musl": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-linux-x64-musl/-/argon2-linux-x64-musl-2.2.2.tgz", + "integrity": "sha512-zgjIwc9TyGodn62vGc+36DGwFqVV5e7L8Ptd2FQWuBxe5aFrcFxvtDGn1/qfYwoHLv09utgtR+RBAPCXepWG3Q==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-arm64-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-arm64-msvc/-/argon2-win32-arm64-msvc-2.2.2.tgz", + "integrity": "sha512-3nLhvLie/ec5xfxUBXXqGMb7oGeqF+YXrcGckqaTaGkPtOBozho0Kh2IuP/zi9BcOriirTG2LW3gtIOfpuh+mQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-ia32-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-ia32-msvc/-/argon2-win32-ia32-msvc-2.2.2.tgz", + "integrity": "sha512-6RJKD6cFl7UeiYJLjRsXPywVXSFSaSDdr6xGpztNDV31QHCEecWnsnNmKxzi4gVpln2F9XeWEtIgM4Nqw1hLbA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/argon2-win32-x64-msvc": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@node-rs/argon2-win32-x64-msvc/-/argon2-win32-x64-msvc-2.2.2.tgz", + "integrity": "sha512-dQOO9S4QKBaVul0Uyk/2quJc/OBeHNZRJP+GZZTy1A5kYIaAfIJGHUYLY6oFoAlcuLIkdFouLaHX3fCl8tZm/w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, "node_modules/@opentelemetry/api": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", @@ -7492,26 +7724,6 @@ "dev": true, "license": "MIT" }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -9096,12 +9308,6 @@ "integrity": "sha512-0a5EOkAUp8D4moMi2W8ZF8jcga7BgZd91O/yabJCFY8az+XSzeGyTKs0Aoo897iV1Nj6guFq8orWDS96z91oGg==", "license": "MIT" }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" - }, "node_modules/ts-jest": { "version": "29.4.15", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.15.tgz", @@ -9421,22 +9627,6 @@ "node": ">= 0.8" } }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/apps/events/backend/package.json b/apps/events/backend/package.json index 602a79c..3a6e3a2 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -1,6 +1,6 @@ { "name": "event-management-backend", - "version": "1.52.3", + "version": "2.0.0", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { @@ -17,10 +17,12 @@ "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" + "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", @@ -34,7 +36,6 @@ "ics": "^3.12.0", "jsonwebtoken": "^9.0.3", "multer": "^2.5.0", - "node-fetch": "^2.7.0", "nodemailer": "^10.3.0", "pdfkit": "^0.17.1", "pg-boss": "^11.1.2", diff --git a/apps/events/backend/prisma/migrations/20261030120000_ai_helpers/migration.sql b/apps/events/backend/prisma/migrations/20261030120000_ai_helpers/migration.sql new file mode 100644 index 0000000..9376809 --- /dev/null +++ b/apps/events/backend/prisma/migrations/20261030120000_ai_helpers/migration.sql @@ -0,0 +1,28 @@ +-- AlterEnum +ALTER TYPE "AdminAuditAction" ADD VALUE 'ai_settings_changed'; + +-- CreateTable +CREATE TABLE "AiCall" ( + "id" TEXT NOT NULL, + "userId" TEXT, + "helper" TEXT NOT NULL, + "outcome" TEXT NOT NULL, + "chargedCents" DOUBLE PRECISION NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AiCall_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "AiCall_createdAt_idx" ON "AiCall"("createdAt"); + +-- CreateIndex +CREATE INDEX "AiCall_userId_createdAt_idx" ON "AiCall"("userId", "createdAt"); + +-- AddForeignKey +ALTER TABLE "AiCall" ADD CONSTRAINT "AiCall_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + + +-- 2.0 AI helpers: Anthropic in the operator register, off until the site uses AI. +INSERT INTO "Operator" ("id", "name", "purpose", "dataShared", "location", "website", "active", "order", "updatedAt") VALUES + (gen_random_uuid()::text, 'Anthropic (Claude), through the software provider''s Hub', 'AI helpers for staff: drafting events and messages, improving text, summarising reports and feedback', 'The text a staff member asks to draft or improve, report figures, and feedback comments with names and contact details removed. Not kept by the software provider; Anthropic''s commercial terms apply', 'United States', 'https://www.anthropic.com/legal/privacy', false, 9, CURRENT_TIMESTAMP); diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index 9a8e954..b536537 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -165,6 +165,7 @@ model User { seriesFollows SeriesFollow[] seasonPassPurchases SeasonPassPurchase[] savedFilters SavedFilter[] + aiCalls AiCall[] swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom") swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo") @@ -833,6 +834,7 @@ enum AdminAuditAction { season_pass_changed webhook_endpoint_changed registrations_bulk + ai_settings_changed } // Append-only audit trail for admin/supervisor-initiated actions with money or @@ -2328,3 +2330,21 @@ model SavedFilter { @@unique([userId, page, name]) @@index([userId, page]) } + +/// One AI helper call (2.0). The Hub meters the money; this copy is for Site settings → AI (use +/// per person, per helper and per day) and per-person daily limits. No prompt or answer text is +/// kept. `userId` is cleared when the account is anonymised; rows go after 13 months. +model AiCall { + id String @id @default(uuid()) + userId String? + helper String + // ok, refused, incomplete, failed, cap_reached, unavailable + outcome String + // What the church was charged, in cents (fractions of a cent). + chargedCents Float @default(0) + createdAt DateTime @default(now()) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + + @@index([createdAt]) + @@index([userId, createdAt]) +} diff --git a/apps/events/backend/scripts/ai-eval.ts b/apps/events/backend/scripts/ai-eval.ts new file mode 100644 index 0000000..42b8bc1 --- /dev/null +++ b/apps/events/backend/scripts/ai-eval.ts @@ -0,0 +1,171 @@ +/** + * The AI helpers' eval set (roadmap §15): `npm run ai:eval` in backend/. + * + * Runs fixed examples of all five helpers through this site's real Hub connection (so the site must + * be connected and its licence must have an AI allowance), checks the facts that matter + * automatically, and prints every answer for a person to read. Run it after changing a helper's + * instructions or the model on the Hub, and compare with the last run. It costs about R1 a run + * with Claude Sonnet 5.5; the calls count against this site's allowance. + * + * The examples come from the October 2026 model trial; the inputs are made up and hold no + * personal information. + */ +import 'dotenv/config'; +import { prisma } from '../src/v2/legacy'; +import { draftEvent, summariseReport, draftMessage, summariseFeedback, improveText } from '../src/ai/helpers'; + +type Check = [label: string, ok: boolean]; +type Case = { name: string; run: (userId: string) => Promise<{ output: unknown; checks: Check[] }> }; + +const has = (text: unknown, re: RegExp) => re.test(JSON.stringify(text)); +const near = (n: number, target: number, give = 1) => Math.abs(n - target) <= give; + +const CAMP_NOTES = 'Youth camp for grades 8–12, Fri 14 March 18:00 to Sun 16 March 14:00 at Camp Wartburg near Pietermaritzburg. 60 places. R450 per person, R400 if they book by 31 January. Parents must give consent. Theme "Rooted" (Colossians 2:7). Costs: venue R180 per person per night including meals, bus hire R6 500 return, speaker gift R1 000, T-shirts R95 each. Friday evening worship, Saturday sessions morning and evening with sport in the afternoon, Sunday morning service before we leave. Bring a sleeping bag, Bible and a torch.'; + +const FEEDBACK_COMMENTS = [ + 'The keynote on Saturday morning was exactly what I needed this year.', 'Could not hear a thing in Hall B, the sound kept cutting out.', + 'Lunch queue took 40 minutes, we missed the start of the afternoon session.', 'Loved the worship, so good to be together again.', + 'Breakouts were too short, just as it got deep we had to leave.', 'Check-in with the QR code was so quick, well done.', + 'Parking was a nightmare, we parked on the road and walked.', 'Please have childcare next year, I almost could not come.', + 'Speaker in the parenting breakout was brilliant.', 'Sound in Hall B again, the mic was crackling the whole time.', + 'Food ran out of vegetarian options by the time we got there.', 'The whole day felt so well organised.', + 'More time for breakouts please, and maybe fewer of them.', 'Lunch took forever.', 'Loved the gift bags!', + 'Hall A was freezing, the aircon was too cold.', 'The app reminders the day before were really helpful.', + 'Would love a longer Q&A with the main speaker.', 'Queue for lunch was very long, maybe stagger the breakouts?', + 'Parking marshals would help a lot.', 'Worship team was amazing.', 'Childcare or a kids programme would let young moms come.', + 'Some of the slides were hard to read from the back.', 'Best conference yet, thank you to the whole team.', + 'I would pay a bit more for a better lunch.', 'Hall B sound please fix it.', +]; + +const CASES: Case[] = [ + { + name: 'Draft an event — full notes with costs', + async run(userId) { + const r = await draftEvent(userId, CAMP_NOTES); + const d = r.draft; + return { + output: r, + checks: [ + ['price R450, early bird R400 until 31 January', d.ticketOptions[0]?.priceRand === 450 && d.ticketOptions[0]?.earlyBirdPriceRand === 400 && d.ticketOptions[0]?.earlyBirdUntil.endsWith('-01-31')], + ['60 places, parental consent', d.capacity === 60 && d.needsParentalConsent], + ['budget R34 800, break-even 78', r.totalCostRand === 34800 && r.breakEvenPlaces === 78], + ['warns the camp is short even when full', r.warnings.some(w => w.includes('short'))], + ['times not in the notes left empty (only 18:00 and 14:00 given)', d.sessions.every(s => !s.startTime || s.startTime === '18:00')], + ], + }; + }, + }, + { + name: 'Summarise a report — a month of payments', + async run(userId) { + const { summary } = await summariseReport(userId, { + reportKey: 'revenue', title: 'Revenue summary — October 2026 (September for comparison)', + columns: ['Method', 'October payments', 'October amount', 'September payments', 'September amount'], + rows: [['Card', 96, 'R42 300', 81, 'R35 100'], ['EFT', 14, 'R18 000', 17, 'R21 500'], ['Cash at the door', 31, 'R6 250', 22, 'R4 100'], ['Refunds', 4, 'R2 700', 2, 'R450']], + stats: [{ label: 'Card payments waiting for the provider over 2 days', value: '3 (R1 350)' }], + }); + return { + output: summary, + checks: [ + ['October total R66 550', has(summary, /66[\s ]?550/)], + ['up on September (R60 700)', has(summary, /60[\s ]?700|5[\s ]?850|9[.,]6/)], + ['the 3 waiting card payments need checking', has(summary.watchOut, /1[\s ]?350|3 (online |card )?payments/i)], + ], + }; + }, + }, + { + name: 'Summarise feedback — women\'s conference', + async run(userId) { + const { summary } = await summariseFeedback(userId, { + event: { title: 'Women\'s Conference 2026' }, responses: 112, invited: 186, + questions: [ + { label: 'Overall', type: 'rating', answered: 112, average: 4.4 }, { label: 'Venue', type: 'rating', answered: 110, average: 3.9 }, + { label: 'Food', type: 'rating', answered: 108, average: 3.6 }, { label: 'Comments', type: 'text', answered: FEEDBACK_COMMENTS.length, texts: FEEDBACK_COMMENTS }, + ], + }); + // A theme may be split (e.g. "lunch queues" and "vegetarian food"): add up every match. + const count = (re: RegExp) => summary.improve.filter(t => re.test(t.theme)).reduce((n, t) => n + t.mentions, 0); + return { + output: summary, + checks: [ + ['lunch/food raised by about 5', near(count(/lunch|food|queue/i), 5)], + ['Hall B sound raised by 3', near(count(/sound|hall b/i), 3, 0)], + ['quotes copied exactly', summary.quotes.every(q => FEEDBACK_COMMENTS.includes(q))], + ], + }; + }, + }, + { + name: 'Draft a message — WhatsApp reminder', + async run(userId) { + const { message } = await draftMessage(userId, { channel: 'whatsapp', note: 'Youth camp this weekend: remind them to bring a sleeping bag; the bus leaves at 7:30 on Friday from the church car park.' }); + return { + output: message, + checks: [ + ['uses {{name}}', message.body.includes('{{name}}')], + ['keeps 7:30, sleeping bag, car park', /7:30/.test(message.body) && /sleeping bag/i.test(message.body) && /car park/i.test(message.body)], + ['no "reminda" (seen with Haiku)', !/reminda/i.test(message.body)], + ['no event placeholders without an event', !/\{\{event\./.test(message.body)], + ], + }; + }, + }, + { + name: 'Draft a message — email about a venue change', + async run(userId) { + const { message } = await draftMessage(userId, { channel: 'email', note: 'Men\'s breakfast this Saturday is moving from the church hall to the Protea Hotel on Main Road because the hall is being renovated. Same time, 7:00. Park at the back of the hotel. Price stays R120, nothing to do if you\'ve paid. Speaker is still Pastor Mike. Questions: events@church.example.org' }); + return { + output: message, + checks: [ + ['has a subject', message.subject.trim().length > 5], + ['keeps the facts', /Protea/.test(message.body) && /7:00/.test(message.body) && /R120/.test(message.body)], + ['the email address came back intact', message.body.includes('events@church.example.org')], + ['no event placeholders without an event', !/\{\{event\./.test(`${message.subject} ${message.body}`)], + ], + }; + }, + }, + { + name: 'Improve this text — a messy description', + async run(userId) { + const { result } = await improveText(userId, { text: 'join us for are anual family fun day!!! theres jumping castles, food stalls and a talent show for the kids. Bring the hole family its going to be awesome. tickets R50 for adults kids under 12 free. starts 9 till 2 on the church field, if it rains we move inside to the hall. please register so we know how many boerewors rolls to make lol', mode: 'improve', where: 'description' }); + return { + output: result, + checks: [ + ['spelling fixed', /annual/i.test(result.text) && /whole family/i.test(result.text) && !/\bare anual\b/.test(result.text)], + ['every fact kept (R50, under 12, 9 to 2, hall)', /R50/.test(result.text) && /12/.test(result.text) && /\b9\b/.test(result.text) && /\b2\b/.test(result.text) && /hall/i.test(result.text)], + ], + }; + }, + }, +]; + +(async () => { + const admin = await prisma.user.findFirst({ where: { role: 'admin', isActive: true }, select: { id: true } }); + if (!admin) throw new Error('No active admin to log the calls against.'); + let passed = 0; + let total = 0; + for (const c of CASES) { + console.log(`\n━━ ${c.name}`); + try { + const { output, checks } = await c.run(admin.id); + for (const [label, ok] of checks) { + total++; + if (ok) passed++; + console.log(` ${ok ? '✓' : '✗'} ${label}`); + } + console.log(JSON.stringify(output, null, 2).split('\n').map(l => ` ${l}`).join('\n')); + } catch (e) { + total++; + console.log(` ✗ failed: ${(e as Error).message}`); + } + } + console.log(`\n${passed} of ${total} checks passed. Read the answers too: the checks only cover the facts.`); + await prisma.$disconnect(); + process.exit(passed === total ? 0 : 1); +})().catch(async e => { + console.error(e); + await prisma.$disconnect(); + process.exit(1); +}); diff --git a/apps/events/backend/scripts/seed-users.js b/apps/events/backend/scripts/seed-users.js index 6814f77..54d2c47 100644 --- a/apps/events/backend/scripts/seed-users.js +++ b/apps/events/backend/scripts/seed-users.js @@ -5,7 +5,7 @@ require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') }); const { createPrismaClient } = require('../src/config/db'); -const bcrypt = require('bcryptjs'); +const { hashPassword } = require('../src/config/auth'); const prisma = createPrismaClient(); @@ -47,7 +47,7 @@ function randomPhone() { } async function main() { - const passwordHash = await bcrypt.hash('Demo@1234', 10); + const passwordHash = await hashPassword('Demo@1234'); // Role distribution: ~55 user, ~15 staff, ~5 supervisor const rolePool = [ diff --git a/apps/events/backend/scripts/set-demo.js b/apps/events/backend/scripts/set-demo.js index 1d9756c..600d6b6 100644 --- a/apps/events/backend/scripts/set-demo.js +++ b/apps/events/backend/scripts/set-demo.js @@ -42,7 +42,7 @@ const readline = require('readline'); require('dotenv').config({ path: path.resolve(__dirname, '../.env') }); -const bcrypt = require('bcryptjs'); +const { hashPassword } = require('../src/config/auth'); const { v4: uuidv4 } = require('uuid'); const { createPrismaClient } = require('../src/config/db'); const { applyBundles } = require('../src/utils/bundles'); @@ -1859,7 +1859,7 @@ async function main() { return; } - passwordHash = await bcrypt.hash(DEMO_PASSWORD, 10); + passwordHash = await hashPassword(DEMO_PASSWORD); const people = buildPeople(); if (profile.campuses) buildCampuses(); const events = profile.upcoming.map(key => UPCOMING[key](people)); diff --git a/apps/events/backend/src/ai/helpers.ts b/apps/events/backend/src/ai/helpers.ts new file mode 100644 index 0000000..319ae96 --- /dev/null +++ b/apps/events/backend/src/ai/helpers.ts @@ -0,0 +1,317 @@ +/** + * The five AI helpers (roadmap §15): each one's instructions, the shape of its answer, and what it + * sends. Run through `runHelper` (./index.ts), which goes via the Hub. + * + * What leaves the site (POPIA): only what a helper needs, and never names, contact details, + * medical or children's information. + * - Email addresses, phone numbers and ID numbers in any free text are swapped for placeholders + * like [[CONTACT1]] before sending, and put back in the answer (`protect` / `restore`). + * - Reports: only those without people in them (REPORTS_WITHOUT_PEOPLE). + * - Feedback: ratings, choice counts and comments, never who answered. + * + * Lessons from the October 2026 trial, built in: every helper is told today's date, and the checks + * that matter most (a weekday that doesn't match its date, an event that loses money when full) + * are worked out here in code as well, not left to the model. + */ + +import { ApiError } from '../v2/errors'; +import { runHelper, type AiStatus } from './index'; + +// ─── Dates ──────────────────────────────────────────────────────────────────── + +const SAST_MS = 2 * 3600 * 1000; +const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; +const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + +/** "Today is Friday 30 October 2026." in South African time. */ +export function todayLine(now = new Date()): string { + const d = new Date(now.getTime() + SAST_MS); + return `Today is ${WEEKDAYS[d.getUTCDay()]} ${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}.`; +} + +// ─── Keeping contact details on the site ────────────────────────────────────── + +const CONTACT_RE = [ + /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, // email + /(?:\+27|\b0)(?:[\s-]?\d){9}\b/g, // South African phone numbers + /\b\d{13}\b/g, // South African ID numbers +]; + +export type Protected = { text: string; found: Map }; + +/** Swap contact details for [[CONTACTn]], so they never leave the site. */ +export function protect(text: string, found: Map = new Map()): Protected { + let out = text; + for (const re of CONTACT_RE) { + out = out.replace(re, match => { + for (const [k, v] of found) if (v === match) return k; + const key = `[[CONTACT${found.size + 1}]]`; + found.set(key, match); + return key; + }); + } + return { text: out, found }; +} + +/** Put the contact details back into an answer (strings anywhere inside it). */ +export function restore(value: T, found: Map): T { + if (!found.size) return value; + const fix = (s: string) => s.replace(/\[\[CONTACT\d+\]\]/g, k => found.get(k) ?? k); + const walk = (v: unknown): unknown => (typeof v === 'string' ? fix(v) : Array.isArray(v) ? v.map(walk) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)])) : v); + return walk(value) as T; +} + +const KEEP_PLACEHOLDERS = 'Text like [[CONTACT1]] stands for a contact detail the site keeps private: copy it exactly where it belongs and never change it.'; + +// ─── Schemas ────────────────────────────────────────────────────────────────── + +const str = { type: 'string' }; +const num = { type: 'number' }; +const int = { type: 'integer' }; +const bool = { type: 'boolean' }; +const list = (items: object) => ({ type: 'array', items }); +const obj = (properties: Record, descriptions: Record = {}) => ({ + type: 'object', additionalProperties: false, required: Object.keys(properties), + properties: Object.fromEntries(Object.entries(properties).map(([k, v]) => [k, descriptions[k] ? { ...v, description: descriptions[k] } : v])), +}); + +// ─── 1. Draft an event ──────────────────────────────────────────────────────── + +export type EventDraftAnswer = { + title: string; summary: string; description: string; + startDate: string; startTime: string; endDate: string; endTime: string; + location: string; capacity: number; needsParentalConsent: boolean; ageGroup: string; + ticketOptions: { name: string; priceRand: number; description: string; earlyBirdPriceRand: number; earlyBirdUntil: string }[]; + sessions: { date: string; startTime: string; endTime: string; label: string }[]; + costs: { item: string; basis: string; amountRand: number }[]; + checks: string[]; +}; + +const EVENT_SCHEMA = obj({ + title: str, summary: str, description: str, + startDate: str, startTime: str, endDate: str, endTime: str, + location: str, capacity: int, needsParentalConsent: bool, ageGroup: str, + ticketOptions: list(obj({ name: str, priceRand: num, description: str, earlyBirdPriceRand: num, earlyBirdUntil: str }, { earlyBirdPriceRand: '0 when there is none', earlyBirdUntil: 'YYYY-MM-DD, or empty' })), + sessions: list(obj({ date: str, startTime: str, endTime: str, label: str })), + costs: list(obj({ item: str, basis: str, amountRand: num }, { basis: 'How it is worked out, e.g. "R180 × 60 people × 2 nights"', amountRand: 'Total for this line at full capacity' })), + checks: list(str), +}, { + summary: 'One sentence for the event card', + description: 'The public event page: 2–4 short paragraphs, plain text', + startDate: 'YYYY-MM-DD', endDate: 'YYYY-MM-DD', startTime: 'HH:MM, 24-hour, or empty', endTime: 'HH:MM, 24-hour, or empty', + capacity: 'Places in total; 0 when not given', + sessions: 'Only for an event that meets on several separate dates people attend, like a weekly course: one row per date. Empty for a single event, even one over a weekend.', + checks: 'Things to look at before publishing: missing details, contradictions, money that does not add up. Empty if none.', +}); + +const EVENT_SYSTEM = (now: Date) => [ + 'You help a church events team set up an event in Cross Events, an event registration system. From the organiser\'s notes, fill in the event form.', + todayLine(now), + '- Title: short and clear. Description: for the public event page, warm and clear, 2–4 short paragraphs, plain text (no markdown): who it is for, what happens, what is included, what to bring if known.', + '- South African rand; 24-hour times. Dates as YYYY-MM-DD: the next time that date comes round after today, unless the notes give a year.', + '- If a weekday in the notes does not match its date, keep the date and say so in "checks".', + '- Ticket options: the prices the notes give, with any early-bird price and its last day. One option when only one price is given.', + '- Leave anything the notes do not give empty (or 0) rather than guess, including times.', + '- Costs: one line per cost the notes give, worked out at full capacity, showing how. Never invent costs.', + '- Never invent names, phone numbers, email addresses or links.', + KEEP_PLACEHOLDERS, +].join('\n'); + +/** Weekdays written next to dates in the notes ("Fri 14 March") that don't match the year used. */ +export function weekdayClashes(notes: string, year: number): string[] { + const out: string[] = []; + const re = /\b(mon|tue|wed|thu|fri|sat|sun)[a-z]*\.?,?\s+(\d{1,2})(?:st|nd|rd|th)?\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*/gi; + for (const m of notes.matchAll(re)) { + const day = Number(m[2]); + const month = MONTHS.findIndex(x => x.toLowerCase().startsWith(m[3].toLowerCase())); + const actual = new Date(Date.UTC(year, month, day)).getUTCDay(); + const said = WEEKDAYS.findIndex(w => w.toLowerCase().startsWith(m[1].toLowerCase())); + if (actual !== said) out.push(`The notes say ${WEEKDAYS[said]} ${day} ${MONTHS[month]}, but ${day} ${MONTHS[month]} ${year} is a ${WEEKDAYS[actual]}. Check the dates.`); + } + return out; +} + +/** R34 800 — plain spaces between thousands, as the AI writes them (en-ZA uses a no-break space). */ +const rands = (n: number) => `R${Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}`; + +/** Money and date checks worked out in code, whatever the model said. */ +export function eventWarnings(notes: string, a: EventDraftAnswer): string[] { + const out: string[] = []; + const year = Number(a.startDate.slice(0, 4)); + if (year > 2000) out.push(...weekdayClashes(notes, year)); + if (a.startDate && a.endDate && `${a.endDate}T${a.endTime || '23:59'}` < `${a.startDate}T${a.startTime || '00:00'}`) out.push('The end is before the start.'); + const costs = a.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0); + const main = a.ticketOptions[0]; + if (costs > 0 && main?.priceRand > 0) { + const breakEven = Math.ceil(costs / main.priceRand); + if (a.capacity > 0 && breakEven > a.capacity) { + const full = a.capacity * main.priceRand; + const early = main.earlyBirdPriceRand > 0 ? a.capacity * main.earlyBirdPriceRand : null; + out.push(`The costs in the notes come to ${rands(costs)}, which needs ${breakEven} places at ${rands(main.priceRand)} — more than the ${a.capacity} available. Even full, the event takes ${rands(full)}${early ? ` (${rands(early)} if everyone books early)` : ''}, ${rands(costs - full)} short.`); + } + } + return out; +} + +export async function draftEvent(userId: string, notes: string, now = new Date()): Promise<{ draft: EventDraftAnswer; warnings: string[]; totalCostRand: number; breakEvenPlaces: number | null; status: AiStatus }> { + const p = protect(notes); + const { output, status } = await runHelper('draft_event', userId, { system: EVENT_SYSTEM(now), input: p.text, schema: EVENT_SCHEMA, maxTokens: 4000, effort: 'low' }); + const draft = restore(output as EventDraftAnswer, p.found); + const totalCostRand = draft.costs.reduce((s, c) => s + (Number(c.amountRand) || 0), 0); + const price = draft.ticketOptions[0]?.priceRand || 0; + return { draft, warnings: eventWarnings(notes, draft), totalCostRand, breakEvenPlaces: totalCostRand > 0 && price > 0 ? Math.ceil(totalCostRand / price) : null, status }; +} + +// ─── 2. Summarise a report ──────────────────────────────────────────────────── + +/** Reports with no people in them: only these can be summarised (keys from ReportCatalog). */ +export const REPORTS_WITHOUT_PEOPLE = ['seriesComparison', 'regTypes', 'usage', 'revenue', 'regStatus', 'donations', 'funnel', 'discounts', 'cashup', 'financeReport', 'profitReport'] as const; +const MAX_ROWS = 400; + +export type ReportInput = { + reportKey: string; + title: string; + subtitle?: string; + stats?: { label: string; value: string | number }[]; + columns: string[]; + rows: (string | number)[][]; +}; + +export type ReportSummary = { headline: string; insights: { title: string; detail: string }[]; watchOut: string[] }; + +const REPORT_SCHEMA = obj({ headline: str, insights: list(obj({ title: str, detail: str })), watchOut: list(str) }, { watchOut: 'Things that need someone to act; empty if none' }); + +const REPORT_SYSTEM = (now: Date) => [ + 'You summarise a report for the leaders of a church that uses Cross Events, an event registration system. They are busy volunteers and staff, not analysts.', + todayLine(now), + '- A one-sentence headline, then 3–5 insights: trends, changes against earlier periods, outliers, and anything that needs action.', + '- Use the report\'s numbers; work out percentages and differences where they help, and get them right. Never invent figures or causes; when you suggest a cause, say it is only a possibility.', + '- Mind the dates against today: an event that has already happened can\'t still be promoted or paid for before it starts.', + '- Plain, friendly South African English. Amounts in rand like R18 900.', +].join('\n'); + +/** The report as compact text: stats, then the table as pipe-separated rows. */ +export function reportText(r: ReportInput): string { + const lines = [`Report: ${r.title}`]; + if (r.subtitle) lines.push(r.subtitle); + for (const s of r.stats || []) lines.push(`${s.label}: ${s.value}`); + lines.push(`Columns: ${r.columns.join(' | ')}`); + for (const row of r.rows.slice(0, MAX_ROWS)) lines.push(row.map(c => String(c ?? '').replace(/\s+/g, ' ')).join(' | ')); + if (r.rows.length > MAX_ROWS) lines.push(`(${r.rows.length - MAX_ROWS} more rows not shown)`); + return lines.join('\n'); +} + +export async function summariseReport(userId: string, report: ReportInput, now = new Date()): Promise<{ summary: ReportSummary; status: AiStatus }> { + if (!(REPORTS_WITHOUT_PEOPLE as readonly string[]).includes(report.reportKey)) { + throw Object.assign(new ApiError('FORBIDDEN', 'This report lists people, so it can\'t be sent to the AI. Summaries work on totals-only reports.'), { reason: 'AI_REPORT_HAS_PEOPLE' }); + } + const p = protect(reportText(report)); + const { output, status } = await runHelper('summarise_report', userId, { system: REPORT_SYSTEM(now), input: p.text, schema: REPORT_SCHEMA, maxTokens: 2000, effort: 'low' }); + return { summary: restore(output as ReportSummary, p.found), status }; +} + +// ─── 3. Draft a message ─────────────────────────────────────────────────────── + +export type MessageAnswer = { subject: string; body: string }; + +const MESSAGE_SCHEMA = obj({ subject: str, body: str }, { subject: 'Empty for WhatsApp' }); + +const MESSAGE_SYSTEM = (channel: 'email' | 'whatsapp', now: Date, withEvent: boolean) => [ + 'You write messages from a church events team to people registered for an event, from the organiser\'s short note.', + todayLine(now), + channel === 'whatsapp' + ? '- WhatsApp: plain text, at most 3 short sentences, at most one emoji. "subject" is empty.' + : '- Email: a clear subject, then the body in short plain-text paragraphs, the most important thing first. Start with "Hi {{name}}," and end with "The events team".', + withEvent + ? '- Use {{name}} for the person\'s first name. {{event.title}}, {{event.start}} and {{event.link}} are filled in with the event\'s details; use them only where the message needs them, and don\'t add a separate block of event details.' + : '- Use {{name}} for the person\'s first name. Use no other {{…}} placeholders: name the event as the note does.', + '- Use only the facts in the note and the event details; never invent times, places, prices, links or contact details, or add advice the note doesn\'t give.', + '- Spell carefully: this goes to everyone registered.', + KEEP_PLACEHOLDERS, +].join('\n'); + +export type EventFacts = { title: string; start: string; location: string | null }; + +export async function draftMessage(userId: string, input: { channel: 'email' | 'whatsapp'; note: string; event?: EventFacts | null }, now = new Date()): Promise<{ message: MessageAnswer; status: AiStatus }> { + const p = protect(input.note); + const facts = input.event ? `\n\nEvent: ${input.event.title}, ${input.event.start}${input.event.location ? `, at ${input.event.location}` : ''}` : ''; + const { output, status } = await runHelper('draft_message', userId, { + system: MESSAGE_SYSTEM(input.channel, now, !!input.event), input: `Note: ${p.text}${facts}`, schema: MESSAGE_SCHEMA, maxTokens: input.channel === 'whatsapp' ? 600 : 1500, effort: 'low', + }); + const message = restore(output as MessageAnswer, p.found); + return { message: input.channel === 'whatsapp' ? { subject: '', body: message.body } : message, status }; +} + +// ─── 4. Summarise feedback ──────────────────────────────────────────────────── + +export type FeedbackQuestion = { label: string; type: string; answered: number; average?: number | null; counts?: { label: string; value: number }[]; texts?: string[] }; +export type FeedbackSummary = { overall: string; liked: { theme: string; mentions: number }[]; improve: { theme: string; mentions: number }[]; quotes: string[]; nextTime: string[] }; + +const FEEDBACK_SCHEMA = obj({ + overall: str, liked: list(obj({ theme: str, mentions: int })), improve: list(obj({ theme: str, mentions: int })), quotes: list(str), nextTime: list(str), +}, { liked: 'Most-mentioned first', improve: 'Most-mentioned first', quotes: 'Up to 3 short comments, copied exactly' }); + +const FEEDBACK_SYSTEM = [ + 'You summarise the feedback people gave after a church event, for the team that ran it.', + '- "overall": two sentences on how it went, using the ratings.', + '- "liked" and "improve": the main themes, most-mentioned first, each with how many comments raised it. Count carefully: a comment counts once per theme.', + '- "quotes": up to 3 short comments that capture the feedback well, copied exactly.', + '- "nextTime": 2–4 concrete suggestions for next time, based only on the feedback.', + '- The comments are anonymous; never guess who wrote one.', + KEEP_PLACEHOLDERS, +].join('\n'); +const MAX_COMMENTS = 400; +const MAX_COMMENT = 600; + +/** The feedback as text: each question with its average or counts, and the comments numbered. */ +export function feedbackText(event: { title: string }, responses: number, invited: number, questions: FeedbackQuestion[]): string { + const lines = [`Event: ${event.title}`, `Responses: ${responses}${invited ? ` of ${invited} asked` : ''}`]; + let n = 0; + for (const q of questions) { + if (q.average != null) lines.push(`${q.label} — average ${q.average} (${q.answered} answers)`); + else if (q.counts) lines.push(`${q.label} — ${q.counts.map(c => `${c.label}: ${c.value}`).join(', ')}`); + else if (q.texts?.length) { + lines.push(`${q.label} — comments:`); + for (const t of q.texts) { + if (n++ >= MAX_COMMENTS) break; + lines.push(`${n}. ${t.replace(/\s+/g, ' ').slice(0, MAX_COMMENT)}`); + } + } + } + return lines.join('\n'); +} + +export async function summariseFeedback(userId: string, input: { event: { title: string }; responses: number; invited: number; questions: FeedbackQuestion[] }): Promise<{ summary: FeedbackSummary; status: AiStatus }> { + const p = protect(feedbackText(input.event, input.responses, input.invited, input.questions)); + const { output, status } = await runHelper('summarise_feedback', userId, { system: FEEDBACK_SYSTEM, input: p.text, schema: FEEDBACK_SCHEMA, maxTokens: 2000, effort: 'low' }); + return { summary: restore(output as FeedbackSummary, p.found), status }; +} + +// ─── 5. Improve this text ───────────────────────────────────────────────────── + +export const IMPROVE_MODES = { improve: 'Make it clear and friendly', shorter: 'Make it shorter', fix: 'Only fix spelling and grammar' } as const; +export type ImproveMode = keyof typeof IMPROVE_MODES; +export type ImproveAnswer = { text: string; changes: string[] }; + +const IMPROVE_SCHEMA = obj({ text: str, changes: list(str) }, { changes: 'A short list of what changed and why' }); + +const IMPROVE_SYSTEM = (mode: ImproveMode, where: string) => [ + `You improve text a church events team wrote for ${where}.`, + mode === 'fix' + ? '- Only fix spelling, grammar and punctuation. Change nothing else.' + : mode === 'shorter' + ? '- Make it noticeably shorter and easier to scan, fixing spelling and grammar too.' + : '- Fix spelling, grammar and punctuation, and make it clear and friendly, about the same length or shorter.', + '- Keep every fact (times, dates, prices, places, ages) exactly; add none.', + '- Plain text, no markdown. Keep the writer\'s warmth, and any humour that works in public. Keep placeholders like {{name}} exactly.', + KEEP_PLACEHOLDERS, +].join('\n'); + +const WHERE = { description: 'an event page', banner: 'a short banner across the top of the website', message: 'a message to people registered for an event' } as const; +export type ImproveWhere = keyof typeof WHERE; + +export async function improveText(userId: string, input: { text: string; mode: ImproveMode; where: ImproveWhere }): Promise<{ result: ImproveAnswer; status: AiStatus }> { + const p = protect(input.text); + const { output, status } = await runHelper('improve_text', userId, { system: IMPROVE_SYSTEM(input.mode, WHERE[input.where]), input: p.text, schema: IMPROVE_SCHEMA, maxTokens: Math.min(8000, 600 + Math.ceil(input.text.length / 2)), effort: 'low' }); + return { result: restore(output as ImproveAnswer, p.found), status }; +} diff --git a/apps/events/backend/src/ai/index.ts b/apps/events/backend/src/ai/index.ts new file mode 100644 index 0000000..ecfec21 --- /dev/null +++ b/apps/events/backend/src/ai/index.ts @@ -0,0 +1,263 @@ +/** + * AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through + * the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap in rand, + * calls Claude and meters the call. This module: + * - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the + * allowance renews — from the licence token first, then the Hub (cached for a minute); + * - runs one helper call (`runHelper`), with this site's own switches per helper and an optional + * daily limit per person, and logs it in `AiCall` (no prompt or answer text); + * - emails the site admins once a month when 80% of the allowance is used. + * The helpers themselves (prompts, schemas, what they send) are in ./helpers.ts. + */ + +import { ApiError } from '../v2/errors'; +import { prisma } from '../v2/legacy'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- the JS Hub client and helpers aren't typed */ +const hub = require('../hub/client') as { + PROTOCOL_VERSION: number; + signedPost(path: string, body: object, opts?: { timeoutMs?: number }): Promise; + HubError: new (...args: any[]) => Error & { code: string; statusCode: number; data: any }; +}; +const { licenceStatus } = require('../hub/licence') as { + licenceStatus(): Promise<{ connected: boolean; claims: { limits?: { aiMonthlyCapCents?: number } } | null; state: string; readOnly: boolean }>; +}; +const email = require('../utils/email') as { + sendMail(m: { to: string; subject: string; html: string; text: string }): Promise; + emailWrapper(body: string): string; + isSmtpConfigured(): boolean; +}; +const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; + +export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const; +export type HelperName = (typeof HELPERS)[number]; + +/** What the Hub says (§3b). Cents are charged rand, with fractions. */ +export type HubAiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string | null }; +/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */ +export type AiStatus = HubAiStatus & { available: boolean; helpers: Record }; + +export type AiSettings = { helpers: Record; dailyLimitPerPerson: number }; +const SETTINGS_KEY = 'ai_settings'; +const WARNED_KEY = 'ai_warned_month'; +const STATUS_TTL_MS = 60 * 1000; +const CALL_TIMEOUT_MS = 90 * 1000; +const KEEP_CALLS_DAYS = 400; + +const OFF: HubAiStatus = { enabled: false, capReached: false, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null }; + +// ─── This site's settings ───────────────────────────────────────────────────── + +export const DEFAULT_SETTINGS: AiSettings = { helpers: Object.fromEntries(HELPERS.map(h => [h, true])) as Record, dailyLimitPerPerson: 0 }; + +export async function getAiSettings(): Promise { + const row = await prisma.appSetting.findUnique({ where: { key: SETTINGS_KEY } }); + let saved: Partial = {}; + try { saved = row ? JSON.parse(row.value) : {}; } catch { /* keep the defaults */ } + return { + helpers: { ...DEFAULT_SETTINGS.helpers, ...Object.fromEntries(HELPERS.filter(h => typeof saved.helpers?.[h] === 'boolean').map(h => [h, saved.helpers![h]])) }, + dailyLimitPerPerson: Number.isInteger(saved.dailyLimitPerPerson) && saved.dailyLimitPerPerson! >= 0 ? saved.dailyLimitPerPerson! : 0, + }; +} + +export async function saveAiSettings(next: { helpers?: Partial>; dailyLimitPerPerson?: number }, actor: { id: string; role: string }, ip?: string): Promise { + const current = await getAiSettings(); + const changed = Object.fromEntries(HELPERS.filter(h => typeof next.helpers?.[h] === 'boolean').map(h => [h, next.helpers![h]])); + const value: AiSettings = { + helpers: { ...current.helpers, ...changed }, + dailyLimitPerPerson: next.dailyLimitPerPerson ?? current.dailyLimitPerPerson, + }; + await prisma.appSetting.upsert({ where: { key: SETTINGS_KEY }, update: { value: JSON.stringify(value) }, create: { key: SETTINGS_KEY, value: JSON.stringify(value) } }); + await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'ai_settings_changed', targetType: 'setting', targetId: SETTINGS_KEY, metadata: value, ip }); + return value; +} + +// ─── Status ─────────────────────────────────────────────────────────────────── + +let cached: { at: number; value: HubAiStatus; available: boolean } | null = null; + +/** Keep what the Hub just said (every AI reply and error carries it). */ +function remember(value: unknown, available = true): void { + const v = value as Partial | null; + if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, available }; +} + +export function clearAiStatusCache(): void { + cached = null; +} + +/** + * The cap from the licence token (refreshed by every heartbeat): no Hub call is needed to know AI + * is off, which is most sites. + */ +async function licenceCap(): Promise { + const l = await licenceStatus(); + if (!l.connected || !l.claims || l.readOnly) return 0; + return Number(l.claims.limits?.aiMonthlyCapCents) || 0; +} + +async function hubStatus(fresh = false): Promise<{ value: HubAiStatus; available: boolean }> { + if (!fresh && cached && Date.now() - cached.at < STATUS_TTL_MS) return cached; + try { + remember(await hub.signedPost('/api/installs/ai/status', { protocolVersion: hub.PROTOCOL_VERSION })); + } catch (e) { + const err = e as { code?: string; statusCode?: number }; + // A Hub before 1.6.0 has no AI; a released install has no licence: both mean off. + if (err.statusCode === 404) cached = { at: Date.now(), value: OFF, available: true }; + else { + console.warn('[ai] could not ask the Hub for the AI status:', (e as Error).message); + // Unreachable: keep showing the buttons (they say AI is unavailable when pressed). + cached = { at: Date.now(), value: { ...(cached?.value || OFF), enabled: true }, available: false }; + } + } + return cached!; +} + +export async function aiStatus({ fresh = false } = {}): Promise { + const settings = await getAiSettings(); + if ((await licenceCap()) <= 0) return { ...OFF, available: true, helpers: settings.helpers }; + const { value, available } = await hubStatus(fresh); + return { ...value, available, helpers: settings.helpers }; +} + +// ─── Running a helper ───────────────────────────────────────────────────────── + +export type HelperRequest = { + /** The helper's fixed instructions (the Hub has Claude cache them). */ + system: string; + /** This request's text. Never names, contact details, medical or children's information. */ + input: string; + /** A JSON schema: the answer comes back as JSON in this shape. */ + schema?: object; + maxTokens: number; + effort?: 'low' | 'medium' | 'high'; +}; + +const failure = (code: 'FORBIDDEN' | 'RATE_LIMITED' | 'UNAVAILABLE', reason: string, message: string) => Object.assign(new ApiError(code, message), { reason }); + +function renewsText(renewsOn: string | null): string { + if (!renewsOn) return 'next month'; + return new Date(`${renewsOn}T12:00:00Z`).toLocaleDateString('en-ZA', { day: 'numeric', month: 'long', timeZone: 'Africa/Johannesburg' }); +} + +/** The Hub's errors (§3b) as v2 errors, and what to log. */ +function fromHubError(e: { code?: string; statusCode?: number; message: string; data?: any }): { error: ApiError; outcome: string } { + remember(e.data?.status); + switch (e.code) { + case 'AI_CAP_REACHED': + return { outcome: 'cap_reached', error: failure('FORBIDDEN', 'AI_CAP_REACHED', `This month's AI allowance is used up — it renews on ${renewsText(e.data?.status?.renewsOn ?? null)}.`) }; + case 'AI_OFF': case 'LICENCE_INACTIVE': case 'AI_NOT_CONFIGURED': + return { outcome: 'unavailable', error: failure('FORBIDDEN', 'AI_OFF', 'AI helpers are not available on this site.') }; + case 'AI_REFUSED': + return { outcome: 'refused', error: failure('UNAVAILABLE', 'AI_REFUSED', "The AI couldn't help with this one. Try wording it differently.") }; + case 'AI_INCOMPLETE': + return { outcome: 'incomplete', error: failure('UNAVAILABLE', 'AI_INCOMPLETE', 'The answer was too long and got cut off. Try asking for less.') }; + case 'AI_INPUT_TOO_LARGE': + return { outcome: 'failed', error: failure('UNAVAILABLE', 'AI_INPUT_TOO_LARGE', 'There is too much here to send in one go.') }; + case 'AI_FAILED': + return { outcome: 'failed', error: failure('UNAVAILABLE', 'AI_FAILED', "The AI's answer couldn't be used. Try again.") }; + default: + return { outcome: 'unavailable', error: failure('UNAVAILABLE', 'AI_UNAVAILABLE', 'AI is unavailable right now. Try again in a few minutes.') }; + } +} + +/** Starts of today in South African time, for the per-person daily limit. */ +function startOfToday(now = new Date()): Date { + const sast = new Date(now.getTime() + 2 * 3600 * 1000); + return new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), sast.getUTCDate()) - 2 * 3600 * 1000); +} + +let prunedOn = ''; +/** Calls older than about 13 months go (once a day, on the first call). */ +async function pruneOldCalls(now = new Date()): Promise { + const today = now.toISOString().slice(0, 10); + if (prunedOn === today) return; + prunedOn = today; + await prisma.aiCall.deleteMany({ where: { createdAt: { lt: new Date(now.getTime() - KEEP_CALLS_DAYS * 86400000) } } }).catch(() => {}); +} + +/** At 80% of the allowance, the site's admins get one email a month. */ +async function warnAt80(status: HubAiStatus): Promise { + if (!status.enabled || status.usedPercent < 80 || !status.renewsOn) return; + const row = await prisma.appSetting.findUnique({ where: { key: WARNED_KEY } }); + if (row?.value === status.renewsOn) return; + await prisma.appSetting.upsert({ where: { key: WARNED_KEY }, update: { value: status.renewsOn }, create: { key: WARNED_KEY, value: status.renewsOn } }); + if (!email.isSmtpConfigured()) return; + const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } }); + const when = renewsText(status.renewsOn); + const text = `This site has used ${status.usedPercent}% of this month's AI allowance (R${(status.usedCents / 100).toFixed(2)} of R${(status.capCents / 100).toFixed(2)}). The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`; + for (const a of admins) { + await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`

${text}

`) }) + .catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message)); + } +} + +/** + * Run one helper call for a person. Resolves to the answer (text, or JSON when a schema was + * given) and the new status; throws an ApiError with a `reason` (AI_OFF, AI_HELPER_OFF, + * AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE…). + */ +export async function runHelper(helper: HelperName, userId: string, req: HelperRequest): Promise<{ output: unknown; status: AiStatus }> { + const status = await aiStatus(); + if (!status.enabled) throw failure('FORBIDDEN', 'AI_OFF', 'AI helpers are not available on this site.'); + if (!status.helpers[helper]) throw failure('FORBIDDEN', 'AI_HELPER_OFF', 'This AI helper is switched off in Site settings → AI.'); + if (status.capReached) throw failure('FORBIDDEN', 'AI_CAP_REACHED', `This month's AI allowance is used up — it renews on ${renewsText(status.renewsOn)}.`); + const { dailyLimitPerPerson } = await getAiSettings(); + if (dailyLimitPerPerson > 0) { + const today = await prisma.aiCall.count({ where: { userId, createdAt: { gte: startOfToday() }, outcome: { in: ['ok', 'refused', 'incomplete'] } } }); + if (today >= dailyLimitPerPerson) throw failure('RATE_LIMITED', 'AI_DAILY_LIMIT', `You've used the AI helpers ${dailyLimitPerPerson} times today, the most this site allows. Try again tomorrow.`); + } + + let outcome = 'ok'; + let chargedCents = 0; + try { + const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS }); + chargedCents = Number(reply.chargedCents) || 0; + remember(reply.status); + await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message)); + return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } }; + } catch (e) { + if (e instanceof ApiError) throw e; + const mapped = fromHubError(e as Error & { code?: string; data?: any }); + outcome = mapped.outcome; + if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false); + throw mapped.error; + } finally { + await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message)); + await pruneOldCalls(); + } +} + +// ─── Usage (Site settings → AI) ─────────────────────────────────────────────── + +/** This month's use on this site: per person, per helper and per day (South African time). */ +export async function usageThisMonth(now = new Date()) { + const sast = new Date(now.getTime() + 2 * 3600 * 1000); + const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000); + const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, chargedCents: true, createdAt: true } }); + const add = (m: Map, key: string, cents: number) => { + const v = m.get(key) || { uses: 0, chargedCents: 0 }; + v.uses++; + v.chargedCents += cents; + m.set(key, v); + }; + const byPerson = new Map(); + const byHelper = new Map(); + const byDay = new Map(); + for (const c of calls) { + if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue; + add(byPerson, c.userId || '', c.chargedCents); + add(byHelper, c.helper, c.chargedCents); + add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c.chargedCents); + } + const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } }); + const names = new Map(people.map(p => [p.id, p.name])); + return { + people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort((a, b) => b.chargedCents - a.chargedCents), + helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort((a, b) => b.chargedCents - a.chargedCents), + days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)), + }; +} + +// For tests. +export const _internal = { fromHubError, startOfToday, renewsText }; diff --git a/apps/events/backend/src/app.js b/apps/events/backend/src/app.js index 724f4be..f021ea4 100644 --- a/apps/events/backend/src/app.js +++ b/apps/events/backend/src/app.js @@ -102,12 +102,10 @@ const globalLimiter = rateLimit({ skip: (req) => RAW_BODY_PREFIXES.some(p => req.path.startsWith(p)), }); // Incoming webhooks and links in sent messages on v2 (1.51.16): see src/v2/links.ts. -const { RAW_BODY_PREFIXES, webhooksRouter, linksRouter, legacyLinkRedirects } = require('./v2/links'); +const { RAW_BODY_PREFIXES, webhooksRouter, linksRouter, legacyLinkRedirects, legacyV1Router, v1Removed } = require('./v2/links'); // /api/v2 answers every error as { error: { code, message } }, including the shared // middleware below (rate limits, read-only guards, auth) that writes v1's { message }. app.use('/api/v2', require('./v2/errors').legacyErrorsToV2); -// v1 endpoints with a v2 replacement say so (Deprecation + Link: rel="successor-version"). -app.use('/api', require('./v2/deprecation').deprecationHeaders); app.use(globalLimiter); @@ -132,34 +130,7 @@ app.use((req, res, next) => { }); -// Import routes -const userRoutes = require('./routes/userRoutes'); -const eventRoutes = require('./routes/eventRoutes'); -const registrationRoutes = require('./routes/registrationRoutes'); -const paymentRoutes = require('./routes/paymentRoutes'); -const ticketRoutes = require('./routes/ticketRoutes'); const webhookRoutes = require('./routes/webhookRoutes'); -const uploadRoutes = require('./routes/uploadRoutes'); -const reportRoutes = require('./routes/reportRoutes'); -const formRoutes = require('./routes/formRoutes'); -const providerTransactionRoutes = require('./routes/providerTransactionRoutes'); -const automationRoutes = require('./routes/automationRoutes'); -const broadcastRoutes = require('./routes/broadcastRoutes'); -const whatsappBroadcastRoutes = require('./routes/whatsappBroadcastRoutes'); -const scheduledEmailRoutes = require('./routes/scheduledEmailRoutes'); -const sectionRoutes = require('./routes/sectionRoutes'); -const bannerRoutes = require('./routes/bannerRoutes'); -const whatsappRoutes = require('./routes/whatsappRoutes'); -const settingsRoutes = require('./routes/settingsRoutes'); -const setupRoutes = require('./routes/setupRoutes'); -const costRoutes = require('./routes/costRoutes'); -const cashupRoutes = require('./routes/cashupRoutes'); -const statsRoutes = require('./routes/statsRoutes'); -const adminRoutes = require('./routes/adminRoutes'); -const backupRoutes = require('./routes/backupRoutes'); -const yocoRoutes = require('./routes/yocoRoutes'); -const payfastRoutes = require('./routes/payfastRoutes'); -const privacyRoutes = require('./routes/privacyRoutes'); // Mount webhook routes BEFORE JSON body parser to avoid double-reading the stream app.use('/api/webhooks', webhookRoutes); @@ -204,52 +175,10 @@ app.use('/api/v2', require('./v2').v2Router()); // Links in messages already sent: v1 addresses answer 308 with their v2 one. app.use(legacyLinkRedirects); app.use('/docs/v2', require('./v2').v2DocsRouter()); -app.use('/api/hub', require('./routes/hubRoutes')); -app.use('/api/campuses', require('./routes/campusRoutes')); -app.use('/api/kids', require('./routes/kidsRoutes')); -app.use('/api/volunteers', require('./routes/volunteerRoutes')); -app.use('/api/series', require('./routes/seriesRoutes')); -app.use('/api/season-passes', require('./routes/seasonPassRoutes')); -app.use('/api/outbound-webhooks', require('./routes/outboundWebhookRoutes')); -app.use('/api/dashboard', require('./routes/dashboardRoutes')); -app.use('/api/saved-filters', require('./routes/savedFilterRoutes')); -app.use('/api/users', userRoutes); -app.use('/api/events', eventRoutes); -app.use('/api/registrations', registrationRoutes); -app.use('/api/payments', paymentRoutes); -app.use('/api/tickets', ticketRoutes); -app.use('/api/uploads', uploadRoutes); -app.use('/api/reports', reportRoutes); -app.use('/api/forms', formRoutes); -app.use('/api/provider-transactions', providerTransactionRoutes); -app.use('/api/yoco-transactions', providerTransactionRoutes); // older name -app.use('/api/automations', automationRoutes); -app.use('/api/broadcasts', broadcastRoutes); -app.use('/api/whatsapp-broadcasts', whatsappBroadcastRoutes); -app.use('/api/scheduled-emails', scheduledEmailRoutes); -app.use('/api/sections', sectionRoutes); -app.use('/api/banner', bannerRoutes); -app.use('/api/whatsapp', whatsappRoutes); -app.use('/api/privacy', privacyRoutes); -app.use('/api/settings', settingsRoutes); -app.use('/api/setup', setupRoutes); -app.use('/api/stats', statsRoutes); -app.use('/api', costRoutes); -app.use('/api/cashups', cashupRoutes); -app.use('/api/admin', adminRoutes); -app.use('/api/coupons', require('./routes/couponRoutes')); -app.use('/api/bundles', require('./routes/bundleRoutes')); -app.use('/api/consent', require('./routes/consentRoutes')); -app.use('/api/waitlist', require('./routes/waitlistRoutes')); -app.use('/api/scan-locks', require('./routes/scanLockRoutes')); -app.use('/api/allocations', require('./routes/allocationRoutes')); -app.use('/api/sponsorships', require('./routes/sponsorshipRoutes')); -app.use('/api/feedback', require('./routes/feedbackRoutes')); -app.use('/api/attendance', require('./routes/attendanceRoutes')); -app.use('/api/analytics', require('./routes/analyticsRoutes')); -app.use('/api/backups', backupRoutes); -app.use('/api/yoco', yocoRoutes); -app.use('/api/payfast', payfastRoutes); +// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old +// address) and links in messages already sent (308s above, a mail app's one-click POST here). +app.use('/api', legacyV1Router); +app.use('/api', v1Removed); // Pre-warm the settings cache so synchronous helpers have DB values from startup const { getSettingSync, warmCache } = require('./utils/settingsCache'); @@ -266,7 +195,6 @@ app.use('/uploads', express.static('public/uploads', { })); // ── Shared page helpers ──────────────────────────────────────────────────────── -const jwt = require('jsonwebtoken'); function pageShell(title, accentColor, bodyHtml) { return ` @@ -407,1309 +335,15 @@ app.get('/', async (req, res) => {
- API documentation is available at /docs (v1) and /docs/v2 (v2, OpenAPI) — both need an admin account token. + API documentation (OpenAPI) is at /docs/v2 — it needs an admin account token.
`); res.send(html); }); -// ── /docs route — interactive API reference, admin only ───────────────────── -app.get('/docs', async (req, res) => { - const tokenFromQuery = req.query.token; - const tokenFromHeader = req.headers.authorization?.startsWith('Bearer ') - ? req.headers.authorization.split(' ')[1] : null; - const token = tokenFromQuery || tokenFromHeader; - - if (!token) { - return res.status(401).send(pageShell('API Docs — Login Required', '#2563eb', ` -

API Documentation

-

Admin access required

-
-

Pass your admin JWT to view the docs:

- /docs?token=<your-admin-jwt> -

Copy your token from the browser's localStorage key token after logging in as admin.

-
`)); - } - - let user; - try { - const decoded = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }); - user = await prisma.user.findUnique({ - where: { id: decoded.id }, - select: { id: true, name: true, email: true, role: true, isActive: true, tokenVersion: true }, - }); - if (!user || !user.isActive) throw new Error('User not found or inactive'); - if ((decoded.tokenVersion ?? 0) !== user.tokenVersion) throw new Error('Token revoked'); - if (user.role !== 'admin') throw new Error('Admin role required'); - } catch (e) { - return res.status(403).send(pageShell('API Docs — Access Denied', '#dc2626', ` -

Access Denied

-

Admin role required

-
-

${e.message}

-

Make sure you are logged in as an admin and using a valid, non-expired token.

-
`)); - } - - // ── Endpoint data ──────────────────────────────────────────────────────── - const GROUPS = [ - { title: 'Users', base: '/api/users', endpoints: [ - { method:'GET', path:'/api/users/activity', auth:'Bearer', desc:'Recent account activity (logins, password changes) for the current user' }, - { method:'POST', path:'/api/users', auth:'public', desc:'Register a new account', - request:{ body:{ name:'Jane Doe', email:'jane@example.com', password:'secret123', phoneNumber:'+27821234567' }}, - responses:[ - { status:201, desc:'Created', body:{ id:'a1b2c3d4-0000-0000-0000-000000000001', name:'Jane Doe', email:'jane@example.com', role:'user', token:'eyJhbGciOiJIUzI1NiJ9...' }}, - { status:400, desc:'Validation error', body:{ message:'Email already in use' }}, - ]}, - { method:'POST', path:'/api/users/login', auth:'public', desc:'Login — returns a signed JWT', - notes:'Rate-limited to 15 requests/min per IP.', - request:{ body:{ email:'jane@example.com', password:'secret123' }}, - responses:[ - { status:200, desc:'Success', body:{ id:'a1b2c3d4-...', name:'Jane Doe', email:'jane@example.com', role:'user', token:'eyJhbGciOiJIUzI1NiJ9...' }}, - { status:200, desc:'Two-factor code sent (account has 2FA on) — no token yet', body:{ twoFactorRequired:true, challengeId:'c0ffee00-...', method:'email', destination:'j•••@example.com' }}, - { status:200, desc:'Admin/supervisor without 2FA — code sent; verifying it turns 2FA on', body:{ twoFactorRequired:true, enrolling:true, challengeId:'c0ffee00-...', method:'email', destination:'j•••@example.com' }}, - { status:401, desc:'Wrong credentials', body:{ message:'Invalid email or password' }}, - ]}, - { method:'POST', path:'/api/users/login/2fa', auth:'public', desc:'Second login step — exchange the emailed/WhatsApp code for a JWT', - notes:'Codes expire after 10 minutes and allow 5 attempts. With rememberDevice, the response includes a deviceToken; send it with later logins to skip the code for 30 days.', - request:{ body:{ challengeId:'c0ffee00-...', code:'123456', rememberDevice:true }}, - responses:[ - { status:200, desc:'Success', body:{ id:'a1b2c3d4-...', name:'Jane Doe', email:'jane@example.com', role:'user', token:'eyJhbGciOiJIUzI1NiJ9...', deviceToken:'9f2c...' }}, - { status:400, desc:'Wrong or expired code', body:{ message:'Incorrect code. 4 attempts left.' }}, - ]}, - { method:'POST', path:'/api/users/login/2fa/resend', auth:'public', desc:'Send a new code for a pending login challenge', - notes:'At most one send per 60 seconds.', - request:{ body:{ challengeId:'c0ffee00-...' }}, - responses:[ - { status:200, desc:'Sent', body:{ challengeId:'c0ffee00-...', method:'email', destination:'j•••@example.com' }}, - { status:429, desc:'Too soon', body:{ message:'Please wait 42 seconds before requesting another code.' }}, - ]}, - { method:'POST', path:'/api/users/forgot', auth:'public', desc:'Request a password reset email', - request:{ body:{ email:'jane@example.com' }}, - responses:[ - { status:200, desc:'Always succeeds (no user enumeration)', body:{ message:'If that email exists, a reset link has been sent.' }}, - ]}, - { method:'POST', path:'/api/users/reset', auth:'public', desc:'Reset password using token from email', - request:{ body:{ token:'reset-token-from-email', password:'newPassword123' }}, - responses:[ - { status:200, desc:'Success', body:{ message:'Password reset successful.' }}, - { status:400, desc:'Invalid or expired token', body:{ message:'Reset token is invalid or has expired.' }}, - ]}, - { method:'POST', path:'/api/users/activate', auth:'public', desc:'Activate a new account via email link', - request:{ body:{ token:'activation-token-from-email' }}, - responses:[ - { status:200, desc:'Success', body:{ message:'Account activated.' }}, - { status:400, desc:'Invalid token', body:{ message:'Invalid or expired activation token.' }}, - ]}, - { method:'GET', path:'/api/users/profile', auth:'user+', desc:'Get own profile', - responses:[ - { status:200, desc:'Success', body:{ id:'a1b2c3d4-...', name:'Jane Doe', email:'jane@example.com', role:'user', phoneNumber:'+27821234567', notificationPreference:'email', createdAt:'2024-01-15T08:00:00.000Z' }}, - { status:401, desc:'Unauthorized', body:{ message:'Not authorized, no token' }}, - ]}, - { method:'PUT', path:'/api/users/profile', auth:'user+', desc:'Update own profile', - request:{ body:{ name:'Jane Smith', phoneNumber:'+27821234567', notificationPreference:'both' }}, - responses:[ - { status:200, desc:'Updated', body:{ id:'a1b2c3d4-...', name:'Jane Smith', email:'jane@example.com', notificationPreference:'both' }}, - ]}, - { method:'POST', path:'/api/users/revoke-sessions', auth:'user+', desc:'Invalidate all own sessions by incrementing tokenVersion', - responses:[{ status:200, desc:'Success', body:{ message:'All sessions revoked.' }}]}, - { method:'POST', path:'/api/users/close-account', auth:'user+', desc:'Deactivate own account', - responses:[{ status:200, desc:'Success', body:{ message:'Account deactivated.' }}]}, - { method:'POST', path:'/api/users/2fa/enable', auth:'user+', desc:'Start turning on two-factor authentication — sends a code to the chosen channel', - notes:'WhatsApp needs a valid phone number on the account and a connected WhatsApp session.', - request:{ body:{ method:'email', password:'secret123' }}, - responses:[ - { status:200, desc:'Code sent', body:{ challengeId:'c0ffee00-...', method:'email', destination:'j•••@example.com' }}, - { status:400, desc:'Wrong password or unavailable channel', body:{ message:'Incorrect password' }}, - ]}, - { method:'POST', path:'/api/users/2fa/confirm', auth:'user+', desc:'Finish turning on two-factor authentication with the code that was sent', - request:{ body:{ challengeId:'c0ffee00-...', code:'123456' }}, - responses:[{ status:200, desc:'Enabled', body:{ twoFactorEnabled:true, twoFactorMethod:'email' }}]}, - { method:'POST', path:'/api/users/2fa/disable', auth:'user+', desc:'Turn off two-factor authentication', - request:{ body:{ password:'secret123' }}, - notes:'Admins and supervisors must keep two-factor on — 403 for them.', - responses:[ - { status:200, desc:'Disabled', body:{ twoFactorEnabled:false, twoFactorMethod:null }}, - { status:403, desc:'Required for this role', body:{ message:"Two-factor authentication is required for your role and can't be turned off." }}, - ]}, - { method:'POST', path:'/api/users/verify-password', auth:'user+', desc:'Re-confirm own password without starting a new session', - request:{ body:{ password:'secret123' }}, - responses:[ - { status:200, desc:'Correct', body:{ ok:true }}, - { status:401, desc:'Wrong password', body:{ message:'Incorrect password' }}, - ]}, - { method:'GET', path:'/api/users', auth:'supervisor+', desc:'List all users (paginated). All filters are applied server-side.', - queryParams:{ page:'Page number (default 1)', limit:'Items per page (max 200, default 100)', search:'Search by name, email, or phone number (case-insensitive substring)', role:'Filter by role: admin|supervisor|staff|user', isActive:'Filter by active status: true|false (omit for both)' }, - responses:[ - { status:200, desc:'Success', body:{ data:[{ id:'a1b2c3d4-...', name:'Jane Doe', email:'jane@example.com', role:'user', isActive:true, createdAt:'2024-01-15T08:00:00.000Z' }], total:1, page:1, limit:20 }}, - ]}, - { method:'GET', path:'/api/users/check-exists', auth:'supervisor+', desc:'Check whether an account already exists for a given email and/or phone number (used by the self-service kiosk and manual registration screens to avoid duplicate accounts)', - queryParams:{ email:'Email to look up (optional)', phone:'Phone number to look up (optional; SA formats normalized)' }, - responses:[ - { status:200, desc:'Success', body:{ exists:true, hasEmail:true, hasPhone:false }}, - ]}, - { method:'GET', path:'/api/users/:id', auth:'admin', desc:'Get a single user by ID (with scopedCampuses)', - pathParams:{ ':id':'User UUID' }, - responses:[ - { status:200, desc:'Success', body:{ id:'a1b2c3d4-...', name:'Jane Doe', email:'jane@example.com', role:'user', isActive:true, phoneNumber:'+27821234567', notificationPreference:'email' }}, - { status:404, desc:'Not found', body:{ message:'User not found' }}, - ]}, - { method:'PUT', path:'/api/users/:id', auth:'admin', desc:'Update any user (including role). scopedCampusIds limits a supervisor/staff member to those campuses (empty = every campus; audited)', - pathParams:{ ':id':'User UUID' }, - request:{ body:{ role:'supervisor', isActive:true, name:'Jane Doe' }}, - responses:[ - { status:200, desc:'Updated', body:{ id:'a1b2c3d4-...', name:'Jane Doe', role:'supervisor' }}, - ]}, - { method:'DELETE', path:'/api/users/:id', auth:'admin', desc:'Deactivate a user account (sets isActive: false; does not erase data)', - pathParams:{ ':id':'User UUID' }, - responses:[ - { status:200, desc:'Deactivated', body:{ message:'User deactivated' }}, - { status:404, desc:'Not found', body:{ message:'User not found' }}, - ]}, - { method:'POST', path:'/api/users/:id/revoke-sessions', auth:'admin', desc:'Revoke all sessions for another user', - pathParams:{ ':id':'User UUID' }, - responses:[{ status:200, desc:'Success', body:{ message:'Sessions revoked for user.' }}]}, - { method:'POST', path:'/api/users/:id/anonymize', auth:'admin', desc:'Erase personal data for a user (POPIA) — the account, the people they registered, form answers, consent details, sponsor names, login history and payer details in provider payloads; payments, registrations and tickets stay as "Deleted User". Refused (409) while they have a registration for an upcoming event. Completes an open deletion request. Irreversible; audited as user_anonymised.', - pathParams:{ ':id':'User UUID' }, - responses:[ - { status:200, desc:'Anonymised', body:{ message:'User data deleted' }}, - { status:404, desc:'Not found', body:{ message:'User not found' }}, - ]}, - ]}, - - { title: 'Events', base: '/api/events', endpoints: [ - { method:'GET', path:'/api/events/admin/all', auth:'admin', desc:'All events, including inactive ones' }, - { method:'GET', path:'/api/events/:id/ics', auth:'Public (optional login)', desc:'Download an .ics calendar file for an event' }, - { method:'GET', path:'/api/events/:id/attachments', auth:'Public', desc:'List the downloadable attachments of an event' }, - { method:'POST', path:'/api/events/:id/attachments', auth:'supervisor+', desc:'Upload an attachment (multipart, field "file")' }, - { method:'DELETE', path:'/api/events/:eventId/attachments/:attachmentId', auth:'supervisor+', desc:'Delete an attachment' }, - { method:'GET', path:'/api/events/attachments/status', auth:'admin', desc:'Diagnostics for the attachments pipeline' }, - { method:'POST', path:'/api/events/attachments/sync', auth:'admin', desc:'Re-sync attachment records with the files on disk' }, - { method:'POST', path:'/api/events/options/:id/variants', auth:'supervisor+', desc:'Add a variant (e.g. a size) to an event option' }, - { method:'GET', path:'/api/events', auth:'public', desc:'List active, public, upcoming events. Each event includes isSoldOut:boolean — true when every option with a stockLimit > 0 is fully booked.', - queryParams:{ limit:'Max results (default 20)' }, - responses:[ - { status:200, desc:'Success', body:[{ id:'ev-uuid-...', title:'Camp 2025', startDate:'2025-07-10T08:00:00.000Z', endDate:'2025-07-14T17:00:00.000Z', price:450, picture:'/uploads/camp.jpg', isActive:true, isSoldOut:false }]}, - ]}, - { method:'GET', path:'/api/events/all', auth:'staff+', desc:'All events including hidden and past', - queryParams:{ includePast:'Include past events (true|false, default false)' }, - responses:[{ status:200, desc:'Success', body:[{ id:'ev-uuid-...', title:'Camp 2025', isHidden:false, isActive:true }]}]}, - { method:'GET', path:'/api/events/:id', auth:'public', desc:'Get full event detail by ID. When called by staff/supervisor/admin, the response also includes createdBy and notifyRecipients (who the event\'s notifications go to).', - pathParams:{ ':id':'Event UUID' }, - responses:[ - { status:200, desc:'Success', body:{ id:'ev-uuid-...', title:'Camp 2025', description:'Annual family camp.', startDate:'2025-07-10T08:00:00.000Z', endDate:'2025-07-14T17:00:00.000Z', price:450, requiresAuth:true, eventOptions:[{ id:'opt-uuid-...', name:'Adult', price:450, isMainTicket:true }], createdBy:{ id:'user-uuid-...', name:'Jane Supervisor', email:'jane@example.com' }, notifyRecipients:[]}}, - { status:404, desc:'Not found', body:{ message:'Event not found' }}, - ]}, - { method:'GET', path:'/api/events/by-alias/:redirectUrl', auth:'public', desc:'Get event by its URL alias', - pathParams:{ ':redirectUrl':'URL alias string (e.g. camp-2025)' }, - responses:[{ status:200, desc:'Success', body:{ id:'ev-uuid-...', title:'Camp 2025', redirectUrl:'camp-2025' }}]}, - { method:'POST', path:'/api/events', auth:'supervisor+', desc:'Create a new event', - request:{ body:{ title:'Camp 2025', description:'Annual family camp', startDate:'2025-07-10T08:00:00.000Z', endDate:'2025-07-14T17:00:00.000Z', registrationDeadline:'2025-07-01T00:00:00.000Z', price:450, isActive:true, isHidden:false, requiresAuth:true }}, - responses:[ - { status:201, desc:'Created', body:{ id:'ev-uuid-new', title:'Camp 2025', createdAt:'2024-11-01T09:00:00.000Z' }}, - ]}, - { method:'PUT', path:'/api/events/:id', auth:'supervisor+', desc:'Update an event. Multi-day events send scheduleType:"sessions" with the full sessions list (rows left out are deleted; ones with check-ins must be cancelled instead), plus lateJoinEnabled, lateJoinUntilSessionIndex, latePricing, lateFixedPrice, checkInWindow, sessionReminders, certificatesEnabled and certificateConfig. The response includes sessionChanges.', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ title:'Camp 2025 Updated', price:500 }}, - responses:[{ status:200, desc:'Updated', body:{ id:'ev-uuid-...', title:'Camp 2025 Updated', price:500 }}]}, - { method:'POST', path:'/api/events/:id/copy-from', auth:'supervisor+', desc:'Copying an event (1.47.0): after the copy is created from the event form, copy the source event\'s allocation sets and groups (not the kids rooms) and, for admins, its planned costs (matched to options by name). Only into an event with no registrations or allocation sets yet. POST /api/events takes clonedFromId to note the source in the audit log.', - pathParams:{ ':id':'The new event' }, - request:{ body:{ fromEventId:'ev-uuid-source' }}, - responses:[{ status:200, desc:'Copied', body:{ sets:2, groups:9, costs:3 }}, { status:409, desc:'The event already has registrations or groups' }]}, - { method:'GET', path:'/api/events/:id/notify-recipients', auth:'supervisor+', desc:'Get which users receive registration/payment/daily-summary notifications for this event. Lightweight — skips the option/stock computation that GET /api/events/:id does.', - pathParams:{ ':id':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:[{ id:'user-uuid-1', name:'Jane Supervisor', email:'jane@example.com', role:'supervisor' }]}]}, - { method:'PUT', path:'/api/events/:id/notify-recipients', auth:'supervisor+', desc:'Set which users receive registration/payment/daily-summary notifications for this event. Pass an empty array to fall back to the event creator.', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ userIds:['user-uuid-1','user-uuid-2'] }}, - responses:[ - { status:200, desc:'Saved', body:[{ id:'user-uuid-1', name:'Jane Supervisor', email:'jane@example.com', role:'supervisor' },{ id:'user-uuid-2', name:'John Admin', email:'john@example.com', role:'admin' }]}, - { status:400, desc:'Bad input', body:{ message:'userIds must be an array' }}, - ]}, - { method:'DELETE', path:'/api/events/:id', auth:'admin', desc:'Permanently delete an event', - pathParams:{ ':id':'Event UUID' }, - responses:[{ status:200, desc:'Deleted', body:{ message:'Event deleted.' }}]}, - { method:'POST', path:'/api/events/:id/email-attendees', auth:'supervisor+', desc:'Send a bulk email to event attendees. Use dryRun:true to preview recipients without sending.', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ subject:'Payment reminder: Camp 2025', text:'Hi {{name}}, you have an outstanding balance of {{balance}}.', filter:{ status:'unpaid', attendeeIds:['user-uuid-1','user-uuid-2'] }, dryRun:false, template:'custom' }}, - responses:[ - { status:200, desc:'Sent', body:{ matched:15, sent:14, failed:1 }}, - { status:200, desc:'Dry run', body:{ matched:15, dryRun:true, recipients:[{ email:'jane@example.com', name:'Jane Doe' }]}}, - ]}, - { method:'POST', path:'/api/events/:id/email-attendees/schedule', auth:'supervisor+', desc:'Schedule a bulk email to run at a future time', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ subject:'Reminder: Camp 2025', text:'Hi {{name}}, see you soon!', scheduledAt:'2025-07-03T09:00:00.000Z', filter:{ status:'paid' }}}, - responses:[{ status:201, desc:'Scheduled', body:{ job:{ id:'job-uuid-...', scheduledAt:'2025-07-03T09:00:00.000Z', status:'queued' }}}]}, - { method:'POST', path:'/api/events/:id/whatsapp-attendees', auth:'supervisor+', desc:'Send a bulk WhatsApp message to attendees with a phone number. Supports dryRun.', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ message:'Hi {{name}}, camp starts in 3 days! 🏕️', filter:{ status:'paid' }, dryRun:false }}, - responses:[ - { status:200, desc:'Sent', body:{ matched:12, sent:11 }}, - ]}, - { method:'POST', path:'/api/events/:id/whatsapp-attendees/schedule', auth:'supervisor+', desc:'Schedule a bulk WhatsApp message', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ message:'Hi {{name}}, final reminder for camp tomorrow! 🎉', scheduledAt:'2025-07-09T08:00:00.000Z', filter:{ status:'paid' }}}, - responses:[{ status:201, desc:'Scheduled', body:{ job:{ id:'job-uuid-...', status:'queued' }}}]}, - { method:'POST', path:'/api/events/:id/options', auth:'supervisor+', desc:'Add a ticket option to an event', - pathParams:{ ':id':'Event UUID' }, - request:{ body:{ name:'Child (under 12)', price:250, isMainTicket:false }}, - responses:[{ status:201, desc:'Created', body:{ id:'opt-uuid-new', name:'Child (under 12)', price:250, isMainTicket:false }}]}, - { method:'PUT', path:'/api/events/options/:id', auth:'supervisor+', desc:'Update a ticket option', - pathParams:{ ':id':'EventOption UUID' }, - request:{ body:{ price:300 }}, - responses:[{ status:200, desc:'Updated', body:{ id:'opt-uuid-...', price:300 }}]}, - { method:'DELETE', path:'/api/events/options/:id', auth:'admin', desc:'Delete a ticket option (fails if registrations exist)', - pathParams:{ ':id':'EventOption UUID' }, - responses:[ - { status:200, desc:'Deleted', body:{ message:'Option deleted.' }}, - { status:400, desc:'In use', body:{ message:'Cannot delete option with existing registrations.' }}, - ]}, - ]}, - - { title: 'Registrations', base: '/api/registrations', endpoints: [ - { method:'PUT', path:'/api/registrations/:id/options', auth:'Bearer (owner or staff)', desc:'Change the items on a registration (add/remove), within stock and paid-ticket limits' }, - { method:'POST', path:'/api/registrations/:id/coupon', auth:'Bearer (owner or staff)', desc:'Apply a coupon code to an existing registration', request:{ body:{ code:'STAFF50' }}}, - { method:'DELETE', path:'/api/registrations/:id/coupon', auth:'staff+', desc:'Remove the coupon from a registration (frees the use)' }, - { method:'GET', path:'/api/registrations/:id/forms/draft', auth:'Owner or staff', desc:'Saved draft of the attendee forms' }, - { method:'PUT', path:'/api/registrations/:id/forms/draft', auth:'Owner or staff', desc:'Save a draft of the attendee forms (not submitted)' }, - { method:'PUT', path:'/api/registrations/:id/forms/responses', auth:'supervisor+', desc:'Replace (edit) the submitted form responses of a registration' }, - { method:'POST', path:'/api/registrations', auth:'optional', desc:'Create a registration. Auth optional — guests are allowed when event does not require auth.', - request:{ body:{ eventId:'ev-uuid-...', options:[{ eventOptionId:'opt-uuid-...', quantity:2 }] }}, - responses:[ - { status:201, desc:'Created', body:{ id:'reg-uuid-...', eventId:'ev-uuid-...', status:'pending', checkoutId:null, createdAt:'2025-06-01T10:00:00.000Z' }}, - { status:400, desc:'Deadline passed', body:{ message:'Registration deadline has passed.' }}, - ]}, - { method:'GET', path:'/api/registrations/myregistrations', auth:'user+', desc:'Get all registrations for the authenticated user', - responses:[{ status:200, desc:'Success', body:[{ id:'reg-uuid-...', event:{ id:'ev-uuid-...', title:'Camp 2025' }, status:'paid', createdAt:'2025-06-01T10:00:00.000Z' }]}]}, - { method:'GET', path:'/api/registrations/:id', auth:'optional', desc:'Get registration detail by ID', - pathParams:{ ':id':'Registration UUID' }, - responses:[{ status:200, desc:'Success', body:{ id:'reg-uuid-...', status:'paid', event:{ title:'Camp 2025' }, registrationOptions:[{ eventOption:{ name:'Adult' }, quantity:1 }], payments:[{ amount:450, method:'card', status:'succeeded' }] }}]}, - { method:'PUT', path:'/api/registrations/:id', auth:'staff+', desc:'Update registration status. If set to "paid", generates tickets and emails them fire-and-forget. If downgraded from "paid", deletes unused tickets (blocks if any ticket has been scanned).', - pathParams:{ ':id':'Registration UUID' }, - request:{ body:{ status:'paid' }}, - responses:[{ status:200, desc:'Updated', body:{ id:'reg-uuid-...', status:'paid' }}]}, - { method:'DELETE', path:'/api/registrations/:id', auth:'user+', desc:'Cancel registration. Users: only allowed when no positive payments exist (returns 403 otherwise). Admins: always allowed.', - pathParams:{ ':id':'Registration UUID' }, - responses:[ - { status:200, desc:'Cancelled', body:{ message:'Registration cancelled', registration:{ id:'reg-uuid-...', status:'cancelled' }}}, - { status:400, desc:'Already cancelled', body:{ message:'Registration is already cancelled' }}, - { status:403, desc:'Payments exist — non-admin cannot cancel', body:{ message:'This registration has payments recorded against it and cannot be self-cancelled. Please contact the organisation for assistance.' }}, - { status:403, desc:'Not the owner (and not admin)', body:{ message:'Not authorized to cancel this registration' }}, - ]}, - { method:'GET', path:'/api/registrations', auth:'staff+', desc:'List all registrations across all events', - queryParams:{ page:'Page (default 1)', limit:'Per page (default 20)', eventId:'Filter by event', status:'Filter by status', search:'Search by name/email' }, - responses:[{ status:200, desc:'Success', body:{ data:[{ id:'reg-uuid-...', user:{ name:'Jane Doe' }, event:{ title:'Camp 2025' }, status:'paid' }], total:1, page:1 }}]}, - { method:'GET', path:'/api/registrations/event/:eventId', auth:'staff+', desc:'Get all registrations for a specific event', - pathParams:{ ':eventId':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:[{ id:'reg-uuid-...', user:{ id:'user-uuid-...', name:'Jane Doe', email:'jane@example.com', phoneNumber:'+27821234567' }, status:'paid' }]}]}, - { method:'PUT', path:'/api/registrations/:id/attendees', auth:'user+', desc:'Replace the named attendees on a registration (group tickets) and choose ticket delivery (payer | each). Owner or staff. Removing an attendee whose ticket was scanned is refused.', - request:{ body:{ attendees:[{ id:'att-uuid-...', eventOptionId:'opt-uuid-...', name:'Sam Smith', email:'sam@example.com' },{ eventOptionId:'opt-uuid-...', name:'Alex Smith' }], ticketDelivery:'each' }}, - responses:[{ status:200, desc:'Saved', body:{ id:'reg-uuid-...', ticketDelivery:'each', attendees:[{ id:'att-uuid-...', name:'Sam Smith', ticket:{ id:'tkt-uuid-...', isUsed:false }}] }}]}, - { method:'POST', path:'/api/registrations/:id/attendees/:attendeeId/send-form-link', auth:'user+', desc:'Email/WhatsApp a named attendee the link to fill in their own attendee form' }, - { method:'POST', path:'/api/registrations/bulk', auth:'supervisor+', desc:'Bulk actions on ticked registrations (up to 500), each run through the same code as doing it one at a time: action "markPaid" { method: cash|eft|card|other, paidAt? } records the balance; "cancel"; "moveOption" { fromOptionId, toOptionId } (same event); "allocate" { setId, groupId } places their named people; "message" { channel: email|whatsapp, subject?, text } sends an event update. Answers { action, done, skipped, failed, results: [{ id, ok, skipped?, message }] }. Campus-checked for every id; payments and ticket changes refused in licence read-only mode. Audited as registrations_bulk', - request:{ body:{ action:'markPaid', registrationIds:['reg-uuid-1','reg-uuid-2'], method:'cash' } } }, - { method:'POST', path:'/api/registrations/manual', auth:'supervisor+', desc:'Manually create a registration (at-the-door / walk-in). Resolves early-bird tier pricing (including per-variant tiers) and stores priceSnapshot + appliedTierId on each option. Creates or finds a matching user by email/phone. If a matching user is found, updates their notificationPreference and backfills a missing phone number or guest placeholder email with the newly supplied value (without overwriting existing contact info). Generates a Yoco checkout link for unpaid registrations to include in the self-service notification email.', - request:{ body:{ eventId:'ev-uuid-...', user:{ name:'Jane Doe', email:'jane@example.com', phoneNumber:'0821234567' }, options:[{ eventOptionId:'opt-uuid-...', quantity:1, variantId:'var-uuid-...' }], notificationPreference:'email' }}, - responses:[{ status:201, desc:'Created', body:{ id:'reg-uuid-new', status:'pending' }}]}, - { method:'POST', path:'/api/registrations/:id/forms/responses', auth:'optional', desc:'Submit form responses for a registration', - pathParams:{ ':id':'Registration UUID' }, - request:{ body:{ answers:[{ fieldId:'field-uuid-...', value:'Yes' }, { fieldId:'field-uuid-2', value:'Vegetarian' }] }}, - responses:[{ status:201, desc:'Submitted', body:{ id:'response-uuid-...', createdAt:'2025-06-01T10:05:00.000Z' }}]}, - { method:'POST', path:'/api/registrations/:id/send-invoice', auth:'user+', desc:'(Re)generate the invoice PDF for one of the caller\'s own registrations and send it on the requested channel — email or WhatsApp. Works regardless of balance (shows "Paid in full" when nothing is owed); fails only if there is no valid email/phone on file for the chosen channel.', - notes:'The PDF\'s invoiceNo is derived, not sequential: INV--. When there is an outstanding balance, generates a fresh Yoco checkout link for the invoice\'s QR code/pay-now link on each call.', - pathParams:{ ':id':'Registration UUID' }, - request:{ body:{ channel:'email' }}, - responses:[ - { status:200, desc:'Sent', body:{ message:'Invoice emailed.' }}, - { status:400, desc:'No valid contact for channel', body:{ message:'No valid email address on file. Add one in your profile.' }}, - { status:403, desc:'Not the owner', body:{ message:'Not authorized to access this registration' }}, - ]}, - ]}, - - { title: 'Impersonation', base: '/api/admin', endpoints: [ - { method:'GET', path:'/api/admin/audit-log', auth:'admin', desc:'Paginated admin/supervisor audit trail (?page, limit, actorId, action, role, from, to, search)' }, - { method:'GET', path:'/api/admin/jobs', auth:'admin', desc:'Background jobs: queue mode, timezone, and each job schedule, next run and last 10 runs' }, - { method:'POST', path:'/api/admin/jobs/:name/run', auth:'admin', desc:'Run a background job now (queued for a worker); audit-logged' }, - { method:'POST', path:'/api/admin/impersonate/:userId', auth:'admin (2FA)', desc:'View the site as a user — read-only token, 30 minutes, audited', request:{ body:{ reason:'Ticket not showing in My Events' }}, responses:[{ status:201, desc:'Started', body:{ token:'jwt…', session:{ id:'sess-uuid', expiresAt:'2025-07-10T08:45:00.000Z' }}}, { status:403, desc:'Not allowed', body:{ message:"Admins can't be impersonated." }}]}, - { method:'POST', path:'/api/admin/impersonate/end', auth:'impersonation token', desc:'End the impersonation session' }, - { method:'POST', path:'/api/admin/impersonate/log', auth:'impersonation token', desc:'Record a page viewed during the session' }, - { method:'GET', path:'/api/admin/impersonate/current', auth:'impersonation token', desc:'The live impersonation session' }, - { method:'GET', path:'/api/admin/impersonation-sessions', auth:'admin', desc:'Impersonation sessions with their request trail' }, - ]}, - { title: 'Registration funnel', base: '/api/analytics', endpoints: [ - { method:'POST', path:'/api/analytics/track', auth:'Public (rate-limited)', desc:'Record a funnel step from a cookie-consented browser (always 204)', - request:{ body:{ sessionId:'random-uuid', eventId:'ev-uuid-...', stage:'view', source:'camp-2025' }}}, - { method:'GET', path:'/api/analytics/funnel', auth:'supervisor+', desc:'Funnel for ?eventIds=a,b&from=&to= — totals, conversion, daily trend, by source/device/option' }, - ]}, - { title: 'Post-event feedback', base: '/api/feedback', endpoints: [ - { method:'GET', path:'/api/feedback/event/:eventId', auth:'supervisor+', desc:'An event\'s feedback form, with invite and response counts' }, - { method:'PUT', path:'/api/feedback/event/:eventId', auth:'supervisor+', desc:'Create/update the feedback form (questions lock once answered)', - request:{ body:{ sendAt:'2025-07-13T09:00:00.000Z', audience:'checked_in', anonymous:false, intro:'Thanks for coming!', fields:[{ type:'rating', label:'Overall?', isRequired:true }, { type:'multiple_choice', label:'Best part', options:['Worship','Talks'] }] }}}, - { method:'DELETE', path:'/api/feedback/event/:eventId', auth:'supervisor+', desc:'Remove the feedback form' }, - { method:'POST', path:'/api/feedback/event/:eventId/send-now', auth:'supervisor+', desc:'Send the feedback form now' }, - { method:'GET', path:'/api/feedback/public/:token', auth:'Link holder', desc:'The form behind a personal feedback link' }, - { method:'POST', path:'/api/feedback/public/:token', auth:'Link holder', desc:'Submit feedback once', request:{ body:{ answers:{ 'field-uuid':'5' } }}}, - { method:'GET', path:'/api/feedback/summary', auth:'supervisor+', desc:'Feedback summary for ?eventIds=a,b (response rate, averages, breakdowns, comments)' }, - ]}, - { title: 'Sponsor a spot', base: '/api/sponsorships', endpoints: [ - { method:'GET', path:'/api/sponsorships/event/:eventId', auth:'Public', desc:'Sponsorship progress for an event (spots funded, goal) — never who was helped', - responses:[{ status:200, desc:'Progress', body:{ enabled:true, open:true, spotPrice:450, showProgress:true, goalSpots:20, spotsFunded:12, sponsors:9 }}]}, - { method:'POST', path:'/api/sponsorships/checkout', auth:'Public (optional login)', desc:'Start a Yoco checkout to sponsor spots or a custom amount; the money lands in the event sponsorship pool', - request:{ body:{ eventId:'ev-uuid-...', spots:2, anonymous:false, sponsorName:'The Smith family', message:'Have a great camp!', name:'Sam Smith', email:'sam@example.com' }}, - responses:[{ status:200, desc:'Checkout created', body:{ redirectUrl:'https://pay.yoco.com/...', amount:900 }}]}, - { method:'GET', path:'/api/sponsorships/event/:eventId/pool', auth:'supervisor+', desc:'Sponsorship pool totals: received, assigned, remaining' }, - ]}, - { title: 'Rooms & groups', base: '/api/allocations', endpoints: [ - { method:'GET', path:'/api/allocations/event/:eventId', auth:'supervisor+', desc:'Allocation board: sets with groups and assignments, named attendees, possible leaders' }, - { method:'POST', path:'/api/allocations/sets', auth:'supervisor+', desc:'Create an allocation set', request:{ body:{ eventId:'ev-uuid-...', name:'Rooms', showOnTicket:true }}}, - { method:'PUT', path:'/api/allocations/sets/:id', auth:'supervisor+', desc:'Rename a set or show it on tickets' }, - { method:'DELETE', path:'/api/allocations/sets/:id', auth:'supervisor+', desc:'Delete a set and its groups' }, - { method:'POST', path:'/api/allocations/sets/:id/groups', auth:'supervisor+', desc:'Add a group', request:{ body:{ name:'Cabin 1', capacity:8, gender:'female', leaderUserId:'user-uuid-...' }}}, - { method:'PUT', path:'/api/allocations/groups/:id', auth:'supervisor+', desc:'Edit a group' }, - { method:'DELETE', path:'/api/allocations/groups/:id', auth:'supervisor+', desc:'Delete a group (its people become unassigned)' }, - { method:'PUT', path:'/api/allocations/sets/:id/assignments', auth:'supervisor+', desc:'Place (or with groupId null, unplace) an attendee; enforces capacity and gender', request:{ body:{ attendeeId:'att-uuid-...', groupId:'grp-uuid-...' }}}, - { method:'DELETE', path:'/api/allocations/sets/:id/assignments', auth:'supervisor+', desc:'Clear every assignment in a set' }, - { method:'POST', path:'/api/allocations/sets/:id/auto', auth:'supervisor+', desc:'Auto-allocate everyone not yet placed', request:{ body:{ mode:'together' }}, responses:[{ status:200, desc:'Done', body:{ placed:12, unplaced:1 }}]}, - { method:'GET', path:'/api/allocations/sets/:id/lists', auth:'supervisor+', desc:'Per-group lists for printing (?medical=true adds medical details; audited)' }, - { method:'GET', path:'/api/allocations/my-groups', auth:'staff+', desc:'Groups the signed-in leader leads, with their people' }, - ]}, - { title: 'Ticket transfer', base: '/api/tickets', endpoints: [ - { method:'DELETE', path:'/api/tickets/:id/transfer', auth:'payer, holder or supervisor+', desc:'Withdraw a transfer offer that has not been accepted yet' }, - { method:'GET', path:'/api/tickets/transfer-offer/:token', auth:'Link holder', desc:'The ticket offered behind a transfer link (status, event, ticket type, sender first name)' }, - { method:'POST', path:'/api/tickets/transfer-offer/:token/accept', auth:'Link holder', desc:'Accept the ticket — the transfer happens now (new QR code, ticket sent to the new holder)' }, - { method:'POST', path:'/api/tickets/transfer-offer/:token/decline', auth:'Link holder', desc:'Decline the ticket offer' }, - { method:'POST', path:'/api/tickets/:id/transfer', auth:'payer, holder or supervisor+', desc:'Give a ticket to someone else before the event (new QR code; the old one stops working; billing stays with the payer)', - request:{ body:{ name:'Nia New', email:'nia@example.com', phone:'0821234567' }}, - responses:[{ status:200, desc:'Transferred', body:{ message:'Ticket transferred to Nia New…', ticketId:'ticket-uuid-...' }}, { status:400, desc:'Not allowed', body:{ message:'This ticket has already been used (or partly used), so it can’t be transferred.' }}]}, - { method:'GET', path:'/api/tickets/:id/transfers', auth:'payer, holder or staff+', desc:'Transfer history of a ticket' }, - ]}, - { title: 'Offline scanning', base: '/api/scan-locks', endpoints: [ - { method:'GET', path:'/api/scan-locks', auth:'staff+', desc:'Active offline locks for an event (?eventId=)' }, - { method:'POST', path:'/api/scan-locks', auth:'staff+', desc:'Lock a section (or the whole event) to this device for offline scanning', - request:{ body:{ eventId:'ev-uuid-...', sectionId:'sec-uuid-...', deviceId:'device-uuid', deviceName:'Chrome on Android' }}, - responses:[{ status:201, desc:'Locked', body:{ id:'lock-uuid-...', sectionName:'Main hall' }}, { status:409, desc:'Held elsewhere', body:{ message:'"Main hall" is offline-locked by Ann on Chrome on Android.' }}]}, - { method:'GET', path:'/api/scan-locks/:id/snapshot', auth:'staff+', desc:'Tickets valid in the lock scope, for the device to keep offline (lock holder, ?deviceId=)' }, - { method:'POST', path:'/api/scan-locks/:id/sync', auth:'staff+', desc:'Upload offline scans (idempotent by clientScanId; capped at what is left on each ticket)', - request:{ body:{ deviceId:'device-uuid', scans:[{ clientScanId:'scan-uuid', qrCode:'qr-uuid', qty:1, scannedAt:'2025-07-10T08:15:00.000Z' }] }}, - responses:[{ status:200, desc:'Synced', body:{ accepted:1, duplicates:0, conflicts:[] }}]}, - { method:'DELETE', path:'/api/scan-locks/:id', auth:'staff+', desc:'End offline mode (lock holder)' }, - { method:'POST', path:'/api/scan-locks/:id/force-release', auth:'supervisor+', desc:'Release a lost device\'s lock' }, - { method:'GET', path:'/api/scan-locks/reports', auth:'supervisor+', desc:'Offline sync reports for an event' }, - { method:'POST', path:'/api/scan-locks/reports/:id/review', auth:'supervisor+', desc:'Mark a sync report reviewed' }, - ]}, - { title: 'Waitlist', base: '/api/waitlist', endpoints: [ - { method:'POST', path:'/api/waitlist', auth:'public', desc:'Join the waitlist for a sold-out line (login needed when the event requires it)', - request:{ body:{ eventId:'ev-uuid-...', eventOptionId:'opt-uuid-...', quantity:2 }}, - responses:[{ status:201, desc:'Joined', body:{ id:'wl-uuid-...', status:'waiting', ahead:3 }}, { status:400, desc:'Places available', body:{ message:'There are places available — you can register now.' }}]}, - { method:'GET', path:'/api/waitlist/mine', auth:'user+', desc:'My active waitlist entries' }, - { method:'DELETE', path:'/api/waitlist/:id', auth:'user+', desc:'Leave the waitlist' }, - { method:'GET', path:'/api/waitlist/claim/:token', auth:'public', desc:'What a claim link offers (rate-limited)' }, - { method:'GET', path:'/api/waitlist/events/:eventId', auth:'staff+', desc:'The queue for an event' }, - { method:'POST', path:'/api/waitlist/:id/offer', auth:'supervisor+', desc:'Offer places now, even over the stock limit' }, - { method:'POST', path:'/api/waitlist/:id/move', auth:'supervisor+', desc:'Move up or down the queue', request:{ body:{ direction:'up' }} }, - { method:'POST', path:'/api/waitlist/:id/remove', auth:'supervisor+', desc:'Take someone off the waitlist' }, - ]}, - { title: 'Attendance & certificates', base: '/api/attendance', endpoints: [ - { method:'GET', path:'/api/attendance/:eventId', auth:'staff+', desc:'Attendance register: sessions (columns), one row per main ticket with check-ins per session, completion and certificate', - responses:[{ status:200, desc:'Register', body:{ event:{ id:'ev-uuid-...', scheduleType:'sessions' }, columns:[{ id:'ses-uuid-...', label:'Week 1', startsAt:'2026-11-04T16:30:00.000Z', cancelled:false }], rows:[{ ticketId:'t-uuid-...', name:'Thandi', checkIns:{ 'ses-uuid-...':1 }, attended:1, total:5, completed:false, certificate:null }], totals:{ 'ses-uuid-...':12 } }}]}, - { method:'GET', path:'/api/attendance/:eventId/export?format=xlsx|pdf', auth:'staff+', desc:'Download the register as Excel or PDF' }, - { method:'POST', path:'/api/attendance/:eventId/mark', auth:'supervisor+', desc:'Mark a ticket present/absent for a session (single-date events use sessionId "event")', request:{ body:{ ticketId:'t-uuid-...', sessionId:'ses-uuid-...', present:true }} }, - { method:'POST', path:'/api/attendance/:eventId/certificates', auth:'supervisor+', desc:'Issue certificates now to everyone eligible, or to one ticket (even if not eligible)', request:{ body:{ ticketId:'t-uuid-... (optional)' }} }, - { method:'POST', path:'/api/attendance/:eventId/certificates/send', auth:'supervisor+', desc:'Email/WhatsApp unsent certificates, or one again', request:{ body:{ certificateId:'(optional)' }} }, - { method:'GET', path:'/api/attendance/:eventId/certificates.pdf', auth:'supervisor+', desc:'All of an event\'s certificates in one PDF' }, - { method:'POST', path:'/api/attendance/certificates/preview', auth:'supervisor+', desc:'Sample certificate PDF with unsaved settings', request:{ body:{ title:'Alpha Course', config:{ template:'classic' } }} }, - { method:'POST', path:'/api/attendance/certificates/:id/revoke', auth:'supervisor+', desc:'Revoke a certificate (never re-issued automatically)' }, - { method:'GET', path:'/api/attendance/certificates/mine', auth:'user+', desc:'My certificates' }, - { method:'GET', path:'/api/attendance/certificates/:id/pdf', auth:'user+', desc:'Download a certificate (its person, the booker, or a supervisor)' }, - { method:'GET', path:'/api/attendance/certificates/verify/:code', auth:'public', desc:'Check a certificate code — name, event and dates only', responses:[{ status:200, desc:'Result', body:{ valid:true, name:'Thandi Mokoena', event:'Alpha Course', completedOn:'2026-12-02T18:30:00.000Z' }}] }, - ]}, - { title: 'Parental consent', base: '/api/consent', endpoints: [ - { method:'GET', path:'/api/consent/:token', auth:'public', desc:'Consent page data for a parent/guardian (the link token is the credential; rate-limited)', - responses:[{ status:200, desc:'Success', body:{ status:'pending', attendeeName:'Sam Smith', consentText:'I give permission…', event:{ title:'Youth Camp' }, collect:{ medical:true, emergency:true, photo:true } }}, { status:404, desc:'Unknown or replaced link', body:{ message:'This consent link is not valid.' }}]}, - { method:'POST', path:'/api/consent/:token', auth:'public', desc:'Give or decline consent. Records name, time, IP, device and the consent text version; medical/emergency details are stored encrypted.', - request:{ body:{ decision:'give', signedName:'Pat Smith', isGuardian:true, medical:{ allergies:'Peanuts' }, emergency:{ name:'Gran', phone:'0821234567' }, photoConsent:true }}, - responses:[{ status:200, desc:'Answered', body:{ status:'given' }}, { status:409, desc:'Already answered', body:{ message:'Consent has already been given.' }}]}, - { method:'GET', path:'/api/consent/events/:eventId', auth:'staff+', desc:'Consent status for every attendee on an event' }, - { method:'POST', path:'/api/consent/requests/:id/resend', auth:'user+', desc:'Re-send a pending request with a fresh link (registrant or staff)' }, - { method:'POST', path:'/api/consent/events/:eventId/resend-pending', auth:'supervisor+', desc:'Re-send every pending request on an event' }, - { method:'POST', path:'/api/consent/events/:eventId/rerequest', auth:'supervisor+', desc:'Ask again where consent was given on an older version of the text, or never requested' }, - { method:'GET', path:'/api/consent/events/:eventId/medical', auth:'supervisor+', desc:'Decrypted medical & emergency list; every view is written to the admin audit log' }, - ]}, - { title: 'Coupons', base: '/api/coupons', endpoints: [ - { method:'POST', path:'/api/coupons/validate', auth:'public', desc:'Check a code against a basket before registering; returns the discount. Login needed for restricted codes; staff can pass forUserId (or null for a walk-in).', - request:{ body:{ code:'STAFF50', eventId:'ev-uuid-...', options:[{ eventOptionId:'opt-uuid-...', quantity:2 }] }}, - responses:[ - { status:200, desc:'Valid (bundle deals come off first, then the code)', body:{ valid:true, code:'STAFF50', type:'percent', value:50, summary:'50% off', discount:450, bundleDiscount:0, bundles:[], subtotal:900, total:450 }}, - { status:400, desc:'Not usable', body:{ valid:false, message:'This code has expired.' }}, - ]}, - { method:'GET', path:'/api/coupons', auth:'supervisor+', desc:'List codes with use counts and total discount given', - responses:[{ status:200, desc:'Success', body:[{ id:'cpn-uuid-...', code:'STAFF50', type:'percent', value:50, summary:'50% off', active:true, uses:3, totalDiscount:1350 }]}]}, - { method:'POST', path:'/api/coupons', auth:'supervisor+', desc:'Create a code. type: percent | fixed | comp. eventIds/options/userIds/restrictRoles/restrictDomain are optional.', - request:{ body:{ code:'STAFF50', type:'percent', value:50, eventIds:['ev-uuid-...'], restrictRoles:['staff','supervisor','admin'], maxUsesPerUser:1, stackEarlyBird:false }}, - responses:[{ status:201, desc:'Created', body:{ id:'cpn-uuid-...', code:'STAFF50' }}, { status:409, desc:'Code exists', body:{ message:'The code STAFF50 already exists' }}]}, - { method:'GET', path:'/api/coupons/:id', auth:'supervisor+', desc:'One code with every use (redemption)' }, - { method:'PUT', path:'/api/coupons/:id', auth:'supervisor+', desc:'Edit a code or turn it off ({ active:false }). Discounts already given keep their amount; a used code can\'t be renamed.' }, - { method:'GET', path:'/api/coupons/redemptions', auth:'supervisor+', desc:'Active uses for the Discounts report. Query: eventIds (comma-separated), from, to' }, - ]}, - { title: 'Bundle deals', base: '/api/bundles', endpoints: [ - { method:'POST', path:'/api/bundles/quote', auth:'public', desc:'The bundle deals a basket gets, applied automatically as many times as they fit and only when cheaper. Staff can pass forUserId (or null for a walk-in).', - request:{ body:{ eventId:'ev-uuid-...', options:[{ eventOptionId:'opt-adult', quantity:5 }, { eventOptionId:'opt-child', quantity:3 }] }}, - responses:[{ status:200, desc:'Success', body:{ subtotal:550, bundleDiscount:50, bundles:[{ bundleId:'bnd-uuid-...', name:'Family deal', count:1, discount:50 }], total:500 }}]}, - { method:'GET', path:'/api/bundles/event/:eventId', auth:'supervisor+', desc:'An event\'s bundles with uses and total discount given' }, - { method:'POST', path:'/api/bundles/event/:eventId', auth:'supervisor+', desc:'Create a bundle. kind: exact (items with quantities, price for the set) | mix (any setSize of the items for price) | free (any setSize, cheapest freeCount free) | group (setSize or more of the items: groupPricing per_ticket price each, or percent off). items: [{ eventOptionId, variantId?, quantity }] (variantId left out = any variant; quantity only for exact).', - request:{ body:{ name:'Family deal', price:500, items:[{ eventOptionId:'opt-adult', quantity:5 }, { eventOptionId:'opt-child', quantity:3 }], validUntil:null }}}, - { method:'PUT', path:'/api/bundles/:id', auth:'supervisor+', desc:'Edit a bundle or switch it off ({ isActive:false }). Registrations keep a bundle they already have.' }, - { method:'DELETE', path:'/api/bundles/:id', auth:'supervisor+', desc:'Delete a bundle; one that has been used is switched off instead' }, - ]}, - { title: 'Payments', base: '/api/payments', endpoints: [ - { method:'GET', path:'/api/payments/:id', auth:'Bearer', desc:'A payment by id' }, - { method:'GET', path:'/api/payments/registration/:registrationId', auth:'Bearer', desc:'Payments of a registration' }, - { method:'POST', path:'/api/payments/checkout/send', auth:'supervisor+', desc:'Send a generated payment link to the registrant by email or WhatsApp (also at /api/payments/yoco-checkout/send)', request:{ body:{ registrationId:'reg-uuid-...', redirectUrl:'https://pay.yoco.com/...', channel:'whatsapp' }}}, - { method:'GET', path:'/api/payments/providers', auth:'—', desc:'Payment providers people can pay with now (enabled in Site settings → Payments and set up), in display order, plus the online minimum (R15)', - responses:[{ status:200, desc:'Success', body:{ providers:[{ id:'yoco', label:'Yoco' }], minimumAmount:15 }}]}, - { method:'GET', path:'/api/payments/pay/:id', auth:'— (checkout id)', desc:'The payer\'s page for a checkout: amount, description, providers to choose from, or the PayFast form to post' }, - { method:'POST', path:'/api/payments/pay/:id', auth:'— (checkout id)', desc:'Start the checkout with the provider the payer picked: { provider } → { redirectUrl } or { form }' }, - { method:'GET', path:'/api/payments/checkouts/open', auth:'supervisor+', desc:'Online checkouts from the last 14 days with no payment yet, and whether their provider can be asked (canCheck)' }, - { method:'POST', path:'/api/payments/checkouts/check', auth:'supervisor+', desc:'Ask providers whether checkouts were paid ({ ids? }, default all open) and record what they received. PayFast: transaction history; Yoco: cant_check' }, - { method:'GET', path:'/api/payments/providers/settings', auth:'admin', desc:'Every provider with enabled, configured and capabilities ({ refund, getTransaction, listTransactions }), in display order' }, - { method:'PUT', path:'/api/payments/providers/settings', auth:'admin', desc:'Turn providers on/off and set their order (the list order). Audit logged.', - request:{ body:{ providers:[{ id:'yoco', enabled:true }] }}}, - { method:'POST', path:'/api/payments/unassign-donation', auth:'supervisor+', desc:'Reverse a donation assignment (removes the leg and reverts the registration status)' }, - { method:'POST', path:'/api/payments/checkout', auth:'user+', desc:'Start an online checkout (also at /api/payments/yoco-checkout) with body.provider, or the first enabled provider. At least R15 (all providers). Before creating the checkout, re-evaluates early-bird tier eligibility (deadline + stock). If any price changed since registration, returns priceUpdated:true instead of creating a checkout — the client must inform the user and retry.', - request:{ body:{ registrationId:'reg-uuid-...', amount:450, provider:'yoco', successUrl:'https://events.example.com/payment/success', cancelUrl:'https://events.example.com/payment/cancel', failureUrl:'https://events.example.com/payment/failure' }}, - responses:[ - { status:200, desc:'Checkout created — send the payer to redirectUrl', body:{ redirectUrl:'https://pay.yoco.com/checkout/abc123', checkoutId:'yoco-checkout-id', provider:'yoco', amount:450 }}, - { status:200, desc:'Early-bird price changed — checkout NOT created. Frontend must show warning and let user confirm before retrying.', body:{ priceUpdated:true, newTotal:500, message:'One or more early-bird prices have changed since your registration was created. Please review the updated total before proceeding.' }}, - ]}, - { method:'POST', path:'/api/payments', auth:'supervisor+', desc:'Record a manual payment (cash, EFT, etc.)', - request:{ body:{ registrationId:'reg-uuid-...', amount:450, method:'cash', userId:'user-uuid-...' }}, - responses:[ - { status:201, desc:'Recorded', body:{ id:'pay-uuid-...', amount:450, method:'cash', status:'succeeded', createdAt:'2025-06-10T09:00:00.000Z' }}, - ]}, - { method:'GET', path:'/api/payments/mypayments', auth:'user+', desc:'Get own payment history (paginated, excludes donations). Returned method is normalized to cash|card|eft|voucher|other — apple_pay/google_pay report as "card", any other gateway-reported value reports as "other"', - queryParams:{ page:'Page (default 1)', limit:'Per page (default 25, max 25)', startDate:'ISO date, filters createdAt >=', endDate:'ISO date, filters createdAt <=', method:'Filter by normalized method: cash|card|eft|voucher|other', kind:'payment|refund — filters by amount sign' }, - responses:[{ status:200, desc:'Success', body:{ data:[{ id:'pay-uuid-...', amount:450, method:'card', status:'succeeded', createdAt:'2025-06-01T11:00:00.000Z' }], total:1, page:1, limit:25, pages:1 }}]}, - { method:'POST', path:'/api/payments/:id/send-receipt', auth:'user+', desc:'Regenerate the receipt PDF for one of the caller\'s own payments and send it on the requested channel — email or WhatsApp. Fails if there is no valid email/phone on file for the chosen channel.', - notes:'The PDF\'s receiptNo is derived, not sequential: RCPT--.', - pathParams:{ ':id':'Payment UUID' }, - request:{ body:{ channel:'whatsapp' }}, - responses:[ - { status:200, desc:'Sent', body:{ message:'Receipt sent to WhatsApp.' }}, - { status:403, desc:'Not the owner', body:{ message:'Not authorized to access this payment' }}, - ]}, - { method:'GET', path:'/api/payments', auth:'supervisor+', desc:'List all payments', - queryParams:{ page:'Page (default 1)', limit:'Per page (default 20)', eventId:'Filter by event', userId:'Filter by user', method:'Filter by method (cash|card|eft|donation)', startDate:'ISO date', endDate:'ISO date' }, - responses:[{ status:200, desc:'Success', body:{ data:[{ id:'pay-uuid-...', amount:450, method:'card', user:{ name:'Jane Doe' }, registration:{ event:{ title:'Camp 2025' }}}], total:1 }}]}, - { method:'GET', path:'/api/payments/event/:eventId', auth:'staff+', desc:'All payments for an event', - pathParams:{ ':eventId':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:[{ id:'pay-uuid-...', amount:450, user:{ name:'Jane Doe' }, method:'card' }]}]}, - { method:'POST', path:'/api/payments/refund', auth:'supervisor+', desc:'Create a refund payment (negative amount)', - request:{ body:{ originalPaymentId:'pay-uuid-...', amount:450, reason:'Cancelled registration' }}, - responses:[{ status:201, desc:'Refund recorded', body:{ id:'pay-uuid-refund', amount:-450, method:'refund' }}]}, - { method:'PUT', path:'/api/payments/assign-donation', auth:'supervisor+', desc:'Link an unassigned donation payment to a specific registration', - request:{ body:{ paymentId:'pay-uuid-...', registrationId:'reg-uuid-...' }}, - responses:[{ status:200, desc:'Assigned', body:{ id:'pay-uuid-...', registrationId:'reg-uuid-...', isDonation:false }}]}, - { method:'GET', path:'/api/payments/admin/stats', auth:'admin', desc:'Aggregated payment statistics', - responses:[{ status:200, desc:'Success', body:{ totalRevenue:98500, totalPayments:215, byMethod:{ card:180, cash:30, eft:5 }, byEvent:[{ eventId:'ev-uuid-...', title:'Camp 2025', total:45000 }] }}]}, - ]}, - - { title: 'Tickets', base: '/api/tickets', endpoints: [ - { method:'GET', path:'/api/tickets', auth:'supervisor+', desc:'All tickets' }, - { method:'GET', path:'/api/tickets/:id', auth:'Bearer (owner or staff)', desc:'A ticket by id' }, - { method:'GET', path:'/api/tickets/qr/:qrCode', auth:'staff+', desc:'A ticket by QR code' }, - { method:'PUT', path:'/api/tickets/email-sent', auth:'admin', desc:'Mark tickets as emailed' }, - { method:'GET', path:'/api/tickets/mytickets', auth:'user+', desc:'Get own tickets', - responses:[{ status:200, desc:'Success', body:[{ id:'tkt-uuid-...', qrCode:'TKT-ABC123', event:{ title:'Camp 2025' }, registrationOption:{ eventOption:{ name:'Adult' }}, quantity:1, isUsed:false }]}]}, - { method:'POST', path:'/api/tickets/generate', auth:'supervisor+', desc:'Generate tickets for a registration (idempotent — skips already-generated options)', - request:{ body:{ registrationId:'reg-uuid-...' }}, - responses:[{ status:201, desc:'Generated', body:{ created:2, skipped:0, tickets:[{ id:'tkt-uuid-...', qrCode:'TKT-ABC123' }] }}]}, - { method:'POST', path:'/api/tickets/scan/:qrCode', auth:'staff+', desc:'Scan and redeem a ticket', - pathParams:{ ':qrCode':'QR code string from ticket' }, - request:{ body:{ quantity:1 }}, - responses:[ - { status:200, desc:'Scanned', body:{ ticket:{ id:'tkt-uuid-...', qrCode:'TKT-ABC123', isUsed:true }, event:{ title:'Camp 2025' }, user:{ name:'Jane Doe' }, quantityRedeemed:1, remainingUses:0 }}, - { status:400, desc:'Already used', body:{ message:'Ticket has already been fully redeemed.' }}, - { status:404, desc:'Not found', body:{ message:'Ticket not found.' }}, - ]}, - { method:'GET', path:'/api/tickets/scan-preview/:qrCode', auth:'staff+', desc:'Preview a ticket scan without marking it used', - pathParams:{ ':qrCode':'QR code string' }, - responses:[{ status:200, desc:'Preview', body:{ ticket:{ qrCode:'TKT-ABC123', quantity:2, isUsed:false }, event:{ title:'Camp 2025' }, user:{ name:'Jane Doe', phoneNumber:'+27821234567' }, totalRedeemed:0 }}]}, - { method:'POST', path:'/api/tickets/email', auth:'user+', desc:'Email own tickets as PDF attachments', - responses:[{ status:200, desc:'Sent', body:{ message:'Tickets emailed.', count:2 }}]}, - { method:'POST', path:'/api/tickets/send-to', auth:'staff+', desc:'Send tickets to a specific user by email or WhatsApp', - request:{ body:{ userId:'user-uuid-...', eventId:'ev-uuid-...', channel:'email' }}, - responses:[{ status:200, desc:'Sent', body:{ sent:2 }}]}, - { method:'GET', path:'/api/tickets/event/:eventId', auth:'staff+', desc:'All tickets for an event', - pathParams:{ ':eventId':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:[{ id:'tkt-uuid-...', qrCode:'TKT-ABC123', user:{ name:'Jane Doe' }, isUsed:false, quantity:1 }]}]}, - { method:'GET', path:'/api/tickets/scans/recent', auth:'staff+', desc:'Last 50 scan events across all events', - responses:[{ status:200, desc:'Success', body:[{ ticketId:'tkt-uuid-...', scannedAt:'2025-07-10T09:05:00.000Z', quantityRedeemed:1, ticket:{ user:{ name:'Jane Doe' }, event:{ title:'Camp 2025' }}, scannedBy:{ name:'Staff Member' }}]}]}, - { method:'GET', path:'/api/tickets/scans/stats', auth:'staff+', desc:'Scan statistics grouped by event', - responses:[{ status:200, desc:'Success', body:[{ eventId:'ev-uuid-...', title:'Camp 2025', totalTickets:50, scanned:38, remaining:12 }]}]}, - ]}, - - { title: 'Hub and licence', base: '/api/hub', endpoints: [ - { method:'GET', path:'/health', auth:'public', desc:'Status, version, database, background jobs and last backup (503 if the database is down)', - responses:[{ status:200, desc:'Healthy', body:{ status:'ok', version:'1.41.0', db:true, jobs:{ mode:'queue', failedLast24h:0 }, lastBackupAt:'2026-10-26T00:00:12.000Z' }}]}, - { method:'GET', path:'/api/hub/status', auth:'admin', desc:'Licence state (active, grace, suspended, revoked, unlicensed), Hub connection, version and update', - responses:[{ status:200, desc:'Success', body:{ state:'grace', readOnly:false, daysLeft:9, connected:true, version:'1.41.0', latestVersion:'1.42.0', updateAvailable:true }}]}, - { method:'POST', path:'/api/hub/connect', auth:'admin', desc:'Connect to the Cross Events Hub with a licence key (also the /setup licence step)', - request:{ body:{ licenceKey:'CEH-7K2M-9QXA-P4RT-WD8C' } }, - responses:[{ status:200, desc:'Connected (status as above)' }, { status:404, desc:'Unknown key', body:{ code:'LICENCE_NOT_FOUND', message:'That licence key was not found.' }}]}, - { method:'POST', path:'/api/hub/heartbeat', auth:'admin', desc:'Check in with the Hub now (picks up licence changes)', - responses:[{ status:200, desc:'Status' }, { status:502, desc:'Hub unreachable' }]}, - { method:'POST', path:'/api/hub/update-request', auth:'admin', desc:'Ask the Hub for this site to be updated to the latest version (the provider is told; the site never updates itself)', - responses:[{ status:200, desc:'Status, with updateRequest', body:{ updateAvailable:true, updateRequest:{ requestedAt:'2026-10-27T09:00:00.000Z', version:'1.42.0' } }}, { status:409, desc:'Already on the latest version', body:{ code:'UP_TO_DATE', message:'This site already runs the latest version.' }}, { status:502, desc:'Hub unreachable' }]}, - { method:'POST', path:'/api/hub/update-request/cancel', auth:'admin', desc:'Withdraw the update request (the provider is told not to update after all)', - responses:[{ status:200, desc:'Status, updateRequest null' }, { status:502, desc:'Hub unreachable, or a Hub too old to withdraw requests (NOT_SUPPORTED)' }]}, - { method:'POST', path:'/api/hub/update-snooze', auth:'admin', desc:'"Not now": no update reminders until a newer version is out. { snooze: false } turns them back on', - request:{ body:{ snooze:true } }, - responses:[{ status:200, desc:'Status', body:{ updateAvailable:true, updateSnoozed:true } }, { status:400, desc:'No update, or an urgent one (can\'t be put off)' }]}, - { method:'GET', path:'/api/hub/notices', auth:'supervisor', desc:'The provider\'s notices showing now (the dashboard banner for site admins and supervisors)', - responses:[{ status:200, desc:'Success', body:[{ id:'…', level:'maintenance', title:'Planned maintenance', message:'The site will be down for 30 minutes.', startsAt:'2026-11-01T16:00:00.000Z', endsAt:'2026-11-01T16:30:00.000Z' }] }]}, - ]}, - - { title: 'Campuses', base: '/api/campuses', endpoints: [ - { method:'GET', path:'/api/campuses', auth:'Public', desc:'Whether campuses are on, and the active campuses in order (empty while off)', - responses:[{ status:200, desc:'Success', body:{ enabled:true, campuses:[{ id:'c_1', name:'Henley Campus', slug:'henley-campus', address:'1 Church St', colour:'#1d4ed8', defaultLocation:'Main hall', order:0 }] }}]}, - { method:'GET', path:'/api/campuses/by-slug/:slug', auth:'Public', desc:'One active campus, for its /campus/ page (404 when archived or campuses are off)' }, - { method:'GET', path:'/api/campuses/admin', auth:'admin', desc:'All campuses with archived ones, event and home-campus counts, and daily-summary recipients' }, - { method:'PUT', path:'/api/campuses/settings', auth:'admin', desc:'Turn campuses on or off (off hides campus fields and filters; nothing is deleted). Audited as campuses_toggled', - request:{ body:{ enabled:true } }}, - { method:'POST', path:'/api/campuses', auth:'admin', desc:'Add a campus (slug made from the name unless given). 409 if the slug is taken', - request:{ body:{ name:'Henley Campus', address:'1 Church St', colour:'#1d4ed8', defaultLocation:'Main hall' } }}, - { method:'PUT', path:'/api/campuses/:id', auth:'admin', desc:'Change a campus, its daily-summary recipients (staff only) and archived state', - request:{ body:{ name:'Henley Campus', notifyRecipientIds:['u_1'], archived:false } }}, - { method:'PUT', path:'/api/campuses/order', auth:'admin', desc:'Put the campuses in this order', request:{ body:{ ids:['c_2','c_1'] } }}, - { method:'DELETE', path:'/api/campuses/:id', auth:'admin', desc:'Delete a campus with no events (409 CAMPUS_HAS_EVENTS otherwise — archive it)' }, - { method:'GET', path:'/api/campuses/:id/audience', auth:'supervisor+', desc:'"Everyone at campus X" for broadcasts: home campus X, plus with ?registrants=true people registered for its events in the last 12 months' }, - ]}, - - { title: 'Kids check-in', base: '/api/kids', endpoints: [ - { method:'GET', path:'/api/kids/me', auth:'user', desc:'My family (children, authorised adults, parents), the family QR token, live pickup codes and pages from the last 24 hours' }, - { method:'POST', path:'/api/kids/me', auth:'user', desc:'Start my family', request:{ body:{ name:'The Smith family' } } }, - { method:'PUT', path:'/api/kids/me', auth:'user', desc:'Rename my family' }, - { method:'DELETE', path:'/api/kids/me', auth:'user', desc:'Leave my family (the last parent leaving deletes it with its children)' }, - { method:'POST', path:'/api/kids/me/children', auth:'user', desc:'Add a child (allergies, medical and custody notes are stored encrypted)', - request:{ body:{ firstName:'Mia', lastName:'Smith', dateOfBirth:'2021-03-04', allergies:'Peanuts', medicalNotes:'', custodyNotes:'' } } }, - { method:'PUT', path:'/api/kids/me/children/:id', auth:'user', desc:'Change a child (custody note changes are audited)' }, - { method:'DELETE', path:'/api/kids/me/children/:id', auth:'user', desc:'Remove a child' }, - { method:'POST', path:'/api/kids/me/adults', auth:'user', desc:'Add an authorised adult (no account needed; up to 10)', request:{ body:{ name:'Mary Smith', phone:'0821234567', relationship:'Gran' } } }, - { method:'PUT', path:'/api/kids/me/adults/:id', auth:'user', desc:'Change an authorised adult' }, - { method:'DELETE', path:'/api/kids/me/adults/:id', auth:'user', desc:'Remove an authorised adult' }, - { method:'GET', path:'/api/kids/setup-events', auth:'supervisor+', desc:'Upcoming events to set kids check-in up for (campus-scoped)' }, - { method:'GET', path:'/api/kids/events/:eventId/settings', auth:'supervisor+', desc:'Kids check-in settings, the main tickets that can be the kids ticket and the allocation sets' }, - { method:'PUT', path:'/api/kids/events/:eventId/settings', auth:'supervisor+', desc:'Switch kids check-in on/off and choose the kids ticket and rooms ("new" makes a free "Kids check-in" ticket or a "Kids rooms" set). Audited as kids_settings_updated', - request:{ body:{ enabled:true, optionId:'new', roomSetId:'new' } } }, - { method:'GET', path:'/api/kids/events', auth:'staff+', desc:'Events with kids check-in from the last week on' }, - { method:'GET', path:'/api/kids/events/:eventId/board', auth:'staff+', desc:'Rooms (counts, leaders on duty, full/over ratio), check-ins with allergies, medical and custody notes, and alerts for today\'s occasion. ?log=1 writes the access log' }, - { method:'GET', path:'/api/kids/events/:eventId/families?q=', auth:'staff+', desc:'Find families by family, child or parent name, email or phone' }, - { method:'POST', path:'/api/kids/events/:eventId/families', auth:'staff+', desc:'New family at the desk: the parent\'s account is matched by email/phone or created inactive', - request:{ body:{ name:'The Smith family', parent:{ name:'Anna Smith', phone:'0821234567', email:'' }, children:[{ firstName:'Mia', dateOfBirth:'2021-03-04' }] } } }, - { method:'GET', path:'/api/kids/events/:eventId/families/qr/:token', auth:'staff+', desc:'The family for a scanned family QR code' }, - { method:'GET', path:'/api/kids/events/:eventId/families/:familyId', auth:'staff+', desc:'One family' }, - { method:'POST', path:'/api/kids/events/:eventId/families/:familyId/parents', auth:'staff+', desc:'Add a parent to a family' }, - { method:'POST', path:'/api/kids/events/:eventId/families/:familyId/children', auth:'staff+', desc:'Add a child (custody notes: supervisors only)' }, - { method:'PUT', path:'/api/kids/events/:eventId/families/:familyId/children/:childId', auth:'staff+', desc:'Change a child' }, - { method:'POST', path:'/api/kids/events/:eventId/families/:familyId/adults', auth:'staff+', desc:'Add an authorised adult' }, - { method:'POST', path:'/api/kids/events/:eventId/check-in', auth:'staff+', desc:'Check children in: one pickup code per family per occasion, a free place on the kids ticket the first time, a ticket usage each time. Sends the code to the parents (and optionally an authorised adult)', - request:{ body:{ familyId:'f_1', children:[{ childId:'c_1', roomId:'g_1' }], sendToAdultId:null } }, - responses:[{ status:201, desc:'Checked in', body:{ code:'K7P2', qr:'KIDS-K7P2', checkIns:[{ id:'k_1', name:'Mia Smith', room:{ id:'g_1', name:'Toddlers' }, sticker:'ALLERGY: PEANUTS' }] } }] }, - { method:'GET', path:'/api/kids/events/:eventId/code/:code', auth:'staff+', desc:'The children on a pickup code (for confirming who is collected)' }, - { method:'POST', path:'/api/kids/events/:eventId/check-out', auth:'staff+', desc:'Check out with the pickup code. 404 WRONG_CODE raises a room alert (audited as kids_wrong_code)', - request:{ body:{ code:'K7P2', collectedBy:'Anna Smith', checkInIds:['k_1'] } } }, - { method:'POST', path:'/api/kids/check-ins/:id/override', auth:'staff+', desc:'Check one child out without the code; reason and who collected required. Audited as kids_checkout_override' }, - { method:'POST', path:'/api/kids/check-ins/:id/page', auth:'staff+', desc:'Ask the parents to come to the room (WhatsApp/email; shows on their Kids page)' }, - { method:'PUT', path:'/api/kids/check-ins/:id/room', auth:'staff+', desc:'Move a child to another room' }, - { method:'POST', path:'/api/kids/events/:eventId/duty', auth:'staff+', desc:'"I\'m on duty" in a room (on:false to go off), for the ratio' }, - { method:'POST', path:'/api/kids/alerts/:id/resolve', auth:'staff+', desc:'Mark an alert as dealt with' }, - { method:'GET', path:'/api/kids/events/:eventId/offline?deviceId=', auth:'staff+', desc:'Offline list for a desk: families, rooms, who is in, and 20 pickup codes reserved for the device' }, - { method:'POST', path:'/api/kids/events/:eventId/sync', auth:'staff+', desc:'Sync an offline desk\'s check-ins and check-outs (idempotent by clientId). Audited as kids_offline_sync' }, - ]}, - - { title: 'Event series', base: '/api/series', endpoints: [ - { method:'GET', path:'/api/series', auth:'supervisor+', desc:'Every series with followers, eventCount and its events (campus-scoped staff see only their campuses\' events in each)' }, - { method:'POST', path:'/api/series', auth:'supervisor+', desc:'Create a series (slug made from the name when not given). Audited as series_created', - request:{ body:{ name:'Family Camp', slug:'family-camp', description:'Every year in March', picture:null } } }, - { method:'PUT', path:'/api/series/:id', auth:'supervisor+', desc:'Change a series. Audited as series_updated' }, - { method:'DELETE', path:'/api/series/:id', auth:'admin', desc:'Delete a series; its events stay without a series and followers are dropped. Audited as series_deleted' }, - { method:'GET', path:'/api/series/by-slug/:slug', auth:'public', desc:'The series page: details, upcoming and past public events, and following (signed in)' }, - { method:'POST', path:'/api/series/:id/follow', auth:'user', desc:'Follow a series: an email (News & announcements) when a new event in it goes live' }, - { method:'DELETE', path:'/api/series/:id/follow', auth:'user', desc:'Unfollow a series' }, - { method:'GET', path:'/api/series/:id/compare', auth:'supervisor+', desc:'Year on year: registrations, tickets, income (as on the dashboard), checked in (average per session on multi-session events) and attendance rate per event in the series, oldest first, with the % change from the one before. Campus-scoped staff: their campuses\x27 events only' }, - ]}, - - { title: 'Saved filters', base: '/api/saved-filters', endpoints: [ - { method:'GET', path:'/api/saved-filters?page=', auth:'staff+', desc:'My saved filters for a list page (registrations, users, events, reports), default first' }, - { method:'POST', path:'/api/saved-filters', auth:'staff+', desc:'Save (or replace by name) a filter: { page, name, params, isDefault? }. Up to 30 per page; making one the default clears the old default', - request:{ body:{ page:'registrations', name:'Camp — unpaid', params:{ event:'ev-uuid', status:'pending' }, isDefault:false } } }, - { method:'PUT', path:'/api/saved-filters/:id', auth:'staff+', desc:'Rename it, or make it (or stop it being) my default — my own only' }, - { method:'DELETE', path:'/api/saved-filters/:id', auth:'staff+', desc:'Delete one of my saved filters' }, - ]}, - - { title: 'Dashboard and command palette', base: '/api/dashboard', endpoints: [ - { method:'GET', path:'/api/dashboard/today', auth:'staff+', desc:'Events on today (or with a session today): places, people checked in today, children in now, volunteers rostered/checked in. Supervisors and admins also get money in (today, last 7 days) and "waiting" items: unpaid registrations for the next two weeks, parental consent, waitlist, cover requests, roster gaps, and for admins cashups due, provider payments to reconcile, privacy requests, failed webhooks. Campus-scoped' }, - { method:'GET', path:'/api/dashboard/search?q=', auth:'staff+', desc:'Command palette search: events; supervisors also payments by amount ("R450"); admins also people and registrations by reference. { results: [{ type, id, title, subtitle, href }] }' }, - ]}, - - { title: 'Outbound webhooks', base: '/api/outbound-webhooks', endpoints: [ - { method:'GET', path:'/api/outbound-webhooks', auth:'admin', desc:'Endpoints (with last-week delivery counts per status) and the event types: registration.created, registration.paid, registration.cancelled, payment.received, payment.refunded, ticket.checked_in, user.created, event.published' }, - { method:'POST', path:'/api/outbound-webhooks', auth:'admin', desc:'Add an endpoint (https, public address). The answer holds the signing secret — shown only now. Also added to the POPIA operator register. Audited as webhook_endpoint_changed', - request:{ body:{ name:'ChurchSuite sync', url:'https://example.com/hooks/cross-events', events:['registration.paid','ticket.checked_in'] } } }, - { method:'PUT', path:'/api/outbound-webhooks/:id', auth:'admin', desc:'Change name, url, events or isActive' }, - { method:'DELETE', path:'/api/outbound-webhooks/:id', auth:'admin', desc:'Delete an endpoint and its deliveries (its operator entry is marked inactive)' }, - { method:'POST', path:'/api/outbound-webhooks/:id/rotate-secret', auth:'admin', desc:'A new signing secret (the old one stops at once)' }, - { method:'POST', path:'/api/outbound-webhooks/:id/test', auth:'admin', desc:'Send a webhook.test now; answers { status, statusCode, error }' }, - { method:'GET', path:'/api/outbound-webhooks/:id/deliveries?status=&limit=', auth:'admin', desc:'Delivery log, newest first, with payloads (kept 30 days)' }, - { method:'POST', path:'/api/outbound-webhooks/deliveries/:id/resend', auth:'admin', desc:'Send a delivery again now' }, - ]}, - - { title: 'Season passes', base: '/api/season-passes', endpoints: [ - { method:'GET', path:'/api/season-passes?seriesId=', auth:'supervisor+', desc:'A series\x27 passes: events, normal prices, each event\x27s share, sold and unpaid counts' }, - { method:'POST', path:'/api/season-passes', auth:'supervisor+', desc:'Create a pass. Events must be in the series; not youth (consent) events, staff-only or per-session tickets. Campus-scoped supervisors: only their campuses\x27 events. Audited as season_pass_changed', - request:{ body:{ seriesId:'series-uuid', name:'2027 breakfasts', price:400, saleEndsAt:null, items:[{ eventId:'ev-uuid', eventOptionId:'opt-uuid', variantId:null }] } } }, - { method:'PUT', path:'/api/season-passes/:id', auth:'supervisor+', desc:'Change a pass (events and price only while nobody has bought it; 409 otherwise)' }, - { method:'DELETE', path:'/api/season-passes/:id', auth:'supervisor+', desc:'Delete a pass nobody has bought' }, - { method:'POST', path:'/api/season-passes/:id/buy', auth:'user', desc:'Buy passes: a registration at every event (lines priced at each event\x27s share), then one checkout for the total (redirectUrl), or tickets straight away when free. 409 when not on sale or an event has too few places', - request:{ body:{ quantity:2 } }, responses:[{ status:201, desc:'Bought', body:{ purchaseId:'uuid', total:800, paid:false, redirectUrl:'https://…', provider:'yoco', message:null } }] }, - { method:'POST', path:'/api/season-passes/purchases/:id/checkout', auth:'user', desc:'Pay what is still owed on my purchase (a new checkout)' }, - { method:'GET', path:'/api/season-passes/mine', auth:'user', desc:'My pass purchases with their registrations' }, - ]}, - - { title: 'Volunteer rosters', base: '/api/volunteers', endpoints: [ - { method:'GET', path:'/api/volunteers/me', auth:'user', desc:'My shifts (upcoming and the last week), cover requests I could take, and events looking for volunteers' }, - { method:'GET', path:'/api/volunteers/events/:eventId', auth:'user', desc:'An event\'s serving roles: shift, how many are needed and signed up, whether I\'m in it, open cover requests' }, - { method:'POST', path:'/api/volunteers/roles/:id/sign-up', auth:'user', desc:'Sign up for a role. 409 ROLE_FULL when it\'s full, 409 SHIFT_CLASH when I serve elsewhere at the same time. Gives a free volunteer place when the event has one', - responses:[{ status:201, desc:'Signed up', body:{ slotId:'s_1', ticket:true } }] }, - { method:'DELETE', path:'/api/volunteers/slots/:id', auth:'user', desc:'Withdraw from a shift (not after checking in or once it\'s over). The event\'s notify recipients are emailed' }, - { method:'POST', path:'/api/volunteers/slots/:id/swap', auth:'user', desc:'"Can\'t make it": ask for cover. The event\'s other volunteers are told; the request shows on everyone\'s Serving page', request:{ body:{ note:'Away that weekend' } } }, - { method:'DELETE', path:'/api/volunteers/swaps/:id', auth:'user', desc:'Cancel my cover request' }, - { method:'POST', path:'/api/volunteers/swaps/:id/accept', auth:'user', desc:'Take over someone\'s place. Happens at once (409 SWAP_CLOSED if someone was first); both volunteers and the event\'s notify recipients are told' }, - { method:'POST', path:'/api/volunteers/check-in', auth:'user', desc:'Check in by scanning the event\'s volunteer QR code: every shift of mine on today is checked in; kids-room roles put me on duty in that room', - request:{ body:{ qr:'SERVE-3f2a…' } }, responses:[{ status:200, desc:'Checked in', body:{ event:{ id:'e_1', title:'Sunday service' }, checkedIn:[{ role:'Kids', kidsRoom:'Toddlers' }], already:[] } }] }, - { method:'GET', path:'/api/volunteers/manage/events', auth:'staff+', desc:'Events with serving roles from the last 30 days on (?all=1, supervisors: every upcoming event). Campus-scoped' }, - { method:'GET', path:'/api/volunteers/manage/events/:eventId', auth:'staff+', desc:'The roster sheet: roles with volunteers, contact details, check-ins and fill rate. ?log=1 writes the access log' }, - { method:'GET', path:'/api/volunteers/manage/events/:eventId/qr', auth:'staff+', desc:'The volunteer check-in QR code value for the event (made the first time)' }, - { method:'POST', path:'/api/volunteers/manage/slots/:id/check-in', auth:'staff+', desc:'Check a volunteer in by hand (undo:true to undo). Audited as volunteer_checked_in_manual' }, - { method:'GET', path:'/api/volunteers/manage/events/:eventId/settings', auth:'supervisor+', desc:'The volunteer ticket setting, the main tickets that can be it and the event\'s kids rooms' }, - { method:'PUT', path:'/api/volunteers/manage/events/:eventId/settings', auth:'supervisor+', desc:'Free volunteer place: optionId of a main ticket, "new" for a free "Volunteer" ticket, null for off (the default). Audited as volunteer_settings_updated', request:{ body:{ optionId:'new' } } }, - { method:'POST', path:'/api/volunteers/manage/events/:eventId/roles', auth:'supervisor+', desc:'Add a serving role (sessionId required on multi-session events; shift times optional). Audited as volunteer_roles_changed', - request:{ body:{ name:'Welcome', needed:4, sessionId:null, startsAt:'2026-11-08T07:30:00.000Z', endsAt:'2026-11-08T09:30:00.000Z', description:'Front doors', kidsRoomId:null } } }, - { method:'PUT', path:'/api/volunteers/manage/roles/:id', auth:'supervisor+', desc:'Change a role' }, - { method:'DELETE', path:'/api/volunteers/manage/roles/:id', auth:'supervisor+', desc:'Delete a role (refused once someone checked in for it); its volunteers are told' }, - { method:'POST', path:'/api/volunteers/manage/roles/:id/assign', auth:'supervisor+', desc:'Put someone on a role (allowed beyond the number needed); they\'re told. Audited as volunteer_assigned', request:{ body:{ userId:'u_1' } } }, - { method:'DELETE', path:'/api/volunteers/manage/slots/:id', auth:'supervisor+', desc:'Take someone off a role (not after check-in); they\'re told. Audited as volunteer_removed' }, - { method:'GET', path:'/api/volunteers/manage/hours?eventId=&from=&to=', auth:'supervisor+', desc:'Hours served per person (checked-in shifts × shift length), most first. Campus-scoped' }, - ]}, - - { title: 'Privacy (POPIA)', base: '/api/privacy', endpoints: [ - { method:'GET', path:'/api/privacy/me', auth:'user', desc:'My news opt-in, its history, and my privacy requests', - responses:[{ status:200, desc:'Success', body:{ news:{ email:true, whatsapp:false }, newsAskedAt:'2026-10-23T08:00:00.000Z', canWhatsApp:false, notificationPreference:'email', history:[{ channel:'email', granted:true, source:'signup', createdAt:'2026-10-23T08:00:00.000Z' }], requests:[] }}]}, - { method:'PUT', path:'/api/privacy/me/news', auth:'user', desc:'Change the News & announcements opt-in per channel (source "prompt" for the one-time question after login)', - request:{ body:{ email:false, whatsapp:false } }, - responses:[{ status:200, desc:'Saved', body:{ news:{ email:false, whatsapp:false }, newsAskedAt:'2026-10-23T08:00:00.000Z' }}]}, - { method:'GET', path:'/api/privacy/me/export', auth:'user', desc:'Download my data — JSON, or ?format=pdf for a readable PDF. Blocked while impersonating', - responses:[{ status:200, desc:'File download' }]}, - { method:'POST', path:'/api/privacy/me/requests', auth:'user', desc:'Correction request ({ type:"correction", details }) or delete my account ({ type:"deletion", password }) — deletion closes the account at once', - request:{ body:{ type:'correction', details:'My son\'s date of birth on the Camp registration is wrong — it should be 3 May 2012.' } }, - responses:[{ status:201, desc:'Created', body:{ request:{ id:'req-uuid-...', type:'correction', status:'open', dueAt:'2026-11-22T08:00:00.000Z' }, message:'Your request was sent.' }}, { status:409, desc:'Already open', body:{ message:'You already have an open correction request.' }}]}, - { method:'GET', path:'/api/privacy/unsubscribe/:token', auth:'public', desc:'What an unsubscribe link (signed token) is for', - responses:[{ status:200, desc:'Success', body:{ kind:'account', email:'jo***@example.com', hasPhone:true, news:{ email:true, whatsapp:true } }}]}, - { method:'POST', path:'/api/privacy/unsubscribe/:token', auth:'public', desc:'Unsubscribe from news ({ channels?: ["email","whatsapp"] }, default both)', - responses:[{ status:200, desc:'Done', body:{ message:'You have been unsubscribed.' }}]}, - { method:'POST', path:'/api/privacy/unsubscribe/:token/one-click', auth:'public', desc:'RFC 8058 one-click unsubscribe from the List-Unsubscribe email header (email news off)', - responses:[{ status:200, desc:'Done' }]}, - { method:'GET', path:'/api/privacy/requests', auth:'admin', desc:'Data requests inbox (?status=open|closed|all), with due dates and, for deletions, the registrations still blocking it', - responses:[{ status:200, desc:'Success', body:{ requests:[{ id:'req-uuid-...', type:'deletion', status:'open', name:'Jane Doe', email:'jane@example.com', dueAt:'2026-11-22T08:00:00.000Z', overdue:false, blockers:[] }], openCount:1 }}]}, - { method:'POST', path:'/api/privacy/requests/:id/complete', auth:'admin', desc:'Complete a request (emailed to the person). Deletion anonymises the account; 409 while it has a registration for an upcoming event', - request:{ body:{ response:'Corrected the date of birth on the Camp 2026 registration.' } }, - responses:[{ status:200, desc:'Completed', body:{ request:{ status:'completed' }, anonymised:null }}]}, - { method:'POST', path:'/api/privacy/requests/:id/reject', auth:'admin', desc:'Reject a request, or mark it withdrawn (cancelled:true); a deletion request reopens the account', - request:{ body:{ response:'We could not find a registration with that name.', cancelled:false } }, - responses:[{ status:200, desc:'Closed', body:{ request:{ status:'rejected' } }}]}, - { method:'GET', path:'/api/privacy/notice', auth:'public', desc:'The privacy notice (current, or ?version=N) with org details and the operator list filled in. Version 0 = built-in, until one is published', - responses:[{ status:200, desc:'Success', body:{ version:2, builtIn:false, current:true, effectiveDate:'23 October 2026', changeSummary:'We added WhatsApp news.', sections:[{ id:'introduction', title:'1. Introduction', body:'Hope Church values your privacy…' }], versions:[{ version:2, publishedAt:'2026-10-23T10:00:00.000Z', requiresAcceptance:true }] }}]}, - { method:'POST', path:'/api/privacy/me/notice/accept', auth:'user', desc:'Accept the current privacy notice version', - responses:[{ status:200, desc:'Accepted', body:{ version:2 }}]}, - { method:'GET', path:'/api/privacy/notice/draft', auth:'admin', desc:'Notice editor: draft (or current) sections, rendered preview, published versions with acceptance counts, built-in text', - responses:[{ status:200, desc:'Success', body:{ sections:[], rendered:[], isDraft:false, savedAt:null, versions:[{ version:1, acceptances:12 }] }}]}, - { method:'PUT', path:'/api/privacy/notice/draft', auth:'admin', desc:'Save the draft ({ sections: [{ id?, title, body }] })', - request:{ body:{ sections:[{ title:'1. Introduction', body:'{org} values your privacy.' }] } }, - responses:[{ status:200, desc:'Saved', body:{ isDraft:true }}]}, - { method:'DELETE', path:'/api/privacy/notice/draft', auth:'admin', desc:'Discard the draft', - responses:[{ status:200, desc:'Discarded', body:{ message:'Draft discarded.' }}]}, - { method:'POST', path:'/api/privacy/notice/publish', auth:'admin', desc:'Publish the next version; requiresAcceptance asks everyone to accept it after their next login (needs changeSummary)', - request:{ body:{ sections:[{ title:'1. Introduction', body:'{org} values your privacy.' }], changeSummary:'We added WhatsApp news.', requiresAcceptance:true } }, - responses:[{ status:201, desc:'Published', body:{ version:2, requiresAcceptance:true }}]}, - { method:'GET', path:'/api/privacy/operators', auth:'admin', desc:'The operator register (third parties that process personal information)', - responses:[{ status:200, desc:'Success', body:[{ id:'op-uuid-...', name:'PayFast', purpose:'Online payments', dataShared:'Name, email address, payment amount and reference', location:'South Africa', website:'https://payfast.io', active:true }] }]}, - { method:'POST', path:'/api/privacy/operators', auth:'admin', desc:'Add an operator (PUT/DELETE /api/privacy/operators/:id to change or remove)', - request:{ body:{ name:'Mailgun', purpose:'Sending emails', dataShared:'Name, email address, message content', location:'EU' } }, - responses:[{ status:201, desc:'Created' }]}, - { method:'GET', path:'/api/privacy/consent-log', auth:'admin', desc:'Consent records: ?type=news|notice|parental, ?q= name/email, ?page=', - responses:[{ status:200, desc:'Success', body:{ total:1, pageSize:50, rows:[{ at:'2026-10-23T08:00:00.000Z', name:'Jane Doe', email:'jane@example.com', channel:'email', granted:false, source:'unsubscribe_link' }] }}]}, - { method:'GET', path:'/api/privacy/readiness', auth:'admin', desc:'POPIA readiness checklist with a score; each open item has a link to fix it', - responses:[{ status:200, desc:'Success', body:{ score:77, passed:10, total:13, checks:[{ key:'notice', label:'Privacy notice published', ok:true, detail:'2 versions published', href:'/dashboard/admin/privacy?tab=notice', applies:true }] }}]}, - { method:'GET', path:'/api/privacy/retention', auth:'admin', desc:'Retention policies, what the next run would affect, and the last run', - responses:[{ status:200, desc:'Success', body:{ policies:{ inactive_accounts:{ enabled:true, months:60 } }, preview:{ inactive_accounts:{ toWarn:3, toAnonymise:0 } }, reviewedAt:null }}]}, - { method:'PUT', path:'/api/privacy/retention', auth:'admin', desc:'Save the retention policies (all five)', - request:{ body:{ policies:{ inactive_accounts:{ enabled:true, months:60 }, form_answers:{ enabled:true, months:12 }, login_history:{ enabled:true, months:24 }, payment_details:{ enabled:true, months:24 }, audit_logs:{ enabled:true, months:60 } } } }, - responses:[{ status:200, desc:'Saved' }]}, - { method:'POST', path:'/api/privacy/retention/run', auth:'admin', desc:'Run the retention job now (warn/anonymise inactive accounts, delete expired data)', - responses:[{ status:200, desc:'Done', body:{ result:{ inactive_accounts:{ warned:3, anonymised:0, waiting:0 }, login_history:{ deleted:120 } } }}]}, - { method:'GET', path:'/api/privacy/breaches', auth:'admin', desc:'The breach register (security compromises); POST to record one, PUT /:id to update or mark the Regulator/people told', - responses:[{ status:200, desc:'Success', body:[{ id:'br-uuid-...', title:'Phone with the attendee list lost', status:'open', discoveredAt:'2026-10-23T08:00:00.000Z', regulatorNotifiedAt:null }] }]}, - { method:'GET', path:'/api/privacy/access-log', auth:'admin', desc:'Bulk exports/views of personal information: ?action=, ?actorId=, ?sensitive=true, ?from=, ?to=, ?page=', - responses:[{ status:200, desc:'Success', body:{ total:1, pageSize:50, rows:[{ at:'2026-10-23T08:00:00.000Z', actor:'Sam Supervisor', action:'report_pdf', what:'Camp 2026 attendees', records:48 }] }}]}, - ]}, - - { title: 'Broadcasts (Email)', base: '/api/broadcasts', endpoints: [ - { method:'POST', path:'/api/broadcasts/preview', auth:'supervisor+', desc:'Dry-run a broadcast — returns resolved recipient list without sending', - request:{ body:{ userIds:['user-uuid-1','user-uuid-2'], emails:'extra@example.com\nJohn ', eventId:'ev-uuid-...' }}, - responses:[{ status:200, desc:'Preview', body:{ matched:3, recipients:[{ email:'jane@example.com', name:'Jane Doe' },{ email:'extra@example.com', name:null }] }}]}, - { method:'POST', path:'/api/broadcasts/send', auth:'supervisor+', desc:'Send an email broadcast to users and/or ad-hoc addresses', - request:{ body:{ subject:'Important update', text:'Hi {{name}}, here is a message for you.', userIds:['user-uuid-1'], emails:'extra@example.com', eventId:'ev-uuid-...' }}, - responses:[{ status:200, desc:'Sent', body:{ matched:2, sent:2 }}]}, - { method:'POST', path:'/api/broadcasts/schedule', auth:'supervisor+', desc:'Schedule an email broadcast for a future time', - request:{ body:{ subject:'Save the date!', text:'Hi {{name}}, mark your calendar for {{event.title}}.', userIds:['user-uuid-1'], scheduledAt:'2025-06-01T09:00:00.000Z', eventId:'ev-uuid-...' }}, - responses:[{ status:201, desc:'Scheduled', body:{ job:{ id:'job-uuid-...', status:'queued', scheduledAt:'2025-06-01T09:00:00.000Z' }}}]}, - ]}, - - { title: 'Broadcasts (WhatsApp)', base: '/api/whatsapp-broadcasts', endpoints: [ - { method:'POST', path:'/api/whatsapp-broadcasts/preview', auth:'supervisor+', desc:'Dry-run — resolve phone list without sending', - request:{ body:{ userIds:['user-uuid-1'], phones:'0821234567\nJane <0721234567>', eventId:'ev-uuid-...' }}, - responses:[{ status:200, desc:'Preview', body:{ matched:2, recipients:[{ phone:'+27821234567', name:'Jane Doe' }] }}]}, - { method:'POST', path:'/api/whatsapp-broadcasts/send', auth:'supervisor+', desc:'Send a WhatsApp broadcast', - request:{ body:{ message:'Hi {{name}}, please check your tickets for {{event.title}}.', userIds:['user-uuid-1'], phones:'0821234567', eventId:'ev-uuid-...' }}, - responses:[{ status:200, desc:'Sent', body:{ matched:2, sent:2 }}]}, - { method:'POST', path:'/api/whatsapp-broadcasts/schedule', auth:'supervisor+', desc:'Schedule a WhatsApp broadcast', - request:{ body:{ message:'Hi {{name}}! {{event.title}} is tomorrow. See you there 🙌', userIds:['user-uuid-1'], scheduledAt:'2025-07-09T08:00:00.000Z' }}, - responses:[{ status:201, desc:'Scheduled', body:{ job:{ id:'job-uuid-...', status:'queued' }}}]}, - ]}, - - { title: 'Scheduled Messages', base: '/api/scheduled-emails', endpoints: [ - { method:'GET', path:'/api/scheduled-emails', auth:'supervisor+', desc:'List all scheduled jobs — email and WhatsApp. Jobs sent more than 7 days ago are hidden.', - responses:[{ status:200, desc:'Success', body:{ jobs:[{ id:'job-uuid-...', channel:'email', broadcast:false, eventId:'ev-uuid-...', status:'queued', scheduledAt:'2025-07-03T09:00:00.000Z', attempts:0, payload:{ subject:'Camp reminder' }}]}}]}, - { method:'PATCH', path:'/api/scheduled-emails/:id', auth:'supervisor+', desc:'Edit a queued job — reschedule or update its message content', - pathParams:{ ':id':'Scheduled job UUID' }, - request:{ body:{ scheduledAt:'2025-07-04T09:00:00.000Z', subject:'Updated subject', text:'Hi {{name}}, updated message.' }}, - responses:[ - { status:200, desc:'Updated', body:{ id:'job-uuid-...', scheduledAt:'2025-07-04T09:00:00.000Z', status:'queued' }}, - { status:400, desc:'Already sent', body:{ message:'Cannot edit a job that has already been sent.' }}, - ]}, - { method:'DELETE', path:'/api/scheduled-emails/:id', auth:'supervisor+', desc:'Cancel and remove a queued job', - pathParams:{ ':id':'Scheduled job UUID' }, - responses:[{ status:200, desc:'Deleted', body:{ message:'Scheduled job removed.' }}]}, - ]}, - - { title: 'Automations', base: '/api/automations', endpoints: [ - { method:'POST', path:'/api/automations/schedule', auth:'supervisor+', desc:'Schedule multiple lifecycle email automations for an event in one call (pre-event, final reminder, thank-you, promo).', - request:{ body:{ eventId:'ev-uuid-...', jobs:[ - { subject:'1 Week to Go: Camp 2025!', text:'Hi {{name}}, camp is one week away!\n\nDetails: {{event.link}}', scheduledAt:'2025-07-03T09:00:00.000Z' }, - { subject:"We'll See You Tomorrow!", text:'Hi {{name}}, final reminder for {{event.title}}. Please have your QR code ready.', scheduledAt:'2025-07-09T09:00:00.000Z' }, - ]}}, - responses:[{ status:201, desc:'Scheduled', body:{ message:'2 automation(s) scheduled.', jobs:[{ id:'job-uuid-1', status:'queued' },{ id:'job-uuid-2', status:'queued' }] }}]}, - ]}, - - { title: 'Reports', base: '/api/reports', endpoints: [ - { method:'POST', path:'/api/reports/excel', auth:'Bearer', desc:'Build an Excel file from a report payload' }, - { method:'POST', path:'/api/reports/whatsapp', auth:'Bearer', desc:'Send a report PDF by WhatsApp' }, - { method:'POST', path:'/api/reports/pdf', auth:'user+', desc:'Generate a PDF report of own registrations and tickets and return it as a binary download', - responses:[{ status:200, desc:'PDF file (application/pdf)', body:'' }]}, - { method:'POST', path:'/api/reports/email', auth:'user+', desc:'Generate PDF report and email it to the authenticated user', - responses:[{ status:200, desc:'Sent', body:{ message:'Report emailed.' }}]}, - ]}, - - { title: 'Costs', base: '/api/events/:eventId/costs', endpoints: [ - { method:'GET', path:'/api/events/:eventId/costs', auth:'supervisor+', desc:'List costs (once-off or per-item) for an event', - pathParams:{ ':eventId':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:[{ id:'cost-uuid-...', label:'Venue hire', costType:'once_off', amount:2500 },{ id:'cost-uuid-2', label:'Catering', costType:'per_item', amount:75, eventOptionId:'opt-uuid-...' }]}]}, - { method:'POST', path:'/api/events/:eventId/costs', auth:'admin', desc:'Create a cost for an event. eventOptionId is required when costType is per_item. paidFromMethod (cash/card/eft/other) optionally tags which float it was paid out of. Rejected once the event is closed.', - pathParams:{ ':eventId':'Event UUID' }, - request:{ body:{ label:'Catering', costType:'per_item', amount:75, eventOptionId:'opt-uuid-...', paidFromMethod:'cash' }}, - responses:[{ status:201, desc:'Created', body:{ id:'cost-uuid-new', label:'Catering', costType:'per_item', amount:75, paidFromMethod:'cash' }}]}, - { method:'PUT', path:'/api/costs/:id', auth:'admin', desc:'Update a cost. Rejected once the event is closed.', - pathParams:{ ':id':'EventCost UUID' }, - request:{ body:{ amount:80 }}, - responses:[{ status:200, desc:'Updated', body:{ id:'cost-uuid-...', amount:80 }}]}, - { method:'DELETE', path:'/api/costs/:id', auth:'admin', desc:'Delete a cost. Rejected once the event is closed.', - pathParams:{ ':id':'EventCost UUID' }, - responses:[{ status:200, desc:'Deleted', body:{ message:'Cost deleted' }}]}, - ]}, - - { title: 'Cashups', base: '/api/cashups', endpoints: [ - { method:'GET', path:'/api/cashups/event/:eventId/cash-by-user', auth:'supervisor+', desc:'Payments recorded for an event, by staff member and method' }, - { method:'PUT', path:'/api/cashups/event/:eventId/person-cash/:userId', auth:'supervisor+', desc:'Enter one staff member\'s physical cash count for an event' }, - { method:'GET', path:'/api/cashups/event/:eventId', auth:'supervisor+', desc:'Live cashup preview for an event: system income vs. reconciled actual per method, method-tagged costs, unallocated donations, net profit, and the full close/reopen history', - pathParams:{ ':eventId':'Event UUID' }, - responses:[{ status:200, desc:'Success', body:{ event:{ id:'ev-uuid-...', title:'Camp 2025', cashupStatus:'open' }, paymentsByMethod:{ cash:1200, card:4500, eft:600, other:0 }, expectedCashByMethod:{ cash:1150, card:4500, eft:600, other:0 }, unallocatedDonationsTotal:150, totalCosts:900, netProfit:6450, history:[] }}]}, - { method:'PUT', path:'/api/cashups/event/:eventId/draft', auth:'admin', desc:'Save in-progress reconciliation entries (actual counted amounts, and cash denomination counts, per method) without closing the event', - pathParams:{ ':eventId':'Event UUID' }, - request:{ body:{ lines:[{ method:'cash', denominations:[{ value:100, count:5 },{ value:50, count:2 }] },{ method:'card', actualAmount:4500 }] }}, - responses:[{ status:200, desc:'Saved', body:{ message:'Draft saved' }}]}, - { method:'POST', path:'/api/cashups/event/:eventId/close', auth:'admin', desc:'Close the event. Pass "lines" for a full per-method cashup (variances computed against expected cash, i.e. income minus any method-tagged costs) — for the cash line, pass "denominations" and the actual amount is computed from the note/coin counts server-side. Omit "lines" for a quick close that accepts system numbers as-is. Either way, unallocated donations are counted as profit and the event is fully locked (no new registrations, payments, refunds, checkouts, or donations) until an admin reopens it. Creates a permanent EventCashup audit row.', - pathParams:{ ':eventId':'Event UUID' }, - request:{ body:{ lines:[{ method:'cash', denominations:[{ value:100, count:5 },{ value:50, count:2 }], notes:'R20 short' }], notes:'Closed after evening service' }}, - responses:[{ status:201, desc:'Closed', body:{ id:'cashup-uuid-...', action:'closed', unallocatedDonationsTotal:150, totalCosts:900, totalExpectedRevenue:6300, totalActualRevenue:6280 }}]}, - { method:'POST', path:'/api/cashups/event/:eventId/reopen', auth:'admin', desc:'Reopen a closed event, unlocking registrations/payments/donations again. Admin-only. Creates a permanent "reopened" EventCashup audit row.', - pathParams:{ ':eventId':'Event UUID' }, - request:{ body:{ notes:'Reopening to correct a miscounted cash drawer' }}, - responses:[{ status:201, desc:'Reopened', body:{ id:'cashup-uuid-...', action:'reopened' }}]}, - { method:'GET', path:'/api/cashups/audit', auth:'supervisor+', desc:'Flat audit log of every close/quick-close/reopen across events, optionally filtered by eventId and/or from/to dates', - request:{ query:{ eventId:'ev-uuid-... (optional)', from:'2026-01-01 (optional)', to:'2026-12-31 (optional)' }}, - responses:[{ status:200, desc:'Success', body:[{ id:'cashup-uuid-...', action:'closed', event:{ id:'ev-uuid-...', title:'Camp 2025' }, performedBy:{ name:'Jane Supervisor' }, createdAt:'2026-07-20T18:00:00.000Z' }]}]}, - ]}, - - { title: 'Uploads', base: '/api/uploads', endpoints: [ - { method:'POST', path:'/api/uploads/logo', auth:'admin (open during first-run setup)', desc:'Upload the site logo (multipart, field "image")' }, - { method:'POST', path:'/api/uploads/favicon', auth:'admin (open during first-run setup)', desc:'Upload the site favicon (multipart, field "image")' }, - { method:'POST', path:'/api/uploads/event-image', auth:'supervisor+', desc:'Upload an event cover image. Send as multipart/form-data with field name "image". Returns the public URL.', - notes:'Content-Type must be multipart/form-data. Max size is typically 5 MB.', - responses:[ - { status:200, desc:'Uploaded', body:{ url:'/uploads/event-images/camp-2025-abc123.jpg' }}, - { status:400, desc:'No file', body:{ message:'No image file provided.' }}, - ]}, - ]}, - - { title: 'Sections', base: '/api/sections', endpoints: [ - { method:'GET', path:'/api/sections', auth:'staff+', desc:'List all sections with their allowed options', - responses:[{ status:200, desc:'Success', body:[{ id:'sec-uuid-...', eventId:'ev-uuid-...', name:'Adults', allowedOptions:[{ eventOptionId:'opt-uuid-...', eventOption:{ name:'Adult', price:450 }}] }]}]}, - { method:'POST', path:'/api/sections', auth:'supervisor+', desc:'Create a section for an event', - request:{ body:{ eventId:'ev-uuid-...', name:'Adults', optionIds:['opt-uuid-1','opt-uuid-2'] }}, - responses:[{ status:201, desc:'Created', body:{ id:'sec-uuid-new', name:'Adults', eventId:'ev-uuid-...' }}]}, - { method:'PUT', path:'/api/sections/:id', auth:'supervisor+', desc:'Update a section', - pathParams:{ ':id':'Section UUID' }, - request:{ body:{ name:'Adults & Teens', optionIds:['opt-uuid-1','opt-uuid-2','opt-uuid-3'] }}, - responses:[{ status:200, desc:'Updated', body:{ id:'sec-uuid-...', name:'Adults & Teens' }}]}, - { method:'DELETE', path:'/api/sections/:id', auth:'admin', desc:'Delete a section', - pathParams:{ ':id':'Section UUID' }, - responses:[{ status:200, desc:'Deleted', body:{ message:'Section deleted.' }}]}, - ]}, - - { title: 'Banner', base: '/api/banner', endpoints: [ - { method:'GET', path:'/api/banner', auth:'public', desc:'Get the current site-wide announcement banner', - responses:[ - { status:200, desc:'Banner set', body:{ message:'Registration for Camp 2025 is now open!', type:'info', active:true }}, - { status:200, desc:'No banner', body:{ message:null, active:false }}, - ]}, - { method:'POST', path:'/api/banner', auth:'supervisor+', desc:'Set or update the site banner', - request:{ body:{ message:'Registration is now closed.', type:'warning', active:true }}, - responses:[{ status:200, desc:'Saved', body:{ message:'Registration is now closed.', type:'warning', active:true }}]}, - ]}, - - { title: 'Forms', base: '/api/forms', endpoints: [ - { method:'GET', path:'/api/forms/responses', auth:'staff+', desc:'List all submitted form responses across all events', - queryParams:{ eventId:'Filter by event UUID', page:'Page (default 1)', limit:'Per page (default 20)' }, - responses:[{ status:200, desc:'Success', body:{ data:[{ id:'resp-uuid-...', registrationId:'reg-uuid-...', createdAt:'2025-06-01T10:05:00.000Z', answers:[{ field:{ label:'Dietary requirements' }, value:'Vegetarian' }] }], total:1 }}]}, - ]}, - - { title: 'Provider Transactions', base: '/api/provider-transactions', endpoints: [ - { method:'GET', path:'/api/provider-transactions', auth:'supervisor+', desc:'Transactions payment providers sent by webhook (also at /api/yoco-transactions)', - queryParams:{ provider:'yoco', reconciled:'true|false', ignored:'true|false' }, - responses:[{ status:200, desc:'Success', body:{ success:true, data:[{ id:'ptx-uuid-...', provider:'yoco', providerLabel:'Yoco', externalId:'pi_yoco_abc', amount:45000, currency:'ZAR', reconciled:true, paymentId:'pay-uuid-...', createdDate:'2025-06-01T11:00:00.000Z' }] }}]}, - { method:'GET', path:'/api/provider-transactions/unreconciled', auth:'supervisor+', desc:'Transactions not yet matched to a payment record', - queryParams:{ provider:'yoco' }, - responses:[{ status:200, desc:'Success', body:{ success:true, data:[{ id:'ptx-uuid-...', provider:'yoco', providerLabel:'Yoco', externalId:'pi_yoco_xyz', amount:45000, currency:'ZAR', reconciled:false }] }}]}, - { method:'POST', path:'/api/provider-transactions/:id/reconcile', auth:'supervisor+', desc:'Record the transaction as a payment on a registration, or as a donation to an event', - pathParams:{ ':id':'ProviderTransaction UUID' }, - request:{ body:{ registrationId:'reg-uuid-...', eventId:'(donation) event-uuid-...', userId:'(donation, optional) user-uuid-...' }}, - responses:[{ status:200, desc:'Reconciled', body:{ success:true, data:{ transaction:{ id:'ptx-uuid-...', reconciled:true, paymentId:'pay-uuid-...' }, payment:{ id:'pay-uuid-...', provider:'yoco' } } }}]}, - { method:'POST', path:'/api/provider-transactions/:id/ignore', auth:'supervisor+', desc:'Mark a transaction as intentionally ignored', - pathParams:{ ':id':'ProviderTransaction UUID' }, - responses:[{ status:200, desc:'Ignored', body:{ success:true, data:{ id:'ptx-uuid-...', ignored:true } }}]}, - ]}, - - { title: 'WhatsApp Admin', base: '/api/whatsapp', endpoints: [ - { method:'POST', path:'/api/whatsapp/start', auth:'admin', desc:'Start (or restart) the WAWP WhatsApp instance' }, - { method:'POST', path:'/api/whatsapp/request-code', auth:'admin', desc:'Request a pairing code to link a WhatsApp number' }, - { method:'POST', path:'/api/whatsapp/delete-instance', auth:'admin', desc:'Delete the WAWP instance' }, - { method:'POST', path:'/api/whatsapp/webhook', auth:'—', desc:'WAWP event webhook (alias of /api/webhooks/whatsapp)' }, - { method:'GET', path:'/api/whatsapp/config', auth:'admin', desc:'Get the currently stored WAWP credentials from DB (tokens are partially masked)', - responses:[{ status:200, desc:'Success', body:{ instanceId:'wawp-instance-abc', accessToken:'eyJ...****', source:'db' }}]}, - { method:'POST', path:'/api/whatsapp/config', auth:'admin', desc:'Save WAWP credentials to the database (AppSetting). Takes effect immediately; no restart needed.', - request:{ body:{ accessToken:'eyJhbGciOiJSUzI1...', instanceId:'wawp-instance-abc' }}, - responses:[{ status:200, desc:'Saved', body:{ message:'WhatsApp config saved.' }}]}, - { method:'GET', path:'/api/whatsapp/status', auth:'admin', desc:'Get the current WAWP session status', - responses:[ - { status:200, desc:'Connected', body:{ status:'open', phoneNumber:'+27821234567', pushName:'Cross Code' }}, - { status:200, desc:'Not connected', body:{ status:'close' }}, - ]}, - { method:'GET', path:'/api/whatsapp/qr', auth:'admin', desc:'Get a QR code image/string to link a WhatsApp account', - responses:[{ status:200, desc:'Success', body:{ qr:'data:image/png;base64,...', qrString:'2@abc123...' }}]}, - { method:'POST', path:'/api/whatsapp/create-instance', auth:'admin', desc:'Create a new WAWP session instance', - responses:[{ status:200, desc:'Created', body:{ instanceId:'wawp-instance-new', message:'Instance created.' }}]}, - { method:'POST', path:'/api/whatsapp/restart', auth:'admin', desc:'Restart the current WAWP instance', - responses:[{ status:200, desc:'Restarted', body:{ message:'Instance restarted.' }}]}, - { method:'POST', path:'/api/whatsapp/logout', auth:'admin', desc:'Log out the current WhatsApp session', - responses:[{ status:200, desc:'Logged out', body:{ message:'Logged out.' }}]}, - ]}, - - { title: 'Dashboard stats', base: '/api/stats', endpoints: [ - { method:'GET', path:'/api/stats/staff', auth:'staff+', desc:'Everything the staff dashboard needs, in one call' }, - { method:'GET', path:'/api/stats/supervisor', auth:'supervisor+', desc:'Everything the supervisor dashboard needs, in one call' }, - { method:'GET', path:'/api/stats/admin', auth:'admin', desc:'Everything the admin dashboard needs, in one call' }, - { method:'GET', path:'/api/stats/overview', auth:'supervisor+', desc:'Trailing-month KPIs (registrations, tickets, revenue, donations), revenue trend, top events, funnel conversion. ?campus= for one campus or church-wide events only' }, - ]}, - { title: 'Backups', base: '/api/backups', endpoints: [ - { method:'GET', path:'/api/backups', auth:'admin', desc:'Local database backups, newest first' }, - { method:'POST', path:'/api/backups/run', auth:'admin', desc:'Run a backup now' }, - { method:'GET', path:'/api/backups/:filename/download', auth:'admin', desc:'Download a backup file' }, - ]}, - { title: 'Webhooks', base: '/api/webhooks', endpoints: [ - { method:'POST', path:'/api/webhooks/payfast', auth:'PayFast ITN', desc:'PayFast payment notification (form-encoded). Checked as PayFast requires: signature, PayFast host, VALID from /eng/query/validate, and amount_gross equal to the checkout (otherwise held for review). COMPLETE records the payment.' }, - { method:'POST', path:'/api/webhooks/yoco', auth:'HMAC', desc:'Yoco payment event webhook. Called by Yoco servers. Verified via HMAC-SHA256 signature in the X-Yoco-Signature header.', - notes:'This endpoint bypasses the global rate limiter. Raw body is parsed before JSON middleware. Refreshes early-bird pricing before computing totalDue to ensure accurate paid/partial status.', - request:{ body:{ id:'evt_yoco_abc', type:'payment.succeeded', payload:{ metadata:{ checkoutId:'checkout-id-...' }, amount:45000, currency:'ZAR' }}}, - responses:[{ status:200, desc:'Acknowledged', body:{ received:true }}]}, - { method:'POST', path:'/api/webhooks/whatsapp', auth:'—', desc:'WAWP inbound message event. Called by WAWP servers when a message arrives on the linked number.', - responses:[{ status:200, desc:'Acknowledged', body:{ received:true }}]}, - ]}, - - { title: 'PayFast', base: '/api/payfast', endpoints: [ - { method:'GET', path:'/api/payfast/config', auth:'admin', desc:'PayFast settings (passphrase masked), mode and the ITN notify URL (with a warning when PayFast can\'t reach it).' }, - { method:'PUT', path:'/api/payfast/config', auth:'admin', desc:'Save merchantId, merchantKey, passphrase (encrypted) and/or mode (sandbox|live). Audit logged.' }, - { method:'POST', path:'/api/payfast/test', auth:'admin', desc:'Check the saved merchant ID and passphrase with PayFast (signed API ping).' }, - ]}, - { title: 'Yoco', base: '/api/yoco', endpoints: [ - { method:'GET', path:'/api/yoco/config', auth:'admin', desc:'Yoco settings with secrets masked (prefix + last 3 characters), where each comes from (db, env or none), test/live mode and the default webhook URL.', - responses:[{ status:200, desc:'Success', body:{ secretKeyMasked:'sk_test_***************aba', secretKeySource:'db', mode:'test', webhookSecretMasked:'whsec_*****************1Xz', webhookSecretSource:'db', webhookId:'sub_123', webhookUrl:'https://api.example.com/api/webhooks/yoco', configured:true }}]}, - { method:'PUT', path:'/api/yoco/config', auth:'admin', desc:'Save the secret key and/or webhook secret (stored AES-256-GCM encrypted). A new secret key is checked against Yoco first. An empty string clears the value (the .env fallback then applies).', - request:{ body:{ secretKey:'sk_test_...', webhookSecret:'whsec_...' }}, - responses:[{ status:200, desc:'Saved', body:{ message:'Yoco settings saved' }}]}, - { method:'GET', path:'/api/yoco/webhooks', auth:'admin', desc:'Webhooks registered on the Yoco account, flagged isActive (its secret is the stored one) and pointsHere (URL is this server).', - responses:[{ status:200, desc:'Success', body:{ webhooks:[{ id:'sub_123', name:'hope-events', url:'https://api.example.com/api/webhooks/yoco', mode:'test', isActive:true, pointsHere:true }], defaultUrl:'https://api.example.com/api/webhooks/yoco' }}]}, - { method:'POST', path:'/api/yoco/webhooks', auth:'admin', desc:'Register a webhook at Yoco (defaults: name "hope-events", URL = BACKEND_URL/api/webhooks/yoco) and store the secret Yoco returns. The URL must be public https.', - request:{ body:{ name:'hope-events', url:'https://api.example.com/api/webhooks/yoco' }}, - responses:[{ status:201, desc:'Registered', body:{ message:'Webhook registered and its secret saved', webhook:{ id:'sub_123', name:'hope-events', url:'https://api.example.com/api/webhooks/yoco', mode:'test' }, webhookSecretMasked:'whsec_*****************1Xz' }}]}, - { method:'DELETE', path:'/api/yoco/webhooks/:id', auth:'admin', desc:'Delete a webhook at Yoco. If it was the active one, the stored webhook secret is cleared too.', - responses:[{ status:200, desc:'Deleted', body:{ message:'Webhook deleted', clearedSecret:false }}]}, - ]}, - - { title: 'Settings', base: '/api/settings', endpoints: [ - { method:'GET', path:'/api/settings', auth:'public', desc:'Public settings — org name, brand colours (primary/secondary/accent), logo URL, favicon URL, legal page slugs, registration notification email (no secrets)', - responses:[{ status:200, desc:'Success', body:{ org_name:'Cross Code', org_tagline:'Event management, made simple', primary_color:'#4F46E5', secondary_color:'#8B5CF6', accent_color:'#EC4899', logo_url:'/uploads/branding/logo-123.png', favicon_url:'/uploads/branding/favicon-123.png' }}]}, - { method:'GET', path:'/api/settings/all', auth:'admin', desc:'All settings including SMTP config. smtp_pass is returned masked (••••••••); smtp_user is returned decrypted.', - responses:[{ status:200, desc:'Success', body:[{ key:'smtp_host', value:'smtp.example.com' },{ key:'smtp_user', value:'user@example.com' },{ key:'smtp_pass', value:'••••••••' }]}]}, - { method:'GET', path:'/api/settings/needs-setup', auth:'public', desc:'Returns true until the setup wizard has been completed (setup_complete flag is set).', - responses:[{ status:200, desc:'Success', body:{ needsSetup:true }}]}, - { method:'PUT', path:'/api/settings', auth:'admin', desc:'Upsert one or more settings. smtp_user and smtp_pass are AES-256-GCM encrypted before storage. Sending •••••••• for smtp_pass is a no-op.', - request:{ body:{ org_name:'Cross Code', smtp_host:'smtp.gmail.com', smtp_port:'587', smtp_user:'user@gmail.com', smtp_pass:'app-password' }}, - responses:[{ status:200, desc:'Saved', body:{ message:'Settings saved.' }}]}, - { method:'POST', path:'/api/settings/test-smtp', auth:'admin (or setup token)', desc:'Test the SMTP connection with provided credentials. On success, sends a real test email to the authenticated admin and returns a friendly message. On failure, returns a human-readable message plus a raw field containing the original SMTP error for debugging. Error code 530 (Microsoft "Client not authenticated") maps to the authentication-failure message.', - request:{ body:{ host:'smtp.gmail.com', port:587, secure:false, user:'me@gmail.com', pass:'app-password', from:'me@gmail.com' }}, - responses:[ - { status:200, desc:'Connection OK — test email sent', body:{ message:'SMTP connection verified — a test email has been sent to admin@example.com' }}, - { status:400, desc:'Connection failed', body:{ message:'Authentication failed — check your SMTP username and password.', raw:'535 5.7.8 Error: authentication failed' }}, - ]}, - ]}, - - { title: 'Setup', base: '/api/setup', endpoints: [ - { method:'POST', path:'/api/setup/register', auth:'public (one-time)', desc:'Step 2 of the first-time setup wizard. Creates the admin account and returns a short-lived JWT. Blocked once any user exists.', - request:{ body:{ name:'Admin User', email:'admin@example.com', password:'strong-password' }}, - responses:[ - { status:201, desc:'Created', body:{ token:'eyJhbGciOiJIUzI1NiJ9...', user:{ id:'uuid-...', name:'Admin User', role:'admin' }}}, - { status:400, desc:'Already exists', body:{ message:'Setup already completed — users exist.' }}, - ]}, - { method:'POST', path:'/api/setup', auth:'setup token or admin', desc:'Final step of the setup wizard. Saves initial site settings. Requires the JWT returned by POST /api/setup/register.', - request:{ body:{ settings:{ org_name:'Cross Code', smtp_host:'smtp.gmail.com', smtp_port:'587', smtp_user:'user@gmail.com', smtp_pass:'app-password', mail_from:'noreply@example.com' }}}, - responses:[{ status:200, desc:'Setup complete', body:{ message:'Setup complete.' }}]}, - ]}, - ]; - - // ── Rendering helpers ───────────────────────────────────────────────────── - function hl(json) { - // Simple JSON syntax highlighting — server-side - const s = JSON.stringify(json, null, 2); - return s - .replace(/&/g,'&').replace(//g,'>') - .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, (m) => { - if (/^"/.test(m)) { - if (/:$/.test(m)) return `${m}`; // key - return `${m}`; // string value - } - if (/true|false/.test(m)) return `${m}`; - if (/null/.test(m)) return `${m}`; - return `${m}`; // number - }); - } - - function codeBlock(content, lang) { - return `
${content}
`; - } - - function headerLine(key, val) { - return `${key}: ${val}`; - } - - function renderEndpoint(ep, idx) { - const id = `ep${idx}`; - const methodCls = { GET:'get', POST:'post', PUT:'put', PATCH:'patch', DELETE:'del' }[ep.method] || 'get'; - const hasDetail = ep.notes || ep.pathParams || ep.queryParams || ep.request || ep.responses; - - // Build HTTP request example - let reqLines = []; - const needsAuth = ep.auth !== 'public' && ep.auth !== 'HMAC' && ep.auth !== '—'; - const isMultipart = ep.notes && ep.notes.includes('multipart'); - - reqLines.push(`${ep.method} ${ep.path} HTTP/1.1`); - if (needsAuth) reqLines.push(headerLine('Authorization','Bearer <your-jwt>')); - if (ep.request?.body && !isMultipart) reqLines.push(headerLine('Content-Type','application/json')); - if (isMultipart) reqLines.push(headerLine('Content-Type','multipart/form-data')); - if (ep.request?.body && !isMultipart) { - reqLines.push(''); - reqLines.push(hl(ep.request.body)); - } else if (isMultipart) { - reqLines.push(''); - reqLines.push(`-- form field: image (binary file) --`); - } - - const reqHtml = codeBlock(reqLines.join('\n')); - - // Build response examples - const resHtml = (ep.responses || []).map(r => { - const statusColor = r.status < 300 ? '#22c55e' : r.status < 500 ? '#f59e0b' : '#ef4444'; - const body = typeof r.body === 'string' ? `${r.body}` : hl(r.body); - return `
-
- HTTP ${r.status} - ${r.desc} -
- ${codeBlock(body)} -
`; - }).join(''); - - // Path params table - let paramsHtml = ''; - if (ep.pathParams && Object.keys(ep.pathParams).length) { - const rows = Object.entries(ep.pathParams).map(([k,v]) => - `${k}${v}`).join(''); - paramsHtml += `
Path parameters
${rows}
`; - } - if (ep.queryParams && Object.keys(ep.queryParams).length) { - const rows = Object.entries(ep.queryParams).map(([k,v]) => - `${k}${v}`).join(''); - paramsHtml += `
Query parameters
${rows}
`; - } - - const notesHtml = ep.notes - ? `
${ep.notes}
` - : ''; - - const detailHtml = hasDetail ? ` - - -
- ${notesHtml} - ${paramsHtml} -
-
-
Request
- ${reqHtml} -
-
-
Responses
- ${resHtml} -
-
-
- - ` : ''; - - const cursor = hasDetail ? 'cursor:pointer' : ''; - const chevron = hasDetail - ? `` - : ''; - - const onclick = hasDetail ? `onclick="toggle('${id}')"` : ''; - - return ` - - ${ep.method} - ${ep.path} - ${ep.auth} - - ${ep.desc} - ${chevron} - - - ${detailHtml}`; - } - - function renderGroup(group) { - const rows = group.endpoints.map((ep, i) => renderEndpoint(ep, `${group.title.replace(/\W+/g,'')}-${i}`)).join(''); - return ` -

${group.title} ${group.base}

-
- - - - - - - - ${rows} -
MethodPathAuthDescription
-
`; - } - - const groupsHtml = GROUPS.map(renderGroup).join(''); - - // ── Notifications reference — every automatic email/WhatsApp message the system sends ── - const NOTIFICATIONS = [ - { category: 'Registration', items: [ - { trigger: 'New registration — self-service (attendee registers via the public website)', channels: ['Email', 'WhatsApp'], recipients: 'Registrant', subject: 'Registration confirmed – {event}', content: 'Selections table, total due / paid / balance, payment options (website or at the door), and an account login / create-account prompt.' }, - { trigger: 'New registration — self-service', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator when none are set)', subject: 'New registration: {event} — {name}', content: 'Registrant name, email, phone, status, items table, total due / paid / balance, registration ID.' }, - { trigger: 'New registration — staff/at-door (manual registration, self-service kiosk)', channels: ['Email', 'WhatsApp'], recipients: 'Registrant', subject: 'Registration confirmed – {event}', content: 'Same as above, plus a Yoco pay-now link when a balance is owing.' }, - { trigger: 'New registration — staff/at-door', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator)', subject: 'New registration: {event} — {name}', content: 'Same layout as the self-service admin notice.' }, - { trigger: 'Registration updated (options changed by staff, or a free registration completes)', channels: ['Email', 'WhatsApp'], recipients: 'Registrant', subject: 'Registration updated – {event}', content: 'Updated selections/total, same payment & account sections as the confirmation email.' }, - { trigger: 'Registration updated', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator)', subject: 'Registration updated: {event} — {name}', content: 'Same layout as the new-registration admin notice.' }, - ]}, - { category: 'Payments', items: [ - { trigger: 'Payment recorded (Yoco webhook success, manual cash/EFT entry, or a donation assigned to a registration)', channels: ['Email', 'WhatsApp'], recipients: 'Payer', subject: 'Payment received – {event} (or "Donation received – {event}" for unassigned donations)', content: 'Amount, method, date, full payment history table, updated balance.' }, - { trigger: 'Payment recorded', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator)', subject: 'Payment recorded: {amount} — {payer} ({event})', content: 'Amount, type (registration payment / donation), payer, event, method, date, payment ID, external (Yoco) ID.' }, - { trigger: 'Refund processed (negative payment created against an original payment)', channels: ['Email'], recipients: 'Payer', subject: 'Refund processed – {amount} for {event}', content: 'Refund amount, method, date, reason (when supplied).' }, - { trigger: 'Refund processed', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator)', subject: 'Refund: Payment recorded: {amount} — {payer} ({event})', content: 'Same payment admin notice content, subject prefixed "Refund:".' }, - ]}, - { category: 'Tickets', items: [ - { trigger: 'Tickets generated — fires whenever a registration becomes fully paid or is free (webhook, manual payment, staff status change, or free/no-cost registration)', channels: ['Email (PDF attached)', 'WhatsApp (PDF)'], recipients: 'Registrant (or a specific user when sent manually via "Send to")', subject: 'Your tickets for {event}', content: 'QR-coded ticket PDF, one per registered option/quantity; WhatsApp caption names the event and date.' }, - ]}, - { category: 'Daily digest', items: [ - { trigger: 'Scheduled — every day at 07:00 local server time, once per active event that has gone live and has not yet started', channels: ['Email'], recipients: 'Admin — registrations inbox + event notify recipients (falls back to the event creator)', subject: 'Daily summary: {event} — {date}', content: 'Stat tiles (registrations, paid, awaiting payment, revenue), full registrations table with balances, full payments & donations table.' }, - ]}, - { category: 'Account & security', items: [ - { trigger: 'New account registered', channels: ['Email (always)', 'WhatsApp (if preferred)'], recipients: 'New user', subject: 'Welcome to {org}!', content: 'Welcome message plus a list of upcoming events.' }, - { trigger: 'Login attempt on an account that is not yet active', channels: ['Email (if a real address is on file)', 'WhatsApp (fallback when there is no usable email)'], recipients: 'User', subject: 'Activate your {org} account', content: 'One-time activation link; expires after 24 hours.' }, - { trigger: 'Successful login', channels: ['Email (always)', 'WhatsApp (if preferred)'], recipients: 'User', subject: 'New login to your {org} account', content: 'Login time, approximate location, device/user agent. Security alert — always emailed regardless of the user\'s notification preference.' }, - { trigger: 'Password changed via profile update', channels: ['Email (always)', 'WhatsApp (if preferred)'], recipients: 'User', subject: 'Your {org} password was changed', content: 'Confirms the change and gives a support contact to use if it wasn\'t them.' }, - { trigger: 'Forgot-password request', channels: ['Email (always)', 'WhatsApp (if preferred)'], recipients: 'User', subject: 'Reset your password', content: 'Password reset link.' }, - { trigger: 'Account closed (self-service — "Deactivate" or "Delete my data")', channels: ['Email', 'WhatsApp (if preferred)'], recipients: 'User (sent to their last-known address/number just before data is wiped)', subject: 'Your {org} account has been closed', content: 'Confirms closure; wording differs slightly when personal data was also erased.' }, - ]}, - { category: 'Admin-triggered broadcasts', items: [ - { trigger: 'Bulk email to event attendees, or an ad-hoc email broadcast — sent immediately or on a schedule', channels: ['Email'], recipients: 'Selected attendees / users / ad-hoc addresses chosen by the sender', subject: 'Admin-authored', content: 'Free-form subject & body written by the sender, supporting {{name}}, {{event.title}}, {{event.link}} placeholders. Used for reminders, thank-yous, promos, and multi-step automations.' }, - { trigger: 'Bulk WhatsApp to event attendees, or an ad-hoc WhatsApp broadcast — sent immediately or on a schedule', channels: ['WhatsApp'], recipients: 'Selected attendees / users / ad-hoc phone numbers chosen by the sender', subject: '—', content: 'Free-form message written by the sender, same placeholder support as email broadcasts.' }, - ]}, - ]; - - function notifChannelBadges(channels) { - return channels.map(c => { - const isWa = /whatsapp/i.test(c); - return `${c}`; - }).join(''); - } - - function renderNotificationRow(n) { - return ` - ${n.trigger} - ${notifChannelBadges(n.channels)} - ${n.recipients} - ${n.subject} - ${n.content} - `; - } - - function renderNotificationCategory(cat) { - const rows = cat.items.map(renderNotificationRow).join(''); - return ` -

${cat.category}

-
- - - - - - - - - ${rows} -
Trigger — when it's sentChannelRecipientsSubjectContent
-
`; - } - - const notificationsHtml = NOTIFICATIONS.map(renderNotificationCategory).join(''); - const orgName = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Code'); - - const html = ` - - - - - ${orgName} Events — API Docs - - - -
-
-

${orgName} Events — API Reference

- ← Status page -
-

- Logged in as ${user.name || user.email} (${user.role}) — - Click any row to expand request & response examples. -

- -
- Protected routes require Authorization: Bearer <jwt>  |  - Roles: admin > supervisor > staff > user  |  - Base URL: ${process.env.APP_BASE_URL || 'http://localhost:' + PORT} -
- - ${groupsHtml} - -

Notifications sent by the system

-

- Every automatic email and WhatsApp message the platform sends, what triggers it, who receives it, and what it contains. - Admin-facing registration/payment/daily-summary notices go to the reg_notification_emails setting plus each - event's configured notify recipients (Admin → Events → edit event → Notifications step) — - falling back to that event's creator when no recipients have been chosen. -

- - ${notificationsHtml} - -

- ${orgName} Events API v${API_VERSION} — ${new Date().toISOString()} -

-
- - -`; - - res.send(html); -}); +// /docs: the v1 reference went with v1 in 2.0; the API is documented at /docs/v2 (OpenAPI). +app.get('/docs', (req, res) => res.redirect(301, '/docs/v2')); // Error middleware app.use(notFound); diff --git a/apps/events/backend/src/config/auth.js b/apps/events/backend/src/config/auth.js index 7db1a5d..8249210 100644 --- a/apps/events/backend/src/config/auth.js +++ b/apps/events/backend/src/config/auth.js @@ -1,4 +1,6 @@ const jwt = require('jsonwebtoken'); +const argon2 = require('@node-rs/argon2'); +// Only for checking passwords saved before 2.0 (they're re-hashed with Argon2id at the next sign-in). const bcrypt = require('bcryptjs'); // `extra` adds claims, e.g. { setup: true } for the first-run setup wizard's token. @@ -10,17 +12,30 @@ const generateToken = (userId, role, tokenVersion = 0, extra = {}) => { ); }; -const hashPassword = async (password) => { - const salt = await bcrypt.genSalt(10); - return await bcrypt.hash(password, salt); +// Argon2id with OWASP's recommended minimum (19 MiB, 2 passes, 1 lane): about 20–40 ms a hash. +const ARGON2 = { algorithm: 2 /* Argon2id (a const enum in the typings, so not on the module) */, memoryCost: 19456, timeCost: 2, parallelism: 1 }; +const ARGON2_PREFIX = `$argon2id$v=19$m=${ARGON2.memoryCost},t=${ARGON2.timeCost},p=${ARGON2.parallelism}$`; + +const hashPassword = async (password) => argon2.hash(password, ARGON2); + +/** Whether `entered` is the password behind `stored` (an Argon2 hash, or a bcrypt one from before 2.0). */ +const comparePassword = async (enteredPassword, storedPassword) => { + if (typeof enteredPassword !== 'string' || typeof storedPassword !== 'string') return false; + try { + if (storedPassword.startsWith('$argon2')) return await argon2.verify(storedPassword, enteredPassword); + if (/^\$2[aby]\$/.test(storedPassword)) return await bcrypt.compare(enteredPassword, storedPassword); + } catch { + // A malformed hash never matches. + } + return false; }; -const comparePassword = async (enteredPassword, storedPassword) => { - return await bcrypt.compare(enteredPassword, storedPassword); -}; +/** True for a hash that isn't Argon2id with today's settings (bcrypt, or weaker Argon2). */ +const needsRehash = (storedPassword) => typeof storedPassword === 'string' && !storedPassword.startsWith(ARGON2_PREFIX); module.exports = { generateToken, hashPassword, comparePassword, -}; \ No newline at end of file + needsRehash, +}; diff --git a/apps/events/backend/src/hub/client.js b/apps/events/backend/src/hub/client.js index 4b5dc4c..53d5f87 100644 --- a/apps/events/backend/src/hub/client.js +++ b/apps/events/backend/src/hub/client.js @@ -25,10 +25,12 @@ function hubUrl() { } class HubError extends Error { - constructor(message, code, status) { + constructor(message, code, status, data = null) { super(message); this.code = code; this.statusCode = status; + // The Hub's whole error body (AI errors carry the new AI status, protocol §3b). + this.data = data; } } @@ -53,7 +55,7 @@ async function read(keys) { return Object.fromEntries(rows.map(r => [r.key, r.value])); } -async function post(path, body, headers = {}) { +async function post(path, body, headers = {}, timeoutMs = TIMEOUT_MS) { const raw = JSON.stringify(body); let res; try { @@ -61,18 +63,21 @@ async function post(path, body, headers = {}) { method: 'POST', headers: { 'Content-Type': 'application/json', ...(typeof headers === 'function' ? headers(raw) : headers) }, body: raw, - signal: AbortSignal.timeout(TIMEOUT_MS), + signal: AbortSignal.timeout(timeoutMs), }); } catch (e) { throw new HubError(`The Hub (${hubUrl()}) could not be reached: ${e?.message || e}`, 'HUB_UNREACHABLE', 502); } const data = await res.json().catch(() => ({})); - if (!res.ok) throw new HubError(data.message || `The Hub answered ${res.status}`, data.code || 'HUB_ERROR', res.status); + if (!res.ok) throw new HubError(data.message || `The Hub answered ${res.status}`, data.code || 'HUB_ERROR', res.status, data); return data; } -/** POST signed with the install secret (§3). Throws NOT_CONNECTED when there is no connection. */ -async function signedPost(path, body) { +/** + * POST signed with the install secret (§3). Throws NOT_CONNECTED when there is no connection. + * AI calls wait longer than the default (Claude can take a while to write). + */ +async function signedPost(path, body, { timeoutMs = TIMEOUT_MS } = {}) { const s = await read(['hub_install_id', 'hub_install_secret']); if (!s.hub_install_id || !s.hub_install_secret) throw new HubError('This site isn\'t connected to the Hub yet.', 'NOT_CONNECTED', 400); const secret = decrypt(s.hub_install_secret); @@ -83,7 +88,7 @@ async function signedPost(path, body) { 'X-Hub-Timestamp': timestamp, 'X-Hub-Signature': crypto.createHmac('sha256', secret).update(`${timestamp}.${raw}`).digest('hex'), }; - }); + }, timeoutMs); } /** Register this install with a licence key. Returns the licence claims. */ @@ -211,4 +216,4 @@ function heartbeatSoon(delayMs = 30 * 1000) { soonTimer.unref?.(); } -module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, connect, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate }; +module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, signedPost, connect, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate }; diff --git a/apps/events/backend/src/hub/readOnly.js b/apps/events/backend/src/hub/readOnly.js index 31c50fc..8781943 100644 --- a/apps/events/backend/src/hub/readOnly.js +++ b/apps/events/backend/src/hub/readOnly.js @@ -10,38 +10,8 @@ const { licenceStatus } = require('./licence'); -// v1 paths (until 2.0 removes them) and their /api/v2 successors (1.52.3: the screens have used v2 -// since 1.51.15, so without these a suspended or unlicensed site wasn't read-only any more). +// /api/v2 only: 2.0 removed v1 (1.52.3 added these — the screens had used v2 since 1.51.15). const BLOCKED = [ - ['POST', /^\/api\/events\/?$/], - ['PUT', /^\/api\/events\/[^/]+\/?$/], - ['POST', /^\/api\/events\/[^/]+\/copy-from\/?$/], - ['POST', /^\/api\/series\/?$/], - ['PUT', /^\/api\/series\/[^/]+\/?$/], - // Season passes: new or changed passes, and buying one (it makes registrations and payments). - ['POST', /^\/api\/season-passes\/?$/], - ['PUT', /^\/api\/season-passes\/[^/]+\/?$/], - ['POST', /^\/api\/season-passes\/[^/]+\/buy\/?$/], - ['POST', /^\/api\/season-passes\/purchases\/[^/]+\/checkout\/?$/], - ['POST', /^\/api\/events\/[^/]+\/options\/?$/], - ['PUT', /^\/api\/events\/options\/[^/]+\/?$/], - ['POST', /^\/api\/events\/options\/[^/]+\/variants\/?$/], - ['PUT', /^\/api\/events\/variants\/[^/]+\/?$/], - ['POST', /^\/api\/registrations\/?$/], - ['POST', /^\/api\/registrations\/manual\/?$/], - ['PUT', /^\/api\/registrations\/[^/]+\/options\/?$/], - ['POST', /^\/api\/payments\/?$/], - ['POST', /^\/api\/payments\/(checkout|yoco-checkout)(\/send)?\/?$/], - ['POST', /^\/api\/payments\/pay\/[^/]+\/?$/], - ['POST', /^\/api\/waitlist\/?$/], - ['POST', /^\/api\/coupons\/?$/], - ['POST', /^\/api\/bundles\/event\/[^/]+\/?$/], - // Volunteer rosters: new roles and new people on them (they can carry a free ticket). - ['POST', /^\/api\/volunteers\/roles\/[^/]+\/sign-up\/?$/], - ['POST', /^\/api\/volunteers\/manage\/events\/[^/]+\/roles\/?$/], - ['POST', /^\/api\/volunteers\/manage\/roles\/[^/]+\/assign\/?$/], - - // /api/v2 — the same actions. ['POST', /^\/api\/v2\/events\/?$/], ['PATCH', /^\/api\/v2\/events\/[^/]+\/?$/], ['POST', /^\/api\/v2\/events\/[^/]+\/copy-from\/?$/], diff --git a/apps/events/backend/src/routes/adminRoutes.js b/apps/events/backend/src/routes/adminRoutes.js deleted file mode 100644 index 2f28b35..0000000 --- a/apps/events/backend/src/routes/adminRoutes.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listAuditLog } = require('../controllers/adminAuditController'); -const { startImpersonation, endImpersonation, logPageView, currentImpersonation, listSessions } = require('../controllers/impersonationController'); -const { listJobs, runJobNow } = require('../controllers/jobsController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -router.get('/audit-log', protect, admin, listAuditLog); -router.get('/jobs', protect, admin, listJobs); -router.post('/jobs/:name/run', protect, admin, runJobNow); -router.get('/impersonation-sessions', protect, admin, listSessions); -// Called with the impersonation token itself (which belongs to the viewed user). -router.post('/impersonate/end', protect, endImpersonation); -router.post('/impersonate/log', protect, logPageView); -router.get('/impersonate/current', protect, currentImpersonation); -router.post('/impersonate/:userId', protect, admin, startImpersonation); - -module.exports = router; diff --git a/apps/events/backend/src/routes/allocationRoutes.js b/apps/events/backend/src/routes/allocationRoutes.js deleted file mode 100644 index b537ec9..0000000 --- a/apps/events/backend/src/routes/allocationRoutes.js +++ /dev/null @@ -1,23 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - getBoard, createSet, updateSet, deleteSet, createGroup, updateGroup, deleteGroup, - assign, autoAssign, clearAssignments, getSetLists, getMyGroups, -} = require('../controllers/allocationController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent, campusIndependent } = require('../utils/campusScope'); - -router.get('/my-groups', protect, staff, campusIndependent('only the groups the signed-in person leads'), getMyGroups); -router.get('/event/:eventId', protect, supervisor, scopeEvent(), getBoard); -router.post('/sets', protect, supervisor, scopeEvent({ from: req => req.body?.eventId }), createSet); -router.put('/sets/:id', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), updateSet); -router.delete('/sets/:id', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), deleteSet); -router.get('/sets/:id/lists', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), getSetLists); -router.post('/sets/:id/groups', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), createGroup); -router.put('/sets/:id/assignments', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), assign); -router.delete('/sets/:id/assignments', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), clearAssignments); -router.post('/sets/:id/auto', protect, supervisor, scopeEvent({ resolve: 'allocationSet' }), autoAssign); -router.put('/groups/:id', protect, supervisor, scopeEvent({ resolve: 'allocationGroup' }), updateGroup); -router.delete('/groups/:id', protect, supervisor, scopeEvent({ resolve: 'allocationGroup' }), deleteGroup); - -module.exports = router; diff --git a/apps/events/backend/src/routes/analyticsRoutes.js b/apps/events/backend/src/routes/analyticsRoutes.js deleted file mode 100644 index 42b2327..0000000 --- a/apps/events/backend/src/routes/analyticsRoutes.js +++ /dev/null @@ -1,19 +0,0 @@ -const express = require('express'); -const rateLimit = require('express-rate-limit'); -const router = express.Router(); -const { trackStage, getFunnel } = require('../controllers/analyticsController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeList } = require('../utils/campusScope'); - -const trackLimiter = rateLimit({ - windowMs: 60 * 1000, - max: 60, - standardHeaders: true, - legacyHeaders: false, - handler: (req, res) => res.status(204).end(), // silently drop floods -}); - -router.post('/track', trackLimiter, trackStage); -router.get('/funnel', protect, supervisor, scopeList, getFunnel); - -module.exports = router; diff --git a/apps/events/backend/src/routes/attendanceRoutes.js b/apps/events/backend/src/routes/attendanceRoutes.js deleted file mode 100644 index 69f390b..0000000 --- a/apps/events/backend/src/routes/attendanceRoutes.js +++ /dev/null @@ -1,26 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - getRegister, markAttendance, exportRegister, - issueCertificates, revokeCertificate, sendCertificatesHandler, downloadEventCertificates, previewCertificate, - myCertificates, downloadCertificate, verifyCertificate, -} = require('../controllers/attendanceController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent, campusIndependent } = require('../utils/campusScope'); - -// Certificates — fixed paths first so they aren't taken as an :eventId -router.get('/certificates/verify/:code', verifyCertificate); -router.get('/certificates/mine', protect, myCertificates); -router.post('/certificates/preview', protect, supervisor, campusIndependent('previews a certificate template from the request body'), previewCertificate); -router.get('/certificates/:id/pdf', protect, downloadCertificate); -router.post('/certificates/:id/revoke', protect, supervisor, scopeEvent({ resolve: 'certificate' }), revokeCertificate); - -// Attendance register -router.get('/:eventId', protect, staff, scopeEvent(), getRegister); -router.get('/:eventId/export', protect, staff, scopeEvent(), exportRegister); -router.post('/:eventId/mark', protect, supervisor, scopeEvent(), markAttendance); -router.post('/:eventId/certificates', protect, supervisor, scopeEvent(), issueCertificates); -router.post('/:eventId/certificates/send', protect, supervisor, scopeEvent(), sendCertificatesHandler); -router.get('/:eventId/certificates.pdf', protect, supervisor, scopeEvent(), downloadEventCertificates); - -module.exports = router; diff --git a/apps/events/backend/src/routes/automationRoutes.js b/apps/events/backend/src/routes/automationRoutes.js deleted file mode 100644 index 8aea12e..0000000 --- a/apps/events/backend/src/routes/automationRoutes.js +++ /dev/null @@ -1,10 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { scheduleAutomations } = require('../controllers/automationController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -// Schedule multiple automation emails for an event -router.post('/schedule', protect, supervisor, scopeEvent({ from: req => req.body?.eventId }), scheduleAutomations); - -module.exports = router; diff --git a/apps/events/backend/src/routes/backupRoutes.js b/apps/events/backend/src/routes/backupRoutes.js deleted file mode 100644 index 00f5ca7..0000000 --- a/apps/events/backend/src/routes/backupRoutes.js +++ /dev/null @@ -1,10 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getBackups, triggerBackup, downloadBackup } = require('../controllers/backupController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -router.get('/', protect, admin, getBackups); -router.post('/run', protect, admin, triggerBackup); -router.get('/:filename/download', protect, admin, downloadBackup); - -module.exports = router; diff --git a/apps/events/backend/src/routes/bannerRoutes.js b/apps/events/backend/src/routes/bannerRoutes.js deleted file mode 100644 index a51d2c2..0000000 --- a/apps/events/backend/src/routes/bannerRoutes.js +++ /dev/null @@ -1,10 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getBanner, setBanner } = require('../controllers/bannerController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { unscopedOnly } = require('../utils/campusScope'); - -router.get('/', getBanner); -router.post('/', protect, supervisor, unscopedOnly, setBanner); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/broadcastRoutes.js b/apps/events/backend/src/routes/broadcastRoutes.js deleted file mode 100644 index 0d471ea..0000000 --- a/apps/events/backend/src/routes/broadcastRoutes.js +++ /dev/null @@ -1,12 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { previewBroadcast, sendBroadcast, scheduleBroadcast } = require('../controllers/broadcastController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeBroadcast } = require('../utils/campusScope'); - -// All routes require supervisor (or admin via middleware logic) access -router.post('/preview', protect, supervisor, scopeBroadcast({ freeformField: 'emails' }), previewBroadcast); -router.post('/send', protect, supervisor, scopeBroadcast({ freeformField: 'emails' }), sendBroadcast); -router.post('/schedule', protect, supervisor, scopeBroadcast({ freeformField: 'emails' }), scheduleBroadcast); - -module.exports = router; diff --git a/apps/events/backend/src/routes/bundleRoutes.js b/apps/events/backend/src/routes/bundleRoutes.js deleted file mode 100644 index 6a09709..0000000 --- a/apps/events/backend/src/routes/bundleRoutes.js +++ /dev/null @@ -1,15 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listBundles, createBundle, updateBundle, deleteBundle, quoteBundles } = require('../controllers/bundleController'); -const { protect, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -// What a basket gets off before registering (guests included) -router.post('/quote', optionalAuth, quoteBundles); - -router.get('/event/:eventId', protect, supervisor, scopeEvent(), listBundles); -router.post('/event/:eventId', protect, supervisor, scopeEvent({ need: 'manage' }), createBundle); -router.put('/:id', protect, supervisor, scopeEvent({ resolve: 'bundle', need: 'manage' }), updateBundle); -router.delete('/:id', protect, supervisor, scopeEvent({ resolve: 'bundle', need: 'manage' }), deleteBundle); - -module.exports = router; diff --git a/apps/events/backend/src/routes/campusRoutes.js b/apps/events/backend/src/routes/campusRoutes.js deleted file mode 100644 index f63f4f1..0000000 --- a/apps/events/backend/src/routes/campusRoutes.js +++ /dev/null @@ -1,21 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - getCampuses, getCampusBySlug, getCampusesAdmin, updateCampusSettings, createCampus, updateCampus, reorderCampuses, deleteCampus, - getCampusAudience, -} = require('../controllers/campusController'); -const { protect, admin, supervisor } = require('../middleware/authMiddleware'); -const { scopeList } = require('../utils/campusScope'); - -// Multi-campus (utils/campuses.js). The public list is empty while campuses are off. -router.get('/', getCampuses); -router.get('/by-slug/:slug', getCampusBySlug); -router.get('/admin', protect, admin, getCampusesAdmin); -router.put('/settings', protect, admin, updateCampusSettings); -router.put('/order', protect, admin, reorderCampuses); -router.post('/', protect, admin, createCampus); -router.put('/:id', protect, admin, updateCampus); -router.delete('/:id', protect, admin, deleteCampus); -router.get('/:id/audience', protect, supervisor, scopeList, getCampusAudience); - -module.exports = router; diff --git a/apps/events/backend/src/routes/cashupRoutes.js b/apps/events/backend/src/routes/cashupRoutes.js deleted file mode 100644 index c0ccbfe..0000000 --- a/apps/events/backend/src/routes/cashupRoutes.js +++ /dev/null @@ -1,16 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getEventCashup, getCashByRecordedUser, savePersonCash, saveEventCashupDraft, closeEvent, reopenEvent, resolvePending, getCashupAudit } = require('../controllers/cashupController'); -const { protect, supervisor, admin } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -router.get('/audit', protect, supervisor, scopeList, getCashupAudit); -router.get('/event/:eventId', protect, supervisor, scopeEvent({ need: 'manage' }), getEventCashup); -router.get('/event/:eventId/cash-by-user', protect, supervisor, scopeEvent({ need: 'manage' }), getCashByRecordedUser); -router.put('/event/:eventId/person-cash/:userId', protect, supervisor, scopeEvent({ need: 'manage' }), savePersonCash); -router.put('/event/:eventId/draft', protect, admin, saveEventCashupDraft); -router.post('/event/:eventId/close', protect, admin, closeEvent); -router.post('/event/:eventId/reopen', protect, admin, reopenEvent); -router.post('/lines/:lineId/pending', protect, admin, resolvePending); - -module.exports = router; diff --git a/apps/events/backend/src/routes/consentRoutes.js b/apps/events/backend/src/routes/consentRoutes.js deleted file mode 100644 index f73d636..0000000 --- a/apps/events/backend/src/routes/consentRoutes.js +++ /dev/null @@ -1,21 +0,0 @@ -const express = require('express'); -const rateLimit = require('express-rate-limit'); -const router = express.Router(); -const { getConsent, answerConsent, listEventConsent, resendRequest, resendPending, rerequestConsent, medicalList } = require('../controllers/consentController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -// The token in the link is the parent's only credential, so keep guessing slow. -const consentLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, message: { message: 'Too many attempts. Please try again in a minute.' } }); - -router.get('/events/:eventId', protect, staff, scopeEvent(), listEventConsent); -router.post('/events/:eventId/resend-pending', protect, supervisor, scopeEvent(), resendPending); -router.post('/events/:eventId/rerequest', protect, supervisor, scopeEvent(), rerequestConsent); -router.get('/events/:eventId/medical', protect, supervisor, scopeEvent(), medicalList); -router.post('/requests/:id/resend', protect, scopeEvent({ resolve: 'consentRequest', ownerOk: true }), resendRequest); - -// Public consent page -router.get('/:token', consentLimiter, getConsent); -router.post('/:token', consentLimiter, answerConsent); - -module.exports = router; diff --git a/apps/events/backend/src/routes/costRoutes.js b/apps/events/backend/src/routes/costRoutes.js deleted file mode 100644 index 9051352..0000000 --- a/apps/events/backend/src/routes/costRoutes.js +++ /dev/null @@ -1,13 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getEventCosts, createEventCost, updateEventCost, deleteEventCost } = require('../controllers/costController'); -const { protect, supervisor, admin } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -// Mounted at /api — paths below match the documented /api/events/:eventId/costs and /api/costs/:id shape -router.get('/events/:eventId/costs', protect, supervisor, scopeEvent({ need: 'manage' }), getEventCosts); -router.post('/events/:eventId/costs', protect, admin, createEventCost); -router.put('/costs/:id', protect, admin, updateEventCost); -router.delete('/costs/:id', protect, admin, deleteEventCost); - -module.exports = router; diff --git a/apps/events/backend/src/routes/couponRoutes.js b/apps/events/backend/src/routes/couponRoutes.js deleted file mode 100644 index f97f2b2..0000000 --- a/apps/events/backend/src/routes/couponRoutes.js +++ /dev/null @@ -1,16 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listCoupons, getCoupon, createCoupon, updateCoupon, validateCode, listRedemptions } = require('../controllers/couponController'); -const { protect, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -// Check a code against a basket before registering (guests included) -router.post('/validate', optionalAuth, scopeEvent({ from: req => req.body?.eventId }), validateCode); - -router.get('/', protect, supervisor, scopeList, listCoupons); -router.post('/', protect, supervisor, scopeList, createCoupon); -router.get('/redemptions', protect, supervisor, scopeList, listRedemptions); -router.get('/:id', protect, supervisor, scopeList, getCoupon); -router.put('/:id', protect, supervisor, scopeList, updateCoupon); - -module.exports = router; diff --git a/apps/events/backend/src/routes/eventRoutes.js b/apps/events/backend/src/routes/eventRoutes.js deleted file mode 100644 index 1e38f8f..0000000 --- a/apps/events/backend/src/routes/eventRoutes.js +++ /dev/null @@ -1,93 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - createEvent, - copyEventSetupFrom, - getEvents, - getAllEvents, - getEventsAll, - getEventById, - getEventIcs, - updateEvent, - getEventNotifyRecipients, - updateEventNotifyRecipients, - deleteEvent, - createEventOption, - updateEventOption, - deleteEventOption, - createOptionVariant, - updateOptionVariant, - deleteOptionVariant, - listEventAttachments, - uploadEventAttachment, - deleteEventAttachment, - attachmentsStatus, - attachmentsSync, - emailEventAttendees, - scheduleEmailEventAttendees, - whatsappEventAttendees, - scheduleWhatsappEventAttendees, - getEventByAlias -} = require('../controllers/eventController'); -const { protect, admin, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeBody, scopeList } = require('../utils/campusScope'); - -// Public routes -router.get('/', getEvents); - -// Staff/supervisor/admin: all events including hidden, optional past/inactive filters -router.get('/all', protect, getEventsAll); - -// Admin routes -router.get('/admin/all', protect, admin, getAllEvents); -router.get('/attachments/status', protect, admin, attachmentsStatus); -router.post('/attachments/sync', protect, admin, attachmentsSync); - -// Public route for single event (keep after specific admin routes). -// optionalAuth populates req.user when a valid token is present so staff/supervisor/admin -// can still load inactive events (e.g. for cashup or editing) without being 404'd. -router.get('/:id', optionalAuth, getEventById); -router.get('/:id/ics', optionalAuth, getEventIcs); -router.get('/by-alias/:redirectUrl', getEventByAlias); - -// Create/Update/Delete event -router.post('/', protect, supervisor, scopeList, createEvent); -router.route('/:id') - .put(protect, supervisor, scopeEvent({ need: 'manage' }), updateEvent) - .delete(protect, admin, deleteEvent); - -// Clone: copy allocation groups (and costs, for admins) from the source event into a new copy. -router.post('/:id/copy-from', protect, supervisor, scopeEvent({ need: 'manage' }), scopeBody([['fromEventId', 'event']]), copyEventSetupFrom); - -// Notification recipients: who gets registration/payment/daily-summary emails for this event -router.route('/:id/notify-recipients') - .get(protect, supervisor, scopeEvent(), getEventNotifyRecipients) - .put(protect, supervisor, scopeEvent({ need: 'manage' }), updateEventNotifyRecipients); - -// Attachments routes -router.get('/:id/attachments', listEventAttachments); // public read (used by event detail page) -router.post('/:id/attachments', protect, supervisor, scopeEvent({ need: 'manage' }), ...uploadEventAttachment); -router.delete('/:eventId/attachments/:attachmentId', protect, supervisor, scopeEvent({ need: 'manage' }), deleteEventAttachment); - -// Bulk email attendees -router.post('/:id/email-attendees', protect, supervisor, scopeEvent(), emailEventAttendees); -// Schedule bulk email to attendees -router.post('/:id/email-attendees/schedule', protect, supervisor, scopeEvent(), scheduleEmailEventAttendees); -// Bulk WhatsApp message to attendees -router.post('/:id/whatsapp-attendees', protect, supervisor, scopeEvent(), whatsappEventAttendees); -// Schedule bulk WhatsApp message to attendees -router.post('/:id/whatsapp-attendees/schedule', protect, supervisor, scopeEvent(), scheduleWhatsappEventAttendees); - -// Event options routes -router.post('/:id/options', protect, supervisor, scopeEvent({ need: 'manage' }), createEventOption); -router.route('/options/:id') - .put(protect, supervisor, scopeEvent({ resolve: 'eventOption', need: 'manage' }), updateEventOption) - .delete(protect, admin, deleteEventOption); - -// Option variant routes -router.post('/options/:id/variants', protect, supervisor, scopeEvent({ resolve: 'eventOption', need: 'manage' }), createOptionVariant); -router.route('/variants/:id') - .put(protect, supervisor, scopeEvent({ resolve: 'optionVariant', need: 'manage' }), updateOptionVariant) - .delete(protect, admin, deleteOptionVariant); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/feedbackRoutes.js b/apps/events/backend/src/routes/feedbackRoutes.js deleted file mode 100644 index 7fd65f5..0000000 --- a/apps/events/backend/src/routes/feedbackRoutes.js +++ /dev/null @@ -1,15 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getEventFeedback, saveEventFeedback, deleteEventFeedback, sendNow, getPublicForm, submitPublicForm, getSummary } = require('../controllers/feedbackController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -router.get('/public/:token', getPublicForm); -router.post('/public/:token', submitPublicForm); -router.get('/summary', protect, supervisor, scopeList, getSummary); -router.get('/event/:eventId', protect, supervisor, scopeEvent(), getEventFeedback); -router.put('/event/:eventId', protect, supervisor, scopeEvent({ need: 'manage' }), saveEventFeedback); -router.delete('/event/:eventId', protect, supervisor, scopeEvent({ need: 'manage' }), deleteEventFeedback); -router.post('/event/:eventId/send-now', protect, supervisor, scopeEvent({ need: 'manage' }), sendNow); - -module.exports = router; diff --git a/apps/events/backend/src/routes/formRoutes.js b/apps/events/backend/src/routes/formRoutes.js deleted file mode 100644 index 1771ce0..0000000 --- a/apps/events/backend/src/routes/formRoutes.js +++ /dev/null @@ -1,10 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listFormResponses } = require('../controllers/formController'); -const { protect, staff } = require('../middleware/authMiddleware'); -const { scopeList } = require('../utils/campusScope'); - -// Staff or higher can view submitted forms -router.get('/responses', protect, staff, scopeList, listFormResponses); - -module.exports = router; diff --git a/apps/events/backend/src/routes/hubRoutes.js b/apps/events/backend/src/routes/hubRoutes.js deleted file mode 100644 index 53ef6e9..0000000 --- a/apps/events/backend/src/routes/hubRoutes.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getStatus, connect, heartbeatNow, requestUpdate, cancelUpdateRequest, snoozeUpdate, getNotices } = require('../controllers/hubController'); -const { protect, admin, supervisor } = require('../middleware/authMiddleware'); -const { campusIndependent } = require('../utils/campusScope'); - -// Licence and the Cross Events Hub (docs/hub-protocol.md). Admins only; the setup wizard's -// admin token counts, so the licence step can run during /setup. -router.get('/status', protect, admin, getStatus); -router.post('/connect', protect, admin, connect); -router.post('/heartbeat', protect, admin, heartbeatNow); -router.post('/update-request', protect, admin, requestUpdate); -router.post('/update-request/cancel', protect, admin, cancelUpdateRequest); -router.post('/update-snooze', protect, admin, snoozeUpdate); -// The provider's notices: site admins and supervisors see them as a banner. -router.get('/notices', protect, supervisor, campusIndependent('notices from the provider are for the whole site'), getNotices); - -module.exports = router; diff --git a/apps/events/backend/src/routes/kidsRoutes.js b/apps/events/backend/src/routes/kidsRoutes.js deleted file mode 100644 index d354f38..0000000 --- a/apps/events/backend/src/routes/kidsRoutes.js +++ /dev/null @@ -1,47 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const c = require('../controllers/kidsController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -// My account → Kids (any signed-in parent; only their own family) -router.get('/me', protect, c.getMine); -router.post('/me', protect, c.createMine); -router.put('/me', protect, c.renameMine); -router.delete('/me', protect, c.leaveMine); -router.post('/me/children', protect, c.saveMyChild); -router.put('/me/children/:id', protect, c.saveMyChild); -router.delete('/me/children/:id', protect, c.deleteMyChild); -router.post('/me/adults', protect, c.saveMyAdult); -router.put('/me/adults/:id', protect, c.saveMyAdult); -router.delete('/me/adults/:id', protect, c.deleteMyAdult); - -// Setup (supervisors) -router.get('/setup-events', protect, supervisor, scopeList, c.setupEvents); -router.get('/events/:eventId/settings', protect, supervisor, scopeEvent(), c.getSettings); -router.put('/events/:eventId/settings', protect, supervisor, scopeEvent({ need: 'manage' }), c.saveSettings); - -// The desk and the rooms (staff). Families are church-wide; staff reach them through an event -// they can work on. -router.get('/events', protect, staff, scopeList, c.listEvents); -router.get('/events/:eventId/board', protect, staff, scopeEvent(), c.getBoard); -router.get('/events/:eventId/families', protect, staff, scopeEvent(), c.searchFamilies); -router.post('/events/:eventId/families', protect, staff, scopeEvent(), c.createFamilyAtDesk); -router.get('/events/:eventId/families/qr/:token', protect, staff, scopeEvent(), c.familyByQr); -router.get('/events/:eventId/families/:familyId', protect, staff, scopeEvent(), c.getFamily); -router.post('/events/:eventId/families/:familyId/parents', protect, staff, scopeEvent(), c.addParentAtDesk); -router.post('/events/:eventId/families/:familyId/children', protect, staff, scopeEvent(), c.saveChildAtDesk); -router.put('/events/:eventId/families/:familyId/children/:childId', protect, staff, scopeEvent(), c.saveChildAtDesk); -router.post('/events/:eventId/families/:familyId/adults', protect, staff, scopeEvent(), c.addAdultAtDesk); -router.post('/events/:eventId/check-in', protect, staff, scopeEvent(), c.checkIn); -router.post('/events/:eventId/check-out', protect, staff, scopeEvent(), c.checkOut); -router.get('/events/:eventId/code/:code', protect, staff, scopeEvent(), c.lookupCode); -router.post('/events/:eventId/duty', protect, staff, scopeEvent(), c.setDuty); -router.get('/events/:eventId/offline', protect, staff, scopeEvent(), c.offlineSnapshot); -router.post('/events/:eventId/sync', protect, staff, scopeEvent(), c.syncOffline); -router.post('/check-ins/:id/override', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.overrideCheckOut); -router.post('/check-ins/:id/page', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.pageParent); -router.put('/check-ins/:id/room', protect, staff, scopeEvent({ resolve: 'kidsCheckIn' }), c.moveRoom); -router.post('/alerts/:id/resolve', protect, staff, scopeEvent({ resolve: 'kidsAlert' }), c.resolveAlert); - -module.exports = router; diff --git a/apps/events/backend/src/routes/outboundWebhookRoutes.js b/apps/events/backend/src/routes/outboundWebhookRoutes.js deleted file mode 100644 index bc0c87f..0000000 --- a/apps/events/backend/src/routes/outboundWebhookRoutes.js +++ /dev/null @@ -1,17 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { list, create, update, remove, rotateSecret, test, deliveries, resend } = require('../controllers/outboundWebhookController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -// Outbound webhooks (1.48.0): admins only. Payment provider webhooks *into* the site are /api/webhooks/. -router.use(protect, admin); -router.get('/', list); -router.post('/', create); -router.post('/deliveries/:id/resend', resend); -router.put('/:id', update); -router.delete('/:id', remove); -router.post('/:id/rotate-secret', rotateSecret); -router.post('/:id/test', test); -router.get('/:id/deliveries', deliveries); - -module.exports = router; diff --git a/apps/events/backend/src/routes/payfastRoutes.js b/apps/events/backend/src/routes/payfastRoutes.js deleted file mode 100644 index 2b32e3f..0000000 --- a/apps/events/backend/src/routes/payfastRoutes.js +++ /dev/null @@ -1,10 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getConfig, updateConfig, testConnection } = require('../controllers/payfastController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -router.get('/config', protect, admin, getConfig); -router.put('/config', protect, admin, updateConfig); -router.post('/test', protect, admin, testConnection); - -module.exports = router; diff --git a/apps/events/backend/src/routes/paymentRoutes.js b/apps/events/backend/src/routes/paymentRoutes.js deleted file mode 100644 index b7afcf8..0000000 --- a/apps/events/backend/src/routes/paymentRoutes.js +++ /dev/null @@ -1,54 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - createPayment, - getPayments, - getUserPayments, - getPaymentById, - getPaymentsByRegistration, - getPaymentsByEvent, - assignDonationToRegistration, - unassignDonationFromRegistration, - createCheckout, - sendPaymentLink, - createRefund, - getPaymentStats, - sendReceipt, -} = require('../controllers/paymentController'); -const { listPaymentProviders, getPaymentProviderSettings, updatePaymentProviderSettings, getPayPage, choosePayProvider, listOpenCheckouts, checkCheckoutStatus } = require('../controllers/paymentProvidersController'); -const { protect, supervisor, staff, admin} = require('../middleware/authMiddleware'); -const { scopeEvent, scopeBody, scopeList, unscopedOnly } = require('../utils/campusScope'); - -// Campus-scoped staff: payments follow their registration's or event's campus. Door payments for -// church-wide events are allowed; refunds of them aren't (need 'manage'); a payment or donation -// not linked to any event is for admins and unscoped supervisors (orphan 'deny'). -const paymentTarget = scopeBody([['registrationId', 'registration'], ['eventId', 'event']], { orphan: 'deny' }); - -// Protected routes -router.post('/', protect, supervisor, paymentTarget, createPayment); -router.get('/providers', listPaymentProviders); -router.get('/pay/:id', getPayPage); -router.post('/pay/:id', choosePayProvider); -router.get('/checkouts/open', protect, supervisor, unscopedOnly, listOpenCheckouts); -router.post('/checkouts/check', protect, supervisor, unscopedOnly, checkCheckoutStatus); -router.get('/providers/settings', protect, admin, getPaymentProviderSettings); -router.put('/providers/settings', protect, admin, updatePaymentProviderSettings); -router.post('/checkout', protect, createCheckout); -router.post('/checkout/send', protect, supervisor, scopeBody([['registrationId', 'registration']]), sendPaymentLink); -// Older names, kept for existing clients -router.post('/yoco-checkout', protect, createCheckout); -router.post('/yoco-checkout/send', protect, supervisor, scopeBody([['registrationId', 'registration']]), sendPaymentLink); -router.get('/mypayments', protect, getUserPayments); -router.post('/:id/send-receipt', protect, scopeEvent({ resolve: 'payment', ownerOk: true }), sendReceipt); -router.get('/:id', protect, scopeEvent({ resolve: 'payment', ownerOk: true }), getPaymentById); -router.get('/registration/:registrationId', protect, scopeEvent({ resolve: 'registration', from: req => req.params.registrationId, ownerOk: true }), getPaymentsByRegistration); - -// Admin/Staff routes -router.get('/', protect, supervisor, scopeList, getPayments); -router.get('/event/:eventId', protect, staff, scopeEvent(), getPaymentsByEvent); -router.put('/assign-donation', protect, supervisor, scopeBody([['paymentId', 'payment']], { orphan: 'deny' }), scopeBody([['registrationId', 'registration']]), assignDonationToRegistration); -router.post('/unassign-donation', protect, supervisor, scopeBody([['legId', 'payment']], { orphan: 'deny' }), unassignDonationFromRegistration); -router.post('/refund', protect, supervisor, scopeBody([['paymentId', 'payment'], ['registrationId', 'registration']], { need: 'manage', orphan: 'deny' }), createRefund); -router.get('/admin/stats', protect, admin, getPaymentStats); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/privacyRoutes.js b/apps/events/backend/src/routes/privacyRoutes.js deleted file mode 100644 index 44a3789..0000000 --- a/apps/events/backend/src/routes/privacyRoutes.js +++ /dev/null @@ -1,87 +0,0 @@ -const express = require('express'); -const rateLimit = require('express-rate-limit'); -const router = express.Router(); -const { - getMyPrivacy, - updateMyNews, - exportMyData, - createMyRequest, - getUnsubscribe, - postUnsubscribe, - oneClickUnsubscribe, - oneClickRedirect, - listRequests, - completeRequest, - rejectRequest, -} = require('../controllers/privacyController'); -const { - getNotice, - acceptMyNotice, - getNoticeDraft, - saveNoticeDraft, - discardNoticeDraft, - publishNotice, - markBuiltInReviewed, - listOperators, - createOperator, - updateOperator, - deleteOperator, - consentLog, - accessLog, - getReadiness, - getRetention, - saveRetention, - runRetentionNow, - listBreaches, - createBreach, - updateBreach, -} = require('../controllers/privacyAdminController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -// Exports are heavy-ish (every record the person has) — a few per 10 minutes is plenty. -const exportLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false }); - -// The person themselves -router.get('/me', protect, getMyPrivacy); -router.put('/me/news', protect, updateMyNews); -router.get('/me/export', protect, exportLimiter, exportMyData); -router.post('/me/requests', protect, createMyRequest); - -// Unsubscribe links (signed tokens, no login) -router.get('/unsubscribe/:token', getUnsubscribe); -router.post('/unsubscribe/:token', postUnsubscribe); -router.get('/unsubscribe/:token/one-click', oneClickRedirect); -router.post('/unsubscribe/:token/one-click', express.urlencoded({ extended: false }), oneClickUnsubscribe); - -// Admin: data requests inbox -router.get('/requests', protect, admin, listRequests); -router.post('/requests/:id/complete', protect, admin, completeRequest); -router.post('/requests/:id/reject', protect, admin, rejectRequest); - -// Privacy notice: public reading, acceptance, and the admin editor -router.get('/notice', getNotice); -router.post('/me/notice/accept', protect, acceptMyNotice); -router.get('/notice/draft', protect, admin, getNoticeDraft); -router.put('/notice/draft', protect, admin, saveNoticeDraft); -router.delete('/notice/draft', protect, admin, discardNoticeDraft); -router.post('/notice/publish', protect, admin, publishNotice); -router.post('/notice/builtin-reviewed', protect, admin, markBuiltInReviewed); - -// Admin: operator register, consent log, access log -router.get('/operators', protect, admin, listOperators); -router.post('/operators', protect, admin, createOperator); -router.put('/operators/:id', protect, admin, updateOperator); -router.delete('/operators/:id', protect, admin, deleteOperator); -router.get('/consent-log', protect, admin, consentLog); -router.get('/access-log', protect, admin, accessLog); - -// Admin: readiness, retention, breach register -router.get('/readiness', protect, admin, getReadiness); -router.get('/retention', protect, admin, getRetention); -router.put('/retention', protect, admin, saveRetention); -router.post('/retention/run', protect, admin, runRetentionNow); -router.get('/breaches', protect, admin, listBreaches); -router.post('/breaches', protect, admin, createBreach); -router.put('/breaches/:id', protect, admin, updateBreach); - -module.exports = router; diff --git a/apps/events/backend/src/routes/providerTransactionRoutes.js b/apps/events/backend/src/routes/providerTransactionRoutes.js deleted file mode 100644 index e48a643..0000000 --- a/apps/events/backend/src/routes/providerTransactionRoutes.js +++ /dev/null @@ -1,21 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getAllProviderTransactions, getUnreconciledProviderTransactions, reconcileProviderTransaction, ignoreProviderTransaction } = require('../controllers/providerTransactionsController'); -const { protect, supervisor} = require('../middleware/authMiddleware'); -const { unscopedOnly } = require('../utils/campusScope'); - -// Mounted at /api/provider-transactions (and /api/yoco-transactions, the older name). - -// GET all payment provider transactions (admin/supervisor) -router.get('/', protect, supervisor, unscopedOnly, getAllProviderTransactions); - -// GET all unreconciled transactions (admin/supervisor) -router.get('/unreconciled', protect, supervisor, unscopedOnly, getUnreconciledProviderTransactions); - -// POST reconcile a transaction -router.post('/:id/reconcile', protect, supervisor, unscopedOnly, reconcileProviderTransaction); - -// POST ignore a transaction -router.post('/:id/ignore', protect, supervisor, unscopedOnly, ignoreProviderTransaction); - -module.exports = router; diff --git a/apps/events/backend/src/routes/registrationRoutes.js b/apps/events/backend/src/routes/registrationRoutes.js deleted file mode 100644 index a01d20b..0000000 --- a/apps/events/backend/src/routes/registrationRoutes.js +++ /dev/null @@ -1,54 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - createRegistration, - getRegistrations, - getUserRegistrations, - getRegistrationById, - updateRegistrationStatus, - cancelRegistration, - getRegistrationsByEvent, - createManualRegistration, - updateRegistrationOptions, - submitFormResponses, replaceFormResponses, - getFormDraft, saveFormDraft, - sendInvoice, - applyCoupon, removeCoupon, - updateAttendees, sendAttendeeFormLink, -} = require('../controllers/registrationController'); -const { protect, supervisor, staff, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList, scopeBody } = require('../utils/campusScope'); -const { notOnSeasonPass } = require('../utils/seasonPass'); - -// Campus-scoped staff (utils/campusScope.js). Routes open to the registration's owner as well -// as to staff check staff against the registration's event, and let the owner through (ownerOk). - -// Registration - auth optional when event doesn't require it -router.post('/', optionalAuth, createRegistration); -router.get('/myregistrations', protect, getUserRegistrations); -router.put('/:id/options', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), notOnSeasonPass, updateRegistrationOptions); -router.delete('/:id', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), cancelRegistration); -router.post('/:id/send-invoice', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), sendInvoice); -router.post('/:id/coupon', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), notOnSeasonPass, applyCoupon); -router.delete('/:id/coupon', protect, staff, scopeEvent({ resolve: 'registration' }), removeCoupon); -router.put('/:id/attendees', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), updateAttendees); -router.post('/:id/attendees/:attendeeId/send-form-link', protect, scopeEvent({ resolve: 'registration', ownerOk: true }), sendAttendeeFormLink); - -// Registration detail + forms — optionalAuth so guests can access with just the registrationId -router.get('/:id', optionalAuth, scopeEvent({ resolve: 'registration', ownerOk: true }), getRegistrationById); -router.get('/:id/forms/draft', optionalAuth, scopeEvent({ resolve: 'registration', ownerOk: true }), getFormDraft); -router.put('/:id/forms/draft', optionalAuth, scopeEvent({ resolve: 'registration', ownerOk: true }), saveFormDraft); -router.post('/:id/forms/responses', optionalAuth, scopeEvent({ resolve: 'registration', ownerOk: true }), submitFormResponses); -router.put('/:id/forms/responses', protect, supervisor, scopeEvent({ resolve: 'registration' }), replaceFormResponses); - -// Admin/Staff routes -router.get('/', protect, staff, scopeList, getRegistrations); -router.put('/:id', protect, staff, scopeEvent({ resolve: 'registration' }), updateRegistrationStatus); -router.get('/event/:eventId', protect, staff, scopeEvent(), getRegistrationsByEvent); -router.post('/manual', protect, supervisor, scopeEvent({ from: req => req.body?.eventId }), createManualRegistration); -// Bulk actions (1.49.1): every ticked registration must be one this person may manage. -router.post('/bulk', protect, supervisor, scopeBody([['registrationIds', 'registration']], { orphan: 'deny' }), async (req, res) => { - try { res.json(await require('../utils/bulkRegistrations').runBulk(req, req.body || {})); } catch (e) { res.status(e.statusCode || 400).json({ message: e.message }); } -}); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/reportRoutes.js b/apps/events/backend/src/routes/reportRoutes.js deleted file mode 100644 index 5c76bfc..0000000 --- a/apps/events/backend/src/routes/reportRoutes.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { generatePdf, generateExcel, emailPdf, whatsappPdf } = require('../controllers/reportController'); -const { protect } = require('../middleware/authMiddleware'); - -// Generate and download PDF -router.post('/pdf', protect, generatePdf); - -// Generate and download styled Excel (.xlsx) -router.post('/excel', protect, generateExcel); - -// Email PDF to current user -router.post('/email', protect, emailPdf); - -// Send PDF to current user's own WhatsApp -router.post('/whatsapp', protect, whatsappPdf); - -module.exports = router; diff --git a/apps/events/backend/src/routes/scanLockRoutes.js b/apps/events/backend/src/routes/scanLockRoutes.js deleted file mode 100644 index ce569a4..0000000 --- a/apps/events/backend/src/routes/scanLockRoutes.js +++ /dev/null @@ -1,16 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listLocks, createLock, getSnapshot, syncLock, releaseLock, forceRelease, listReports, reviewReport } = require('../controllers/scanLockController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -router.get('/', protect, staff, scopeEvent({ from: req => req.query.eventId }), listLocks); -router.post('/', protect, staff, scopeEvent({ from: req => req.body?.eventId }), createLock); -router.get('/reports', protect, supervisor, scopeEvent({ from: req => req.query.eventId }), listReports); -router.post('/reports/:id/review', protect, supervisor, scopeEvent({ resolve: 'syncReport' }), reviewReport); -router.get('/:id/snapshot', protect, staff, scopeEvent({ resolve: 'scanLock' }), getSnapshot); -router.post('/:id/sync', protect, staff, scopeEvent({ resolve: 'scanLock' }), syncLock); -router.post('/:id/force-release', protect, supervisor, scopeEvent({ resolve: 'scanLock' }), forceRelease); -router.delete('/:id', protect, staff, scopeEvent({ resolve: 'scanLock' }), releaseLock); - -module.exports = router; diff --git a/apps/events/backend/src/routes/scheduledEmailRoutes.js b/apps/events/backend/src/routes/scheduledEmailRoutes.js deleted file mode 100644 index 7976dc0..0000000 --- a/apps/events/backend/src/routes/scheduledEmailRoutes.js +++ /dev/null @@ -1,12 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listScheduledEmails, updateScheduledEmail, deleteScheduledEmail } = require('../controllers/scheduledEmailsController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeList } = require('../utils/campusScope'); - -// All routes require supervisor (or admin via middleware logic) access -router.get('/', protect, supervisor, scopeList, listScheduledEmails); -router.patch('/:id', protect, supervisor, scopeList, updateScheduledEmail); -router.delete('/:id', protect, supervisor, scopeList, deleteScheduledEmail); - -module.exports = router; diff --git a/apps/events/backend/src/routes/seasonPassRoutes.js b/apps/events/backend/src/routes/seasonPassRoutes.js deleted file mode 100644 index deab1f7..0000000 --- a/apps/events/backend/src/routes/seasonPassRoutes.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listPasses, createPass, updatePass, deletePass, buy, payPurchase, myPurchases } = require('../controllers/seasonPassController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { campusIndependent } = require('../utils/campusScope'); - -const SPANS = campusIndependent('a pass can span campuses; each event on it is checked against the person\'s campuses in the controller'); - -router.get('/mine', protect, myPurchases); -router.post('/:id/buy', protect, buy); -router.post('/purchases/:id/checkout', protect, payPurchase); - -router.get('/', protect, supervisor, SPANS, listPasses); -router.post('/', protect, supervisor, SPANS, createPass); -router.put('/:id', protect, supervisor, SPANS, updatePass); -router.delete('/:id', protect, supervisor, SPANS, deletePass); - -module.exports = router; diff --git a/apps/events/backend/src/routes/sectionRoutes.js b/apps/events/backend/src/routes/sectionRoutes.js deleted file mode 100644 index 9498a19..0000000 --- a/apps/events/backend/src/routes/sectionRoutes.js +++ /dev/null @@ -1,17 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - getSections, - createSection, - deleteSection, - updateSection -} = require('../controllers/sectionController'); -const { protect, admin, supervisor, staff } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -router.get('/', protect, staff, scopeList, getSections); -router.post('/', protect, supervisor, scopeEvent({ from: req => req.body?.eventId, need: 'manage' }), createSection); -router.delete('/:id', protect, admin, deleteSection); -router.put('/:id', protect, supervisor, scopeEvent({ resolve: 'section', need: 'manage' }), updateSection); - -module.exports = router; diff --git a/apps/events/backend/src/routes/seriesRoutes.js b/apps/events/backend/src/routes/seriesRoutes.js deleted file mode 100644 index 48d0f3a..0000000 --- a/apps/events/backend/src/routes/seriesRoutes.js +++ /dev/null @@ -1,21 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { listSeries, createSeries, updateSeries, deleteSeries, getSeriesBySlug, followSeries, unfollowSeries, compare } = require('../controllers/seriesController'); -const { protect, admin, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { campusIndependent, scopeList } = require('../utils/campusScope'); - -const SPANS = campusIndependent('a series spans campuses; adding an event to one is checked on the event'); - -router.get('/by-slug/:slug', optionalAuth, getSeriesBySlug); -router.post('/:id/follow', protect, followSeries); -router.delete('/:id/follow', protect, unfollowSeries); - -// The list filters each series' events by the person's campuses itself. -router.get('/', protect, supervisor, SPANS, listSeries); -router.post('/', protect, supervisor, SPANS, createSeries); -router.put('/:id', protect, supervisor, SPANS, updateSeries); -router.delete('/:id', protect, admin, deleteSeries); -// Year-on-year report: only the events the person may see (filtered in the controller). -router.get('/:id/compare', protect, supervisor, scopeList, compare); - -module.exports = router; diff --git a/apps/events/backend/src/routes/settingsRoutes.js b/apps/events/backend/src/routes/settingsRoutes.js deleted file mode 100644 index 10b2ce9..0000000 --- a/apps/events/backend/src/routes/settingsRoutes.js +++ /dev/null @@ -1,12 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getSettings, getAllSettings, updateSettings, needsSetup, testSmtp } = require('../controllers/settingsController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -router.get('/needs-setup', needsSetup); -router.get('/all', protect, admin, getAllSettings); -router.get('/', getSettings); -router.put('/', protect, admin, updateSettings); -router.post('/test-smtp', protect, admin, testSmtp); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/setupRoutes.js b/apps/events/backend/src/routes/setupRoutes.js deleted file mode 100644 index b58bb53..0000000 --- a/apps/events/backend/src/routes/setupRoutes.js +++ /dev/null @@ -1,12 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { setupRegister, runSetup } = require('../controllers/settingsController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -// Step 1 of setup: create the admin account, returns a JWT token -router.post('/register', setupRegister); - -// Step 2 of setup: finalize settings (requires the token from /register) -router.post('/', protect, admin, runSetup); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/sponsorshipRoutes.js b/apps/events/backend/src/routes/sponsorshipRoutes.js deleted file mode 100644 index dfdaf26..0000000 --- a/apps/events/backend/src/routes/sponsorshipRoutes.js +++ /dev/null @@ -1,11 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getEventSponsorship, createSponsorCheckout, getPool } = require('../controllers/sponsorshipController'); -const { protect, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -router.get('/event/:eventId', getEventSponsorship); -router.get('/event/:eventId/pool', protect, supervisor, scopeEvent(), getPool); -router.post('/checkout', optionalAuth, createSponsorCheckout); - -module.exports = router; diff --git a/apps/events/backend/src/routes/statsRoutes.js b/apps/events/backend/src/routes/statsRoutes.js deleted file mode 100644 index c23c001..0000000 --- a/apps/events/backend/src/routes/statsRoutes.js +++ /dev/null @@ -1,18 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getStaffDashboardStats, getSupervisorDashboardStats, getAdminDashboardStats, getOverviewStats } = require('../controllers/statsController'); -const { protect, staff, supervisor, admin } = require('../middleware/authMiddleware'); -const { scopeList } = require('../utils/campusScope'); - -// One endpoint per dashboard — each returns exactly what that dashboard renders in a -// single response instead of the dashboard making several separate calls (and, previously, -// pulling full payments/events lists just to reduce them to a couple of numbers). -router.get('/staff', protect, staff, scopeList, getStaffDashboardStats); -router.get('/supervisor', protect, supervisor, scopeList, getSupervisorDashboardStats); -router.get('/admin', protect, admin, getAdminDashboardStats); - -// Month-over-month KPIs + trend + top events, shared by the Admin and Supervisor dashboards. -// Staff never sees financial data, so this has no staff-accessible route. -router.get('/overview', protect, supervisor, scopeList, getOverviewStats); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/ticketRoutes.js b/apps/events/backend/src/routes/ticketRoutes.js deleted file mode 100644 index 92f02a9..0000000 --- a/apps/events/backend/src/routes/ticketRoutes.js +++ /dev/null @@ -1,55 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - generateTickets, - getTickets, - getUserTickets, - getTicketById, - getTicketByQrCode, - getScanPreview, - scanTicket, - getTicketsByEvent, - markTicketsAsEmailSent, - emailTickets, - sendTicketsTo, - getRecentScans, - getScanStats, - transferTicketHandler, - cancelTransferHandler, - getTransferOffer, - acceptTransferOffer, - declineTransferOffer, - getTicketTransfers -} = require('../controllers/ticketController'); -const { protect, admin, supervisor, staff } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeBody, scopeList } = require('../utils/campusScope'); - -// Campus-scoped staff (utils/campusScope.js). The scanner names the campus of another campus's ticket. - -// Protected routes -router.get('/mytickets', protect, getUserTickets); -router.get('/:id', protect, scopeEvent({ resolve: 'ticket', ownerOk: true }), getTicketById); -router.post('/email', protect, emailTickets); -router.post('/:id/transfer', protect, scopeEvent({ resolve: 'ticket', ownerOk: true }), transferTicketHandler); -router.delete('/:id/transfer', protect, scopeEvent({ resolve: 'ticket', ownerOk: true }), cancelTransferHandler); -// Transfer links (public: the person the ticket is offered to) -router.get('/transfer-offer/:token', getTransferOffer); -router.post('/transfer-offer/:token/accept', acceptTransferOffer); -router.post('/transfer-offer/:token/decline', declineTransferOffer); -router.get('/:id/transfers', protect, scopeEvent({ resolve: 'ticket', ownerOk: true }), getTicketTransfers); - -// Staff routes -router.post('/send-to', protect, staff, scopeBody([['registrationId', 'registration'], ['ticketIds', 'ticket']]), sendTicketsTo); -router.get('/scan-preview/:qrCode', protect, staff, scopeEvent({ resolve: 'ticketQr', from: req => req.params.qrCode, nameCampus: true }), getScanPreview); -router.get('/qr/:qrCode', protect, staff, scopeEvent({ resolve: 'ticketQr', from: req => req.params.qrCode, nameCampus: true }), getTicketByQrCode); -router.post('/scan/:qrCode', protect, staff, scopeEvent({ resolve: 'ticketQr', from: req => req.params.qrCode, nameCampus: true }), scanTicket); -router.get('/event/:eventId', protect, staff, scopeEvent(), getTicketsByEvent); -router.get('/scans/recent', protect, staff, scopeList, getRecentScans); -router.get('/scans/stats', protect, staff, scopeList, getScanStats); - -// Admin routes -router.post('/generate', protect, supervisor, scopeBody([['registrationId', 'registration']]), generateTickets); -router.get('/', protect, supervisor, scopeList, getTickets); -router.put('/email-sent', protect, admin, markTicketsAsEmailSent); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/uploadRoutes.js b/apps/events/backend/src/routes/uploadRoutes.js deleted file mode 100644 index 3034e53..0000000 --- a/apps/events/backend/src/routes/uploadRoutes.js +++ /dev/null @@ -1,53 +0,0 @@ -const express = require('express'); -const router = express.Router(); - -const { upload, uploadEventImage, uploadLogo, uploadLogoImage, uploadFavicon, uploadFaviconImage } = require('../controllers/uploadController'); -const { protect, supervisor, admin } = require('../middleware/authMiddleware'); -const { campusIndependent } = require('../utils/campusScope'); -const prisma = require('../config/db'); - -// @route POST /api/uploads/event-image -// @desc Upload an image for an event -// @access Private (Supervisor+ recommended) -router.post('/event-image', protect, supervisor, campusIndependent('stores an image file; the event it goes on is checked when the event is saved'), (req, res, next) => { - upload.single('image')(req, res, (err) => { - if (err) { - req.multerError = err; - } - next(); - }); -}, uploadEventImage); - -// Shared access rule for branding assets (logo, favicon): admin, OR allowed -// during first-time setup (no users yet). -async function brandingAssetAccess(req, res, next) { - try { - const count = await prisma.user.count(); - if (count === 0) return next(); // first-time setup - return protect(req, res, () => admin(req, res, next)); - } catch { - return protect(req, res, () => admin(req, res, next)); - } -} - -// @route POST /api/uploads/logo -// @desc Upload site logo — admin, OR allowed during first-time setup (no users yet) -// @access Admin or setup -router.post('/logo', brandingAssetAccess, (req, res, next) => { - uploadLogo.single('image')(req, res, (err) => { - if (err) req.multerError = err; - next(); - }); -}, uploadLogoImage); - -// @route POST /api/uploads/favicon -// @desc Upload site favicon — admin, OR allowed during first-time setup (no users yet) -// @access Admin or setup -router.post('/favicon', brandingAssetAccess, (req, res, next) => { - uploadFavicon.single('image')(req, res, (err) => { - if (err) req.multerError = err; - next(); - }); -}, uploadFaviconImage); - -module.exports = router; diff --git a/apps/events/backend/src/routes/userRoutes.js b/apps/events/backend/src/routes/userRoutes.js deleted file mode 100644 index c5f037a..0000000 --- a/apps/events/backend/src/routes/userRoutes.js +++ /dev/null @@ -1,67 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - registerUser, - loginUser, - verifyLoginTwoFactor, - resendLoginTwoFactor, - startEnableTwoFactor, - confirmEnableTwoFactor, - disableTwoFactor, - verifyPassword, - getUserProfile, - updateUserProfile, - getUsers, - checkUserExists, - getUserById, - updateUser, - deleteUser, - anonymizeUser, - requestPasswordReset, - resetPassword, - activateAccount, - revokeMySession, - adminRevokeUserSessions, - closeAccount, - getMyActivity, -} = require('../controllers/userController'); -const { protect, admin, supervisor, loginLimiter} = require('../middleware/authMiddleware'); -const { campusIndependent } = require('../utils/campusScope'); - -// Public routes -router.post('/', registerUser); -router.post('/login', loginLimiter, loginUser); -router.post('/login/2fa', loginLimiter, verifyLoginTwoFactor); -router.post('/login/2fa/resend', loginLimiter, resendLoginTwoFactor); -router.post('/forgot', loginLimiter, requestPasswordReset); -router.post('/reset', resetPassword); -router.post('/activate', activateAccount); - -// Protected routes -router.route('/profile') - .get(protect, getUserProfile) - .put(protect, updateUserProfile); - -router.post('/revoke-sessions', protect, revokeMySession); -router.post('/close-account', protect, closeAccount); -router.get('/activity', protect, getMyActivity); -router.post('/verify-password', protect, loginLimiter, verifyPassword); -router.post('/2fa/enable', protect, loginLimiter, startEnableTwoFactor); -router.post('/2fa/confirm', protect, loginLimiter, confirmEnableTwoFactor); -router.post('/2fa/disable', protect, loginLimiter, disableTwoFactor); - -// Admin routes -router.route('/') - .get(protect, supervisor, campusIndependent('accounts are shared across campuses'), getUsers); - -router.get('/check-exists', protect, supervisor, campusIndependent('accounts are shared across campuses'), checkUserExists); - -router.route('/:id') - .get(protect, admin, getUserById) - .put(protect, admin, updateUser) - .delete(protect, admin, deleteUser); - -router.post('/:id/revoke-sessions', protect, admin, adminRevokeUserSessions); -router.post('/:id/anonymize', protect, admin, anonymizeUser); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/volunteerRoutes.js b/apps/events/backend/src/routes/volunteerRoutes.js deleted file mode 100644 index fc66a09..0000000 --- a/apps/events/backend/src/routes/volunteerRoutes.js +++ /dev/null @@ -1,33 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const c = require('../controllers/volunteerController'); -const { protect, staff, supervisor } = require('../middleware/authMiddleware'); -const { scopeEvent, scopeList } = require('../utils/campusScope'); - -// My account → Serving (anyone with an account can volunteer; only their own slots) -router.get('/me', protect, c.getMine); -router.get('/events/:eventId', protect, c.getEventRoles); -router.post('/roles/:id/sign-up', protect, c.signUp); -router.delete('/slots/:id', protect, c.withdraw); -router.post('/slots/:id/swap', protect, c.requestSwap); -router.delete('/swaps/:id', protect, c.cancelSwap); -router.post('/swaps/:id/accept', protect, c.acceptSwap); -router.post('/check-in', protect, c.checkIn); - -// The roster on the day (staff) -router.get('/manage/events', protect, staff, scopeList, c.listEvents); -router.get('/manage/events/:eventId', protect, staff, scopeEvent(), c.getRoster); -router.get('/manage/events/:eventId/qr', protect, staff, scopeEvent(), c.getQr); -router.post('/manage/slots/:id/check-in', protect, staff, scopeEvent({ resolve: 'volunteerSlot' }), c.checkInManual); - -// Roles, people, settings and reports (supervisors) -router.get('/manage/events/:eventId/settings', protect, supervisor, scopeEvent(), c.getSettings); -router.put('/manage/events/:eventId/settings', protect, supervisor, scopeEvent({ need: 'manage' }), c.saveSettings); -router.post('/manage/events/:eventId/roles', protect, supervisor, scopeEvent({ need: 'manage' }), c.createRole); -router.put('/manage/roles/:id', protect, supervisor, scopeEvent({ resolve: 'servingRole', need: 'manage' }), c.updateRole); -router.delete('/manage/roles/:id', protect, supervisor, scopeEvent({ resolve: 'servingRole', need: 'manage' }), c.deleteRole); -router.post('/manage/roles/:id/assign', protect, supervisor, scopeEvent({ resolve: 'servingRole' }), c.assign); -router.delete('/manage/slots/:id', protect, supervisor, scopeEvent({ resolve: 'volunteerSlot' }), c.remove); -router.get('/manage/hours', protect, supervisor, scopeList, c.hours); - -module.exports = router; diff --git a/apps/events/backend/src/routes/waitlistRoutes.js b/apps/events/backend/src/routes/waitlistRoutes.js deleted file mode 100644 index 5e4c183..0000000 --- a/apps/events/backend/src/routes/waitlistRoutes.js +++ /dev/null @@ -1,20 +0,0 @@ -const express = require('express'); -const rateLimit = require('express-rate-limit'); -const router = express.Router(); -const { joinWaitlist, myWaitlist, leaveWaitlist, claimInfo, eventWaitlist, offerManually, moveEntry, removeEntry } = require('../controllers/waitlistController'); -const { protect, staff, supervisor, optionalAuth } = require('../middleware/authMiddleware'); -const { scopeEvent } = require('../utils/campusScope'); - -// Claim links are credentials, so keep guessing slow. -const claimLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, message: { message: 'Too many attempts. Please try again in a minute.' } }); - -router.post('/', optionalAuth, joinWaitlist); -router.get('/mine', protect, myWaitlist); -router.get('/claim/:token', claimLimiter, claimInfo); -router.get('/events/:eventId', protect, staff, scopeEvent(), eventWaitlist); -router.post('/:id/offer', protect, supervisor, scopeEvent({ resolve: 'waitlistEntry' }), offerManually); -router.post('/:id/move', protect, supervisor, scopeEvent({ resolve: 'waitlistEntry' }), moveEntry); -router.post('/:id/remove', protect, supervisor, scopeEvent({ resolve: 'waitlistEntry' }), removeEntry); -router.delete('/:id', protect, leaveWaitlist); - -module.exports = router; diff --git a/apps/events/backend/src/routes/whatsappBroadcastRoutes.js b/apps/events/backend/src/routes/whatsappBroadcastRoutes.js deleted file mode 100644 index 29d1a40..0000000 --- a/apps/events/backend/src/routes/whatsappBroadcastRoutes.js +++ /dev/null @@ -1,11 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { previewWhatsAppBroadcast, sendWhatsAppBroadcast, scheduleWhatsAppBroadcast } = require('../controllers/whatsappBroadcastController'); -const { protect, supervisor } = require('../middleware/authMiddleware'); -const { scopeBroadcast } = require('../utils/campusScope'); - -router.post('/preview', protect, supervisor, scopeBroadcast({ freeformField: 'phones' }), previewWhatsAppBroadcast); -router.post('/send', protect, supervisor, scopeBroadcast({ freeformField: 'phones' }), sendWhatsAppBroadcast); -router.post('/schedule', protect, supervisor, scopeBroadcast({ freeformField: 'phones' }), scheduleWhatsAppBroadcast); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/whatsappRoutes.js b/apps/events/backend/src/routes/whatsappRoutes.js deleted file mode 100644 index 47bee9a..0000000 --- a/apps/events/backend/src/routes/whatsappRoutes.js +++ /dev/null @@ -1,37 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { - getConfigHandler, - saveConfigHandler, - createInstanceHandler, - deleteInstanceHandler, - getStatusHandler, - getQrHandler, - requestCodeHandler, - logoutHandler, - startHandler, - restartHandler, - handleWebhook, -} = require('../controllers/whatsappController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -// Public webhook (called by WAWP servers) -router.post('/webhook', handleWebhook); - -// Admin-only: credentials config -router.get( '/config', protect, admin, getConfigHandler); -router.post('/config', protect, admin, saveConfigHandler); - -// Admin-only: instance lifecycle -router.post('/create-instance', protect, admin, createInstanceHandler); -router.post('/delete-instance', protect, admin, deleteInstanceHandler); - -// Admin-only: session management -router.get( '/status', protect, admin, getStatusHandler); -router.get( '/qr', protect, admin, getQrHandler); -router.post('/request-code', protect, admin, requestCodeHandler); -router.post('/logout', protect, admin, logoutHandler); -router.post('/start', protect, admin, startHandler); -router.post('/restart', protect, admin, restartHandler); - -module.exports = router; \ No newline at end of file diff --git a/apps/events/backend/src/routes/yocoRoutes.js b/apps/events/backend/src/routes/yocoRoutes.js deleted file mode 100644 index 1f37619..0000000 --- a/apps/events/backend/src/routes/yocoRoutes.js +++ /dev/null @@ -1,12 +0,0 @@ -const express = require('express'); -const router = express.Router(); -const { getConfig, updateConfig, getWebhooks, createWebhook, removeWebhook } = require('../controllers/yocoController'); -const { protect, admin } = require('../middleware/authMiddleware'); - -router.get('/config', protect, admin, getConfig); -router.put('/config', protect, admin, updateConfig); -router.get('/webhooks', protect, admin, getWebhooks); -router.post('/webhooks', protect, admin, createWebhook); -router.delete('/webhooks/:id', protect, admin, removeWebhook); - -module.exports = router; diff --git a/apps/events/backend/src/services/auth.ts b/apps/events/backend/src/services/auth.ts index 56ab378..197e0d4 100644 --- a/apps/events/backend/src/services/auth.ts +++ b/apps/events/backend/src/services/auth.ts @@ -12,6 +12,7 @@ const auth = require('../config/auth') as { generateToken(id: string, role: string, tokenVersion: number): string; hashPassword(pw: string): Promise; comparePassword(pw: string, hash: string): Promise; + needsRehash(hash: string): boolean; }; const twoFactor = require('../utils/twoFactor') as { createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>; @@ -249,7 +250,9 @@ export async function logIn(input: { identifier: string; password: string; devic fail(401, 'Invalid email or password', undefined, { v1Status: 400 }); } - const updated = await prisma.user.update({ where: { id: user.id }, data: { failedAttempts: 0, lockUntil: null }, select: LOGIN_USER_SELECT }); + // 2.0: a password saved with bcrypt (or weaker Argon2 settings) is re-hashed now we have it. + const rehashed = auth.needsRehash(user.password) ? { password: await auth.hashPassword(input.password) } : {}; + const updated = await prisma.user.update({ where: { id: user.id }, data: { failedAttempts: 0, lockUntil: null, ...rehashed }, select: LOGIN_USER_SELECT }); // Two-factor: the password alone isn't enough unless this browser was remembered earlier. if (updated.twoFactorEnabled && !(await twoFactor.isTrustedDevice(updated.id, input.deviceToken))) { diff --git a/apps/events/backend/src/utils/accessLog.js b/apps/events/backend/src/utils/accessLog.js index c0dbad1..b760322 100644 --- a/apps/events/backend/src/utils/accessLog.js +++ b/apps/events/backend/src/utils/accessLog.js @@ -18,6 +18,7 @@ const ACCESS_ACTIONS = { kids_rooms: 'Kids check-in desk or room opened', kids_offline: 'Kids check-in list downloaded for offline use', volunteer_roster: 'Volunteer roster opened', + ai_feedback: 'Feedback comments summarised by the AI helper', }; /** diff --git a/apps/events/backend/src/utils/impersonation.js b/apps/events/backend/src/utils/impersonation.js index 6c9aae0..9950bd3 100644 --- a/apps/events/backend/src/utils/impersonation.js +++ b/apps/events/backend/src/utils/impersonation.js @@ -18,7 +18,7 @@ const prisma = require('../config/db'); const MAX_MINUTES = 30; const SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']; // v1 and v2 paths for ending a viewing-as session and logging what was viewed. -const ALLOWED_WRITES = ['/api/admin/impersonate/end', '/api/admin/impersonate/log', '/api/v2/me/impersonation/end', '/api/v2/me/impersonation/log']; +const ALLOWED_WRITES = ['/api/v2/me/impersonation/end', '/api/v2/me/impersonation/log']; /** The `imp` claim of a bearer token, or null (no token, invalid token, or not impersonating). */ function impersonationClaim(req) { diff --git a/apps/events/backend/src/utils/privacy.js b/apps/events/backend/src/utils/privacy.js index fe19a3b..204e3c8 100644 --- a/apps/events/backend/src/utils/privacy.js +++ b/apps/events/backend/src/utils/privacy.js @@ -469,6 +469,8 @@ async function anonymiseUser(userId, db = prisma) { await tx.webhookDelivery.deleteMany({ where: { userId } }); // Their saved list filters (can hold search text, such as names). await tx.savedFilter.deleteMany({ where: { userId } }); + // AI helper calls (2.0): kept for the site's monthly totals, no longer linked to them. + await tx.aiCall.updateMany({ where: { userId }, data: { userId: null } }); return { attendees: attendeeIds.length, formAnswers: answers.count, providerRecords: txns.length + checkouts.length, familyDeleted, shiftsGivenUp }; }); diff --git a/apps/events/backend/src/utils/privacyNotice.js b/apps/events/backend/src/utils/privacyNotice.js index 155e01e..c22dc20 100644 --- a/apps/events/backend/src/utils/privacyNotice.js +++ b/apps/events/backend/src/utils/privacyNotice.js @@ -96,6 +96,7 @@ const DEFAULT_SECTIONS = [ '• Tell you when a new event in a series you follow comes out. This counts as news, so it\'s only sent if you get news and announcements.', '• Offer places from a waitlist, arrange rooms and groups, and ask for parental consent on youth events.', '• Send you an optional feedback form after an event, with one reminder.', + '• If we use the AI helpers: our staff can ask an AI service to help draft event details and messages, improve text, and summarise reports and event feedback. A person checks every suggestion before anything is saved or sent. Only what a task needs is sent — never your name, contact details, or medical or children\'s information — and feedback comments are sent without who wrote them (see section 9).', '• Manage user accounts and event attendance records, and give support when you ask for help.', '• Improve our events and website (using anonymous statistics, and only with your permission).', '• Comply with legal obligations.', @@ -166,6 +167,7 @@ const DEFAULT_SECTIONS = [ 'We do not sell or rent your personal information. Outside our organisation, it is shared only with these service providers ("operators"), each only for its purpose:', '{operators}', '• Anyone we are required to share it with under South African law.', + 'If we use the AI helpers, requests go through our software provider\'s service to Anthropic (the Claude AI service) in the United States, which is listed above. Our software provider does not keep what was sent. Anthropic handles it under its commercial terms, which do not allow it to be used to train AI; it may be kept for a short time for safety checks. Because this is outside South Africa, it is only done under the protections POPIA requires for such transfers.', 'If we connect another system — for example our church-management software — through a webhook, it is listed above with what it receives. It gets only the updates we chose (such as new registrations, payments and check-ins), and never children\'s details from kids check-in.', 'Within our organisation, people see only what they need:', "• Door staff see a ticket's holder name, ticket type and check-in status when scanning.", @@ -279,6 +281,14 @@ const BUILT_IN_UPDATES = [ ], sections: ['summary', 'information', 'use', 'whatsapp', 'retention', 'sharing', 'cookies', 'changes'], }, + { + revision: '2.0.0', + summary: [ + 'AI helpers: staff can ask an AI service (Anthropic\'s Claude, through the software provider) to draft events and messages, improve text and summarise reports and feedback; a person checks every suggestion, and no names, contact details, medical or children\'s information are sent.', + 'Where AI requests go (the United States), that the provider doesn\'t keep them, and that they aren\'t used to train AI.', + ], + sections: ['use', 'sharing'], + }, ]; const BUILT_IN_REVISION = BUILT_IN_UPDATES[BUILT_IN_UPDATES.length - 1].revision; const REVIEWED_KEY = 'privacy_notice_builtin_reviewed'; diff --git a/apps/events/backend/src/v2/deprecation.ts b/apps/events/backend/src/v2/deprecation.ts deleted file mode 100644 index 45c1664..0000000 --- a/apps/events/backend/src/v2/deprecation.ts +++ /dev/null @@ -1,380 +0,0 @@ -import type { RequestHandler } from 'express'; - -/** - * v1 endpoints that have a v2 replacement say so (1.51.3): a `Deprecation` header (RFC 9745, - * the date v2 covered them) and `Link: <…>; rel="successor-version"` pointing at the v2 - * endpoint. v1 keeps working until 2.0; endpoints without a v2 version get no header yet. - */ - -// When these v1 endpoints got their v2 replacement (1.51.3's release day). -const DEPRECATED_AT = Math.floor(Date.UTC(2026, 9, 29) / 1000); - -type Successor = { method: string; v1: RegExp; v2: (m: RegExpMatchArray) => string }; - -const SUCCESSORS: Successor[] = [ - { method: 'GET', v1: /^\/api\/events\/?$/, v2: () => '/api/v2/events' }, - // v1's event detail is the full record (v2's /events/{id} is the public summary). - { method: 'GET', v1: /^\/api\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/full` }, - // 1.51.8: the rest of the events area - { method: 'GET', v1: /^\/api\/events\/([^/]+)\/ics$/, v2: m => `/api/v2/events/${m[1]}/calendar.ics` }, - { method: 'GET', v1: /^\/api\/events\/by-alias\/([^/]+)$/, v2: m => `/api/v2/events/by-alias/${m[1]}` }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/options$/, v2: m => `/api/v2/events/${m[1]}/ticket-options` }, - { method: 'PUT', v1: /^\/api\/events\/options\/([^/]+)$/, v2: m => `/api/v2/ticket-options/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/events\/options\/([^/]+)$/, v2: m => `/api/v2/ticket-options/${m[1]}` }, - { method: 'POST', v1: /^\/api\/events\/options\/([^/]+)\/variants$/, v2: m => `/api/v2/ticket-options/${m[1]}/variants` }, - { method: 'PUT', v1: /^\/api\/events\/variants\/([^/]+)$/, v2: m => `/api/v2/variants/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/events\/variants\/([^/]+)$/, v2: m => `/api/v2/variants/${m[1]}` }, - { method: 'GET', v1: /^\/api\/events\/attachments\/status$/, v2: () => '/api/v2/attachments/status' }, - { method: 'POST', v1: /^\/api\/events\/attachments\/sync$/, v2: () => '/api/v2/attachments/sync' }, - { method: 'GET', v1: /^\/api\/events\/([^/]+)\/attachments$/, v2: m => `/api/v2/events/${m[1]}/attachments` }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/attachments$/, v2: m => `/api/v2/events/${m[1]}/attachments` }, - { method: 'DELETE', v1: /^\/api\/events\/([^/]+)\/attachments\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/attachments/${m[2]}` }, - { method: 'GET', v1: /^\/api\/sections\/?$/, v2: () => '/api/v2/sections' }, - { method: 'POST', v1: /^\/api\/sections\/?$/, v2: () => '/api/v2/sections' }, - { method: 'PUT', v1: /^\/api\/sections\/([^/]+)$/, v2: m => `/api/v2/sections/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/sections\/([^/]+)$/, v2: m => `/api/v2/sections/${m[1]}` }, - { method: 'GET', v1: /^\/api\/events\/([^/]+)\/costs$/, v2: m => `/api/v2/events/${m[1]}/costs` }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/costs$/, v2: m => `/api/v2/events/${m[1]}/costs` }, - { method: 'PUT', v1: /^\/api\/costs\/([^/]+)$/, v2: m => `/api/v2/costs/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/costs\/([^/]+)$/, v2: m => `/api/v2/costs/${m[1]}` }, - { method: 'POST', v1: /^\/api\/uploads\/(event-image|logo|favicon)$/, v2: m => `/api/v2/uploads/${m[1]}` }, - // 1.51.7: setting events up - { method: 'GET', v1: /^\/api\/events\/all$/, v2: () => '/api/v2/events/manage' }, - { method: 'POST', v1: /^\/api\/events\/?$/, v2: () => '/api/v2/events' }, - { method: 'PUT', v1: /^\/api\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}` }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/copy-from$/, v2: m => `/api/v2/events/${m[1]}/copy-from` }, - { method: 'GET', v1: /^\/api\/events\/([^/]+)\/notify-recipients$/, v2: m => `/api/v2/events/${m[1]}/notify-recipients` }, - { method: 'PUT', v1: /^\/api\/events\/([^/]+)\/notify-recipients$/, v2: m => `/api/v2/events/${m[1]}/notify-recipients` }, - // 1.51.16: incoming webhooks and links in sent messages (v1 still answered by the same code) - { method: 'POST', v1: /^\/api\/webhooks\/(yoco|payfast|whatsapp)$/, v2: m => `/api/v2/webhooks/${m[1]}` }, - { method: 'POST', v1: /^\/api\/whatsapp\/webhook$/, v2: () => '/api/v2/webhooks/whatsapp' }, - { method: 'POST', v1: /^\/api\/privacy\/unsubscribe\/([^/]+)\/one-click$/, v2: m => `/api/v2/unsubscribe/${m[1]}/one-click` }, - // 1.51.15: privacy and admin - { method: 'GET', v1: /^\/api\/privacy\/me$/, v2: () => '/api/v2/me/privacy' }, - { method: 'PUT', v1: /^\/api\/privacy\/me\/news$/, v2: () => '/api/v2/me/privacy/news' }, - { method: 'GET', v1: /^\/api\/privacy\/me\/export$/, v2: () => '/api/v2/me/privacy/export' }, - { method: 'POST', v1: /^\/api\/privacy\/me\/requests$/, v2: () => '/api/v2/me/privacy/requests' }, - { method: 'POST', v1: /^\/api\/privacy\/me\/notice\/accept$/, v2: () => '/api/v2/me/privacy/notice/accept' }, - { method: 'GET', v1: /^\/api\/privacy\/notice$/, v2: () => '/api/v2/privacy/notice' }, - { method: 'GET', v1: /^\/api\/privacy\/unsubscribe\/([^/]+)$/, v2: m => `/api/v2/unsubscribe/${m[1]}` }, - { method: 'POST', v1: /^\/api\/privacy\/unsubscribe\/([^/]+)$/, v2: m => `/api/v2/unsubscribe/${m[1]}` }, - { method: 'GET', v1: /^\/api\/privacy\/requests$/, v2: () => '/api/v2/privacy/requests' }, - { method: 'POST', v1: /^\/api\/privacy\/requests\/([^/]+)\/(complete|reject)$/, v2: m => `/api/v2/privacy/requests/${m[1]}/${m[2]}` }, - { method: 'GET', v1: /^\/api\/privacy\/notice\/draft$/, v2: () => '/api/v2/privacy/notice/draft' }, - { method: 'PUT', v1: /^\/api\/privacy\/notice\/draft$/, v2: () => '/api/v2/privacy/notice/draft' }, - { method: 'DELETE', v1: /^\/api\/privacy\/notice\/draft$/, v2: () => '/api/v2/privacy/notice/draft' }, - { method: 'POST', v1: /^\/api\/privacy\/notice\/(publish|builtin-reviewed)$/, v2: m => `/api/v2/privacy/notice/${m[1]}` }, - { method: 'GET', v1: /^\/api\/privacy\/operators$/, v2: () => '/api/v2/privacy/operators' }, - { method: 'POST', v1: /^\/api\/privacy\/operators$/, v2: () => '/api/v2/privacy/operators' }, - { method: 'PUT', v1: /^\/api\/privacy\/operators\/([^/]+)$/, v2: m => `/api/v2/privacy/operators/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/privacy\/operators\/([^/]+)$/, v2: m => `/api/v2/privacy/operators/${m[1]}` }, - { method: 'GET', v1: /^\/api\/privacy\/(consent-log|access-log|readiness|retention|breaches)$/, v2: m => `/api/v2/privacy/${m[1]}` }, - { method: 'PUT', v1: /^\/api\/privacy\/retention$/, v2: () => '/api/v2/privacy/retention' }, - { method: 'POST', v1: /^\/api\/privacy\/retention\/run$/, v2: () => '/api/v2/privacy/retention/run' }, - { method: 'POST', v1: /^\/api\/privacy\/breaches$/, v2: () => '/api/v2/privacy/breaches' }, - { method: 'PUT', v1: /^\/api\/privacy\/breaches\/([^/]+)$/, v2: m => `/api/v2/privacy/breaches/${m[1]}` }, - { method: 'GET', v1: /^\/api\/admin\/(audit-log|jobs|impersonation-sessions)$/, v2: m => `/api/v2/admin/${m[1]}` }, - { method: 'POST', v1: /^\/api\/admin\/jobs\/([^/]+)\/run$/, v2: m => `/api/v2/admin/jobs/${m[1]}/run` }, - { method: 'POST', v1: /^\/api\/admin\/impersonate\/(end|log)$/, v2: m => `/api/v2/me/impersonation/${m[1]}` }, - { method: 'GET', v1: /^\/api\/admin\/impersonate\/current$/, v2: () => '/api/v2/me/impersonation' }, - { method: 'POST', v1: /^\/api\/admin\/impersonate\/([^/]+)$/, v2: m => `/api/v2/admin/impersonate/${m[1]}` }, - { method: 'GET', v1: /^\/api\/settings\/needs-setup$/, v2: () => '/api/v2/setup/needed' }, - { method: 'GET', v1: /^\/api\/settings\/all$/, v2: () => '/api/v2/settings/all' }, - { method: 'GET', v1: /^\/api\/settings\/?$/, v2: () => '/api/v2/settings' }, - { method: 'PUT', v1: /^\/api\/settings\/?$/, v2: () => '/api/v2/settings' }, - { method: 'POST', v1: /^\/api\/settings\/test-smtp$/, v2: () => '/api/v2/settings/test-smtp' }, - { method: 'POST', v1: /^\/api\/setup\/register$/, v2: () => '/api/v2/setup/register' }, - { method: 'POST', v1: /^\/api\/setup\/?$/, v2: () => '/api/v2/setup' }, - { method: 'GET', v1: /^\/api\/hub\/(status|notices)$/, v2: m => `/api/v2/hub/${m[1]}` }, - { method: 'POST', v1: /^\/api\/hub\/(connect|heartbeat|update-request|update-snooze)$/, v2: m => `/api/v2/hub/${m[1]}` }, - { method: 'POST', v1: /^\/api\/hub\/update-request\/cancel$/, v2: () => '/api/v2/hub/update-request/cancel' }, - { method: 'GET', v1: /^\/api\/outbound-webhooks\/?$/, v2: () => '/api/v2/outbound-webhooks' }, - { method: 'POST', v1: /^\/api\/outbound-webhooks\/?$/, v2: () => '/api/v2/outbound-webhooks' }, - { method: 'POST', v1: /^\/api\/outbound-webhooks\/deliveries\/([^/]+)\/resend$/, v2: m => `/api/v2/outbound-webhook-deliveries/${m[1]}/resend` }, - { method: 'PUT', v1: /^\/api\/outbound-webhooks\/([^/]+)$/, v2: m => `/api/v2/outbound-webhooks/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/outbound-webhooks\/([^/]+)$/, v2: m => `/api/v2/outbound-webhooks/${m[1]}` }, - { method: 'POST', v1: /^\/api\/outbound-webhooks\/([^/]+)\/(rotate-secret|test)$/, v2: m => `/api/v2/outbound-webhooks/${m[1]}/${m[2]}` }, - { method: 'GET', v1: /^\/api\/outbound-webhooks\/([^/]+)\/deliveries$/, v2: m => `/api/v2/outbound-webhooks/${m[1]}/deliveries` }, - { method: 'GET', v1: /^\/api\/backups\/?$/, v2: () => '/api/v2/backups' }, - { method: 'POST', v1: /^\/api\/backups\/run$/, v2: () => '/api/v2/backups/run' }, - { method: 'GET', v1: /^\/api\/backups\/([^/]+)\/download$/, v2: m => `/api/v2/backups/${m[1]}/download` }, - { method: 'GET', v1: /^\/api\/(yoco|payfast)\/config$/, v2: m => `/api/v2/payments/${m[1]}/config` }, - { method: 'PUT', v1: /^\/api\/(yoco|payfast)\/config$/, v2: m => `/api/v2/payments/${m[1]}/config` }, - { method: 'GET', v1: /^\/api\/yoco\/webhooks$/, v2: () => '/api/v2/payments/yoco/webhooks' }, - { method: 'POST', v1: /^\/api\/yoco\/webhooks$/, v2: () => '/api/v2/payments/yoco/webhooks' }, - { method: 'DELETE', v1: /^\/api\/yoco\/webhooks\/([^/]+)$/, v2: m => `/api/v2/payments/yoco/webhooks/${m[1]}` }, - { method: 'POST', v1: /^\/api\/payfast\/test$/, v2: () => '/api/v2/payments/payfast/test' }, - // 1.51.14: people and messaging - { method: 'POST', v1: /^\/api\/users\/login\/2fa\/resend$/, v2: () => '/api/v2/auth/login/code/resend' }, - { method: 'POST', v1: /^\/api\/users\/forgot$/, v2: () => '/api/v2/auth/password/forgot' }, - { method: 'POST', v1: /^\/api\/users\/reset$/, v2: () => '/api/v2/auth/password/reset' }, - { method: 'POST', v1: /^\/api\/users\/activate$/, v2: () => '/api/v2/auth/activate' }, - { method: 'POST', v1: /^\/api\/users\/revoke-sessions$/, v2: () => '/api/v2/me/sessions/revoke' }, - { method: 'POST', v1: /^\/api\/users\/close-account$/, v2: () => '/api/v2/me/close' }, - { method: 'GET', v1: /^\/api\/users\/activity$/, v2: () => '/api/v2/me/activity' }, - { method: 'POST', v1: /^\/api\/users\/verify-password$/, v2: () => '/api/v2/me/verify-password' }, - { method: 'POST', v1: /^\/api\/users\/2fa\/(enable|confirm|disable)$/, v2: m => `/api/v2/me/two-factor/${m[1]}` }, - { method: 'GET', v1: /^\/api\/users\/check-exists$/, v2: () => '/api/v2/users/exists' }, - { method: 'POST', v1: /^\/api\/users\/([^/]+)\/revoke-sessions$/, v2: m => `/api/v2/users/${m[1]}/sessions/revoke` }, - { method: 'POST', v1: /^\/api\/users\/([^/]+)\/anonymize$/, v2: m => `/api/v2/users/${m[1]}/anonymize` }, - { method: 'GET', v1: /^\/api\/users\/?$/, v2: () => '/api/v2/users' }, - // (/api/users/profile is /api/v2/me — see 1.51.2 below.) - { method: 'GET', v1: /^\/api\/users\/(?!profile$)([^/]+)$/, v2: m => `/api/v2/users/${m[1]}` }, - { method: 'PUT', v1: /^\/api\/users\/(?!profile$)([^/]+)$/, v2: m => `/api/v2/users/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/users\/([^/]+)$/, v2: m => `/api/v2/users/${m[1]}` }, - { method: 'GET', v1: /^\/api\/events\/admin\/all$/, v2: () => '/api/v2/admin/events' }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/(email|whatsapp)-attendees$/, v2: m => `/api/v2/events/${m[1]}/${m[2]}-attendees` }, - { method: 'POST', v1: /^\/api\/events\/([^/]+)\/(email|whatsapp)-attendees\/schedule$/, v2: m => `/api/v2/events/${m[1]}/${m[2]}-attendees/schedule` }, - { method: 'POST', v1: /^\/api\/broadcasts\/(preview|send|schedule)$/, v2: m => `/api/v2/broadcasts/email/${m[1]}` }, - { method: 'POST', v1: /^\/api\/whatsapp-broadcasts\/(preview|send|schedule)$/, v2: m => `/api/v2/broadcasts/whatsapp/${m[1]}` }, - { method: 'GET', v1: /^\/api\/scheduled-emails\/?$/, v2: () => '/api/v2/scheduled-messages' }, - { method: 'PATCH', v1: /^\/api\/scheduled-emails\/([^/]+)$/, v2: m => `/api/v2/scheduled-messages/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/scheduled-emails\/([^/]+)$/, v2: m => `/api/v2/scheduled-messages/${m[1]}` }, - { method: 'POST', v1: /^\/api\/automations\/schedule$/, v2: () => '/api/v2/automations/schedule' }, - { method: 'GET', v1: /^\/api\/whatsapp\/(config|status|qr)$/, v2: m => `/api/v2/whatsapp/${m[1]}` }, - { method: 'POST', v1: /^\/api\/whatsapp\/config$/, v2: () => '/api/v2/whatsapp/config' }, - { method: 'POST', v1: /^\/api\/whatsapp\/create-instance$/, v2: () => '/api/v2/whatsapp/instance' }, - { method: 'POST', v1: /^\/api\/whatsapp\/delete-instance$/, v2: () => '/api/v2/whatsapp/instance' }, - { method: 'POST', v1: /^\/api\/whatsapp\/(request-code|logout|start|restart)$/, v2: m => `/api/v2/whatsapp/${m[1]}` }, - { method: 'GET', v1: /^\/api\/banner\/?$/, v2: () => '/api/v2/banner' }, - { method: 'POST', v1: /^\/api\/banner\/?$/, v2: () => '/api/v2/banner' }, - { method: 'GET', v1: /^\/api\/saved-filters\/?$/, v2: () => '/api/v2/saved-filters' }, - { method: 'POST', v1: /^\/api\/saved-filters\/?$/, v2: () => '/api/v2/saved-filters' }, - { method: 'PUT', v1: /^\/api\/saved-filters\/([^/]+)$/, v2: m => `/api/v2/saved-filters/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/saved-filters\/([^/]+)$/, v2: m => `/api/v2/saved-filters/${m[1]}` }, - { method: 'GET', v1: /^\/api\/dashboard\/(today|search)$/, v2: m => `/api/v2/dashboard/${m[1]}` }, - { method: 'GET', v1: /^\/api\/stats\/(staff|supervisor|admin|overview)$/, v2: m => `/api/v2/stats/${m[1]}` }, - { method: 'POST', v1: /^\/api\/analytics\/track$/, v2: () => '/api/v2/analytics/track' }, - { method: 'GET', v1: /^\/api\/analytics\/funnel$/, v2: () => '/api/v2/analytics/funnel' }, - { method: 'POST', v1: /^\/api\/reports\/(pdf|excel|email|whatsapp)$/, v2: m => `/api/v2/reports/${m[1]}` }, - // 1.51.13: kids check-in and volunteer rosters - { method: 'GET', v1: /^\/api\/kids\/me$/, v2: () => '/api/v2/me/family' }, - { method: 'POST', v1: /^\/api\/kids\/me$/, v2: () => '/api/v2/me/family' }, - { method: 'PUT', v1: /^\/api\/kids\/me$/, v2: () => '/api/v2/me/family' }, - { method: 'DELETE', v1: /^\/api\/kids\/me$/, v2: () => '/api/v2/me/family' }, - { method: 'POST', v1: /^\/api\/kids\/me\/(children|adults)$/, v2: m => `/api/v2/me/family/${m[1]}` }, - { method: 'PUT', v1: /^\/api\/kids\/me\/(children|adults)\/([^/]+)$/, v2: m => `/api/v2/me/family/${m[1]}/${m[2]}` }, - { method: 'DELETE', v1: /^\/api\/kids\/me\/(children|adults)\/([^/]+)$/, v2: m => `/api/v2/me/family/${m[1]}/${m[2]}` }, - { method: 'GET', v1: /^\/api\/kids\/setup-events$/, v2: () => '/api/v2/kids/setup-events' }, - { method: 'GET', v1: /^\/api\/kids\/events$/, v2: () => '/api/v2/kids/events' }, - { method: 'GET', v1: /^\/api\/kids\/events\/([^/]+)\/(settings|board|families|offline)$/, v2: m => `/api/v2/events/${m[1]}/kids/${m[2]}` }, - { method: 'PUT', v1: /^\/api\/kids\/events\/([^/]+)\/settings$/, v2: m => `/api/v2/events/${m[1]}/kids/settings` }, - { method: 'POST', v1: /^\/api\/kids\/events\/([^/]+)\/(families|check-in|check-out|duty|sync)$/, v2: m => `/api/v2/events/${m[1]}/kids/${m[2]}` }, - { method: 'GET', v1: /^\/api\/kids\/events\/([^/]+)\/families\/qr\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/kids/families/qr/${m[2]}` }, - { method: 'GET', v1: /^\/api\/kids\/events\/([^/]+)\/families\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/kids/families/${m[2]}` }, - { method: 'POST', v1: /^\/api\/kids\/events\/([^/]+)\/families\/([^/]+)\/(parents|children|adults)$/, v2: m => `/api/v2/events/${m[1]}/kids/families/${m[2]}/${m[3]}` }, - { method: 'PUT', v1: /^\/api\/kids\/events\/([^/]+)\/families\/([^/]+)\/children\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/kids/families/${m[2]}/children/${m[3]}` }, - { method: 'GET', v1: /^\/api\/kids\/events\/([^/]+)\/code\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/kids/code/${m[2]}` }, - { method: 'POST', v1: /^\/api\/kids\/check-ins\/([^/]+)\/(override|page)$/, v2: m => `/api/v2/kids/check-ins/${m[1]}/${m[2]}` }, - { method: 'PUT', v1: /^\/api\/kids\/check-ins\/([^/]+)\/room$/, v2: m => `/api/v2/kids/check-ins/${m[1]}/room` }, - { method: 'POST', v1: /^\/api\/kids\/alerts\/([^/]+)\/resolve$/, v2: m => `/api/v2/kids/alerts/${m[1]}/resolve` }, - { method: 'GET', v1: /^\/api\/volunteers\/me$/, v2: () => '/api/v2/me/volunteering' }, - { method: 'GET', v1: /^\/api\/volunteers\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/volunteer-roles` }, - { method: 'POST', v1: /^\/api\/volunteers\/roles\/([^/]+)\/sign-up$/, v2: m => `/api/v2/volunteer-roles/${m[1]}/sign-up` }, - { method: 'DELETE', v1: /^\/api\/volunteers\/slots\/([^/]+)$/, v2: m => `/api/v2/volunteer-slots/${m[1]}` }, - { method: 'POST', v1: /^\/api\/volunteers\/slots\/([^/]+)\/swap$/, v2: m => `/api/v2/volunteer-slots/${m[1]}/swap` }, - { method: 'DELETE', v1: /^\/api\/volunteers\/swaps\/([^/]+)$/, v2: m => `/api/v2/volunteer-swaps/${m[1]}` }, - { method: 'POST', v1: /^\/api\/volunteers\/swaps\/([^/]+)\/accept$/, v2: m => `/api/v2/volunteer-swaps/${m[1]}/accept` }, - { method: 'POST', v1: /^\/api\/volunteers\/check-in$/, v2: () => '/api/v2/volunteering/check-in' }, - { method: 'GET', v1: /^\/api\/volunteers\/manage\/events$/, v2: () => '/api/v2/volunteering/events' }, - { method: 'GET', v1: /^\/api\/volunteers\/manage\/hours$/, v2: () => '/api/v2/volunteering/hours' }, - { method: 'GET', v1: /^\/api\/volunteers\/manage\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/volunteers` }, - { method: 'GET', v1: /^\/api\/volunteers\/manage\/events\/([^/]+)\/(qr|settings)$/, v2: m => `/api/v2/events/${m[1]}/volunteers/${m[2]}` }, - { method: 'PUT', v1: /^\/api\/volunteers\/manage\/events\/([^/]+)\/settings$/, v2: m => `/api/v2/events/${m[1]}/volunteers/settings` }, - { method: 'POST', v1: /^\/api\/volunteers\/manage\/events\/([^/]+)\/roles$/, v2: m => `/api/v2/events/${m[1]}/volunteer-roles` }, - { method: 'PUT', v1: /^\/api\/volunteers\/manage\/roles\/([^/]+)$/, v2: m => `/api/v2/volunteer-roles/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/volunteers\/manage\/roles\/([^/]+)$/, v2: m => `/api/v2/volunteer-roles/${m[1]}` }, - { method: 'POST', v1: /^\/api\/volunteers\/manage\/roles\/([^/]+)\/assign$/, v2: m => `/api/v2/volunteer-roles/${m[1]}/assign` }, - { method: 'POST', v1: /^\/api\/volunteers\/manage\/slots\/([^/]+)\/check-in$/, v2: m => `/api/v2/volunteer-slots/${m[1]}/check-in` }, - { method: 'DELETE', v1: /^\/api\/volunteers\/manage\/slots\/([^/]+)$/, v2: m => `/api/v2/volunteer-slots/${m[1]}/remove` }, - // 1.51.12: tickets, scan locks, attendance and certificates, allocations - { method: 'GET', v1: /^\/api\/tickets\/mytickets$/, v2: () => '/api/v2/me/tickets' }, - { method: 'POST', v1: /^\/api\/tickets\/email$/, v2: () => '/api/v2/me/tickets/email' }, - { method: 'GET', v1: /^\/api\/tickets\/scans\/recent$/, v2: () => '/api/v2/tickets/scans/recent' }, - { method: 'GET', v1: /^\/api\/tickets\/scans\/stats$/, v2: () => '/api/v2/tickets/scans/stats' }, - { method: 'POST', v1: /^\/api\/tickets\/send-to$/, v2: () => '/api/v2/tickets/send' }, - { method: 'POST', v1: /^\/api\/tickets\/generate$/, v2: () => '/api/v2/tickets/generate' }, - { method: 'PUT', v1: /^\/api\/tickets\/email-sent$/, v2: () => '/api/v2/tickets/email-sent' }, - { method: 'GET', v1: /^\/api\/tickets\/qr\/([^/]+)$/, v2: m => `/api/v2/tickets/qr/${m[1]}` }, - { method: 'GET', v1: /^\/api\/tickets\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/tickets` }, - { method: 'GET', v1: /^\/api\/tickets\/transfer-offer\/([^/]+)$/, v2: m => `/api/v2/ticket-transfers/${m[1]}` }, - { method: 'POST', v1: /^\/api\/tickets\/transfer-offer\/([^/]+)\/(accept|decline)$/, v2: m => `/api/v2/ticket-transfers/${m[1]}/${m[2]}` }, - { method: 'GET', v1: /^\/api\/tickets\/?$/, v2: () => '/api/v2/tickets' }, - { method: 'GET', v1: /^\/api\/tickets\/([^/]+)\/transfers$/, v2: m => `/api/v2/tickets/${m[1]}/transfers` }, - { method: 'POST', v1: /^\/api\/tickets\/([^/]+)\/transfer$/, v2: m => `/api/v2/tickets/${m[1]}/transfer` }, - { method: 'DELETE', v1: /^\/api\/tickets\/([^/]+)\/transfer$/, v2: m => `/api/v2/tickets/${m[1]}/transfer` }, - { method: 'GET', v1: /^\/api\/tickets\/([^/]+)$/, v2: m => `/api/v2/tickets/${m[1]}` }, - { method: 'GET', v1: /^\/api\/scan-locks\/?$/, v2: () => '/api/v2/scan-locks' }, - { method: 'POST', v1: /^\/api\/scan-locks\/?$/, v2: () => '/api/v2/scan-locks' }, - { method: 'GET', v1: /^\/api\/scan-locks\/reports$/, v2: () => '/api/v2/scan-locks/reports' }, - { method: 'POST', v1: /^\/api\/scan-locks\/reports\/([^/]+)\/review$/, v2: m => `/api/v2/scan-locks/reports/${m[1]}/review` }, - { method: 'GET', v1: /^\/api\/scan-locks\/([^/]+)\/snapshot$/, v2: m => `/api/v2/scan-locks/${m[1]}/snapshot` }, - { method: 'POST', v1: /^\/api\/scan-locks\/([^/]+)\/(sync|force-release)$/, v2: m => `/api/v2/scan-locks/${m[1]}/${m[2]}` }, - { method: 'DELETE', v1: /^\/api\/scan-locks\/([^/]+)$/, v2: m => `/api/v2/scan-locks/${m[1]}` }, - { method: 'GET', v1: /^\/api\/attendance\/certificates\/verify\/([^/]+)$/, v2: m => `/api/v2/certificates/verify/${m[1]}` }, - { method: 'GET', v1: /^\/api\/attendance\/certificates\/mine$/, v2: () => '/api/v2/me/certificates' }, - { method: 'POST', v1: /^\/api\/attendance\/certificates\/preview$/, v2: () => '/api/v2/certificates/preview' }, - { method: 'GET', v1: /^\/api\/attendance\/certificates\/([^/]+)\/pdf$/, v2: m => `/api/v2/certificates/${m[1]}/pdf` }, - { method: 'POST', v1: /^\/api\/attendance\/certificates\/([^/]+)\/revoke$/, v2: m => `/api/v2/certificates/${m[1]}/revoke` }, - { method: 'GET', v1: /^\/api\/attendance\/([^/]+)\/export$/, v2: m => `/api/v2/events/${m[1]}/attendance/export` }, - { method: 'POST', v1: /^\/api\/attendance\/([^/]+)\/mark$/, v2: m => `/api/v2/events/${m[1]}/attendance` }, - { method: 'POST', v1: /^\/api\/attendance\/([^/]+)\/certificates$/, v2: m => `/api/v2/events/${m[1]}/certificates` }, - { method: 'POST', v1: /^\/api\/attendance\/([^/]+)\/certificates\/send$/, v2: m => `/api/v2/events/${m[1]}/certificates/send` }, - { method: 'GET', v1: /^\/api\/attendance\/([^/]+)\/certificates\.pdf$/, v2: m => `/api/v2/events/${m[1]}/certificates.pdf` }, - { method: 'GET', v1: /^\/api\/attendance\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/attendance` }, - { method: 'GET', v1: /^\/api\/allocations\/my-groups$/, v2: () => '/api/v2/me/allocation-groups' }, - { method: 'GET', v1: /^\/api\/allocations\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/allocations` }, - { method: 'POST', v1: /^\/api\/allocations\/sets$/, v2: () => '/api/v2/allocation-sets' }, - { method: 'PUT', v1: /^\/api\/allocations\/sets\/([^/]+)$/, v2: m => `/api/v2/allocation-sets/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/allocations\/sets\/([^/]+)$/, v2: m => `/api/v2/allocation-sets/${m[1]}` }, - { method: 'GET', v1: /^\/api\/allocations\/sets\/([^/]+)\/lists$/, v2: m => `/api/v2/allocation-sets/${m[1]}/lists` }, - { method: 'POST', v1: /^\/api\/allocations\/sets\/([^/]+)\/(groups|auto)$/, v2: m => `/api/v2/allocation-sets/${m[1]}/${m[2]}` }, - { method: 'PUT', v1: /^\/api\/allocations\/sets\/([^/]+)\/assignments$/, v2: m => `/api/v2/allocation-sets/${m[1]}/assignments` }, - { method: 'DELETE', v1: /^\/api\/allocations\/sets\/([^/]+)\/assignments$/, v2: m => `/api/v2/allocation-sets/${m[1]}/assignments` }, - { method: 'PUT', v1: /^\/api\/allocations\/groups\/([^/]+)$/, v2: m => `/api/v2/allocation-groups/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/allocations\/groups\/([^/]+)$/, v2: m => `/api/v2/allocation-groups/${m[1]}` }, - // 1.51.11: money (payments, cash-ups, provider transactions, waitlist, sponsorship, consent, forms, feedback) - { method: 'GET', v1: /^\/api\/payments\/providers$/, v2: () => '/api/v2/payments/providers' }, - { method: 'GET', v1: /^\/api\/payments\/providers\/settings$/, v2: () => '/api/v2/payments/providers/settings' }, - { method: 'PUT', v1: /^\/api\/payments\/providers\/settings$/, v2: () => '/api/v2/payments/providers/settings' }, - { method: 'GET', v1: /^\/api\/payments\/pay\/([^/]+)$/, v2: m => `/api/v2/payment-links/${m[1]}` }, - { method: 'POST', v1: /^\/api\/payments\/pay\/([^/]+)$/, v2: m => `/api/v2/payment-links/${m[1]}` }, - { method: 'GET', v1: /^\/api\/payments\/checkouts\/open$/, v2: () => '/api/v2/payments/open-checkouts' }, - { method: 'POST', v1: /^\/api\/payments\/checkouts\/check$/, v2: () => '/api/v2/payments/open-checkouts/check' }, - { method: 'POST', v1: /^\/api\/payments\/(yoco-)?checkout\/send$/, v2: () => '/api/v2/registrations/{id}/payment-link' }, - { method: 'GET', v1: /^\/api\/payments\/mypayments$/, v2: () => '/api/v2/me/payments' }, - { method: 'GET', v1: /^\/api\/payments\/admin\/stats$/, v2: () => '/api/v2/payments/stats' }, - { method: 'GET', v1: /^\/api\/payments\/registration\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/payments` }, - { method: 'GET', v1: /^\/api\/payments\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/payments` }, - { method: 'PUT', v1: /^\/api\/payments\/assign-donation$/, v2: () => '/api/v2/payments/donations/assign' }, - { method: 'POST', v1: /^\/api\/payments\/unassign-donation$/, v2: () => '/api/v2/payments/donations/unassign' }, - { method: 'POST', v1: /^\/api\/payments\/refund$/, v2: () => '/api/v2/payments/refunds' }, - { method: 'POST', v1: /^\/api\/payments\/([^/]+)\/send-receipt$/, v2: m => `/api/v2/payments/${m[1]}/receipt` }, - { method: 'GET', v1: /^\/api\/payments\/?$/, v2: () => '/api/v2/payments' }, - { method: 'POST', v1: /^\/api\/payments\/?$/, v2: () => '/api/v2/payments' }, - { method: 'GET', v1: /^\/api\/payments\/([^/]+)$/, v2: m => `/api/v2/payments/${m[1]}` }, - { method: 'GET', v1: /^\/api\/cashups\/audit$/, v2: () => '/api/v2/cashups/audit' }, - { method: 'GET', v1: /^\/api\/cashups\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/cashup` }, - { method: 'GET', v1: /^\/api\/cashups\/event\/([^/]+)\/cash-by-user$/, v2: m => `/api/v2/events/${m[1]}/cashup/cash-by-user` }, - { method: 'PUT', v1: /^\/api\/cashups\/event\/([^/]+)\/person-cash\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/cashup/person-cash/${m[2]}` }, - { method: 'PUT', v1: /^\/api\/cashups\/event\/([^/]+)\/draft$/, v2: m => `/api/v2/events/${m[1]}/cashup/draft` }, - { method: 'POST', v1: /^\/api\/cashups\/event\/([^/]+)\/close$/, v2: m => `/api/v2/events/${m[1]}/cashup/close` }, - { method: 'POST', v1: /^\/api\/cashups\/event\/([^/]+)\/reopen$/, v2: m => `/api/v2/events/${m[1]}/cashup/reopen` }, - { method: 'POST', v1: /^\/api\/cashups\/lines\/([^/]+)\/pending$/, v2: m => `/api/v2/cashup-lines/${m[1]}/pending` }, - { method: 'GET', v1: /^\/api\/(provider|yoco)-transactions\/?$/, v2: () => '/api/v2/provider-transactions' }, - { method: 'GET', v1: /^\/api\/(provider|yoco)-transactions\/unreconciled$/, v2: () => '/api/v2/provider-transactions/unreconciled' }, - { method: 'POST', v1: /^\/api\/(?:provider|yoco)-transactions\/([^/]+)\/reconcile$/, v2: m => `/api/v2/provider-transactions/${m[1]}/reconcile` }, - { method: 'POST', v1: /^\/api\/(?:provider|yoco)-transactions\/([^/]+)\/ignore$/, v2: m => `/api/v2/provider-transactions/${m[1]}/ignore` }, - { method: 'POST', v1: /^\/api\/waitlist\/?$/, v2: () => '/api/v2/waitlist' }, - { method: 'GET', v1: /^\/api\/waitlist\/mine$/, v2: () => '/api/v2/me/waitlist' }, - { method: 'GET', v1: /^\/api\/waitlist\/claim\/([^/]+)$/, v2: m => `/api/v2/waitlist/claims/${m[1]}` }, - { method: 'GET', v1: /^\/api\/waitlist\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/waitlist` }, - { method: 'POST', v1: /^\/api\/waitlist\/([^/]+)\/(offer|move|remove)$/, v2: m => `/api/v2/waitlist/${m[1]}/${m[2]}` }, - { method: 'DELETE', v1: /^\/api\/waitlist\/([^/]+)$/, v2: m => `/api/v2/waitlist/${m[1]}` }, - { method: 'GET', v1: /^\/api\/sponsorships\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/sponsorship` }, - { method: 'GET', v1: /^\/api\/sponsorships\/event\/([^/]+)\/pool$/, v2: m => `/api/v2/events/${m[1]}/sponsorship/pool` }, - { method: 'POST', v1: /^\/api\/sponsorships\/checkout$/, v2: () => '/api/v2/sponsorships/checkout' }, - { method: 'GET', v1: /^\/api\/consent\/events\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/consent` }, - { method: 'GET', v1: /^\/api\/consent\/events\/([^/]+)\/medical$/, v2: m => `/api/v2/events/${m[1]}/consent/medical` }, - { method: 'POST', v1: /^\/api\/consent\/events\/([^/]+)\/(resend-pending|rerequest)$/, v2: m => `/api/v2/events/${m[1]}/consent/${m[2]}` }, - { method: 'POST', v1: /^\/api\/consent\/requests\/([^/]+)\/resend$/, v2: m => `/api/v2/consent-requests/${m[1]}/resend` }, - { method: 'GET', v1: /^\/api\/consent\/([^/]+)$/, v2: m => `/api/v2/consent/${m[1]}` }, - { method: 'POST', v1: /^\/api\/consent\/([^/]+)$/, v2: m => `/api/v2/consent/${m[1]}` }, - { method: 'GET', v1: /^\/api\/forms\/responses$/, v2: () => '/api/v2/form-responses' }, - { method: 'GET', v1: /^\/api\/feedback\/summary$/, v2: () => '/api/v2/feedback/summary' }, - { method: 'GET', v1: /^\/api\/feedback\/public\/([^/]+)$/, v2: m => `/api/v2/feedback-forms/${m[1]}` }, - { method: 'POST', v1: /^\/api\/feedback\/public\/([^/]+)$/, v2: m => `/api/v2/feedback-forms/${m[1]}` }, - { method: 'GET', v1: /^\/api\/feedback\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/feedback` }, - { method: 'PUT', v1: /^\/api\/feedback\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/feedback` }, - { method: 'DELETE', v1: /^\/api\/feedback\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/feedback` }, - { method: 'POST', v1: /^\/api\/feedback\/event\/([^/]+)\/send-now$/, v2: m => `/api/v2/events/${m[1]}/feedback/send-now` }, - // 1.51.10: managing registrations - { method: 'GET', v1: /^\/api\/registrations\/?$/, v2: () => '/api/v2/registrations' }, - { method: 'GET', v1: /^\/api\/registrations\/myregistrations$/, v2: () => '/api/v2/me/registrations/full' }, - { method: 'GET', v1: /^\/api\/registrations\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/registrations` }, - { method: 'POST', v1: /^\/api\/registrations\/manual$/, v2: () => '/api/v2/registrations/manual' }, - { method: 'POST', v1: /^\/api\/registrations\/bulk$/, v2: () => '/api/v2/registrations/bulk' }, - { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/options$/, v2: m => `/api/v2/registrations/${m[1]}/items` }, - { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/send-invoice$/, v2: m => `/api/v2/registrations/${m[1]}/invoice` }, - { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/coupon$/, v2: m => `/api/v2/registrations/${m[1]}/coupon` }, - { method: 'DELETE', v1: /^\/api\/registrations\/([^/]+)\/coupon$/, v2: m => `/api/v2/registrations/${m[1]}/coupon` }, - { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/attendees$/, v2: m => `/api/v2/registrations/${m[1]}/attendees` }, - { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/attendees\/([^/]+)\/send-form-link$/, v2: m => `/api/v2/registrations/${m[1]}/attendees/${m[2]}/form-link` }, - { method: 'GET', v1: /^\/api\/registrations\/([^/]+)\/forms\/draft$/, v2: m => `/api/v2/registrations/${m[1]}/form-draft` }, - { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/forms\/draft$/, v2: m => `/api/v2/registrations/${m[1]}/form-draft` }, - { method: 'POST', v1: /^\/api\/registrations\/([^/]+)\/forms\/responses$/, v2: m => `/api/v2/registrations/${m[1]}/form-responses` }, - { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)\/forms\/responses$/, v2: m => `/api/v2/registrations/${m[1]}/form-responses` }, - { method: 'GET', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/full` }, - { method: 'PUT', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/status` }, - // 1.51.9: series, season passes, bundles, coupons, campuses - { method: 'GET', v1: /^\/api\/series\/?$/, v2: () => '/api/v2/series' }, - { method: 'POST', v1: /^\/api\/series\/?$/, v2: () => '/api/v2/series' }, - { method: 'GET', v1: /^\/api\/series\/by-slug\/([^/]+)$/, v2: m => `/api/v2/series/by-slug/${m[1]}` }, - { method: 'GET', v1: /^\/api\/series\/([^/]+)\/compare$/, v2: m => `/api/v2/series/${m[1]}/compare` }, - { method: 'POST', v1: /^\/api\/series\/([^/]+)\/follow$/, v2: m => `/api/v2/series/${m[1]}/follow` }, - { method: 'DELETE', v1: /^\/api\/series\/([^/]+)\/follow$/, v2: m => `/api/v2/series/${m[1]}/follow` }, - { method: 'PUT', v1: /^\/api\/series\/([^/]+)$/, v2: m => `/api/v2/series/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/series\/([^/]+)$/, v2: m => `/api/v2/series/${m[1]}` }, - { method: 'GET', v1: /^\/api\/season-passes\/mine$/, v2: () => '/api/v2/me/season-passes' }, - { method: 'POST', v1: /^\/api\/season-passes\/purchases\/([^/]+)\/checkout$/, v2: m => `/api/v2/season-pass-purchases/${m[1]}/checkout` }, - { method: 'POST', v1: /^\/api\/season-passes\/([^/]+)\/buy$/, v2: m => `/api/v2/season-passes/${m[1]}/buy` }, - { method: 'GET', v1: /^\/api\/season-passes\/?$/, v2: () => '/api/v2/season-passes' }, - { method: 'POST', v1: /^\/api\/season-passes\/?$/, v2: () => '/api/v2/season-passes' }, - { method: 'PUT', v1: /^\/api\/season-passes\/([^/]+)$/, v2: m => `/api/v2/season-passes/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/season-passes\/([^/]+)$/, v2: m => `/api/v2/season-passes/${m[1]}` }, - { method: 'POST', v1: /^\/api\/bundles\/quote$/, v2: () => '/api/v2/bundles/quote' }, - { method: 'GET', v1: /^\/api\/bundles\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/bundles` }, - { method: 'POST', v1: /^\/api\/bundles\/event\/([^/]+)$/, v2: m => `/api/v2/events/${m[1]}/bundles` }, - { method: 'PUT', v1: /^\/api\/bundles\/([^/]+)$/, v2: m => `/api/v2/bundles/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/bundles\/([^/]+)$/, v2: m => `/api/v2/bundles/${m[1]}` }, - { method: 'POST', v1: /^\/api\/coupons\/validate$/, v2: () => '/api/v2/coupons/check' }, - { method: 'GET', v1: /^\/api\/coupons\/redemptions$/, v2: () => '/api/v2/coupons/redemptions' }, - { method: 'GET', v1: /^\/api\/coupons\/?$/, v2: () => '/api/v2/coupons' }, - { method: 'POST', v1: /^\/api\/coupons\/?$/, v2: () => '/api/v2/coupons' }, - { method: 'GET', v1: /^\/api\/coupons\/([^/]+)$/, v2: m => `/api/v2/coupons/${m[1]}` }, - { method: 'PUT', v1: /^\/api\/coupons\/([^/]+)$/, v2: m => `/api/v2/coupons/${m[1]}` }, - { method: 'GET', v1: /^\/api\/campuses\/?$/, v2: () => '/api/v2/campuses' }, - { method: 'GET', v1: /^\/api\/campuses\/admin$/, v2: () => '/api/v2/campuses/admin' }, - { method: 'GET', v1: /^\/api\/campuses\/by-slug\/([^/]+)$/, v2: m => `/api/v2/campuses/by-slug/${m[1]}` }, - { method: 'PUT', v1: /^\/api\/campuses\/settings$/, v2: () => '/api/v2/campuses/enabled' }, - { method: 'PUT', v1: /^\/api\/campuses\/order$/, v2: () => '/api/v2/campuses/order' }, - { method: 'POST', v1: /^\/api\/campuses\/?$/, v2: () => '/api/v2/campuses' }, - { method: 'GET', v1: /^\/api\/campuses\/([^/]+)\/audience$/, v2: m => `/api/v2/campuses/${m[1]}/audience` }, - { method: 'PUT', v1: /^\/api\/campuses\/([^/]+)$/, v2: m => `/api/v2/campuses/${m[1]}` }, - { method: 'DELETE', v1: /^\/api\/campuses\/([^/]+)$/, v2: m => `/api/v2/campuses/${m[1]}` }, - { method: 'GET', v1: /^\/api\/users\/profile$/, v2: () => '/api/v2/me' }, - { method: 'PUT', v1: /^\/api\/users\/profile$/, v2: () => '/api/v2/me' }, - { method: 'POST', v1: /^\/api\/users\/?$/, v2: () => '/api/v2/auth/signup' }, - { method: 'POST', v1: /^\/api\/users\/login$/, v2: () => '/api/v2/auth/login' }, - { method: 'POST', v1: /^\/api\/users\/login\/2fa$/, v2: () => '/api/v2/auth/login/code' }, - { method: 'POST', v1: /^\/api\/registrations\/?$/, v2: () => '/api/v2/registrations' }, - { method: 'DELETE', v1: /^\/api\/registrations\/([^/]+)$/, v2: m => `/api/v2/registrations/${m[1]}/cancel` }, - { method: 'POST', v1: /^\/api\/payments\/checkout$/, v2: () => '/api/v2/registrations/{id}/checkout' }, - { method: 'GET', v1: /^\/api\/tickets\/scan-preview\/([^/]+)$/, v2: m => `/api/v2/checkin/${m[1]}` }, - { method: 'POST', v1: /^\/api\/tickets\/scan\/([^/]+)$/, v2: m => `/api/v2/checkin/${m[1]}` }, -]; - -// GET /api/events/all isn't a single event. -const NOT_AN_EVENT_ID = new Set(['all']); - -/** The v2 successor of a v1 request, if it has one. Pure; exported for tests. */ -export function successorOf(method: string, path: string): string | null { - for (const s of SUCCESSORS) { - if (s.method !== method) continue; - const m = path.match(s.v1); - if (!m) continue; - if (s.v1.source.startsWith('^\\/api\\/events\\/(') && NOT_AN_EVENT_ID.has(m[1])) continue; - return s.v2(m); - } - return null; -} - -export const deprecationHeaders: RequestHandler = (req, res, next) => { - const successor = successorOf(req.method, req.originalUrl.split('?')[0]); - if (successor) { - res.setHeader('Deprecation', `@${DEPRECATED_AT}`); - res.setHeader('Link', `<${successor}>; rel="successor-version"`); - } - next(); -}; diff --git a/apps/events/backend/src/v2/errors.ts b/apps/events/backend/src/v2/errors.ts index f34ae48..959973c 100644 --- a/apps/events/backend/src/v2/errors.ts +++ b/apps/events/backend/src/v2/errors.ts @@ -14,6 +14,7 @@ export type ErrorCode = | 'CONFLICT' | 'RATE_LIMITED' | 'READ_ONLY' + | 'UNAVAILABLE' | 'INTERNAL'; export const ERROR_STATUS: Record = { @@ -24,6 +25,8 @@ export const ERROR_STATUS: Record = { CONFLICT: 409, RATE_LIMITED: 429, READ_ONLY: 403, + // Something this depends on (the Hub, the AI service) can't be reached right now. + UNAVAILABLE: 503, INTERNAL: 500, }; @@ -54,7 +57,7 @@ export function zodFields(err: ZodError): Record { return fields; } -const STATUS_CODE: Record = { 400: 'VALIDATION_FAILED', 401: 'UNAUTHENTICATED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 409: 'CONFLICT', 423: 'READ_ONLY', 429: 'RATE_LIMITED' }; +const STATUS_CODE: Record = { 400: 'VALIDATION_FAILED', 401: 'UNAUTHENTICATED', 403: 'FORBIDDEN', 404: 'NOT_FOUND', 409: 'CONFLICT', 423: 'READ_ONLY', 429: 'RATE_LIMITED', 503: 'UNAVAILABLE' }; const PRISMA_CODE: Record = { P2002: 'CONFLICT', P2025: 'NOT_FOUND', P2003: 'CONFLICT' }; type LegacyError = Error & { statusCode?: number; status?: number; code?: string }; diff --git a/apps/events/backend/src/v2/index.ts b/apps/events/backend/src/v2/index.ts index ea79bb3..e5e51ac 100644 --- a/apps/events/backend/src/v2/index.ts +++ b/apps/events/backend/src/v2/index.ts @@ -22,6 +22,7 @@ import './resources/peopleMessaging'; import './resources/adminPrivacy'; import './resources/checkin'; import './resources/auth'; +import './resources/ai'; const pkg = require('../../package.json') as { version: string }; diff --git a/apps/events/backend/src/v2/links.ts b/apps/events/backend/src/v2/links.ts index aa972bd..420a4da 100644 --- a/apps/events/backend/src/v2/links.ts +++ b/apps/events/backend/src/v2/links.ts @@ -42,6 +42,22 @@ const REDIRECTS: { method: string; v1: RegExp; v2: (m: RegExpMatchArray) => stri { method: 'GET', v1: /^\/api\/privacy\/unsubscribe\/([^/]+)\/one-click$/, v2: m => `/api/v2/unsubscribe/${m[1]}/one-click` }, ]; +/** + * What's left of v1 (removed in 2.0), mounted at /api: WAWP's oldest webhook address (sites set + * up before 1.51.16 registered /api/whatsapp/webhook, and providers may not follow a redirect on + * POST) and a mail app's one-click unsubscribe POST to the address in an email already sent. + * /api/webhooks/… (Yoco, PayFast, WAWP) is mounted by app.js before the JSON parser. + */ +export const legacyV1Router = Router(); +legacyV1Router.post('/whatsapp/webhook', handleWhatsappWebhook); +legacyV1Router.post('/privacy/unsubscribe/:token/one-click', express.urlencoded({ extended: false }), privacy.oneClickUnsubscribe); + +/** Any other v1 address: gone since 2.0 (410, pointing at v2). /api/v2 misses fall through to 404. */ +export const v1Removed: RequestHandler = (req, res, next) => { + if (req.path === '/v2' || req.path.startsWith('/v2/')) return next(); + res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2.' }); +}; + export const legacyLinkRedirects: RequestHandler = (req, res, next) => { const [path, query] = req.originalUrl.split('?'); for (const r of REDIRECTS) { diff --git a/apps/events/backend/src/v2/openapi.ts b/apps/events/backend/src/v2/openapi.ts index 0686e34..834f92f 100644 --- a/apps/events/backend/src/v2/openapi.ts +++ b/apps/events/backend/src/v2/openapi.ts @@ -107,7 +107,7 @@ export function buildOpenApi(opts: { version: string; serverUrl?: string; list?: '- an error is `{ "error": { "code", "message", "fields"? } }` with a stable `code`.', '', 'Dates are ISO 8601 in UTC; amounts are in rand. Sign in through the app and send the token as `Authorization: Bearer `.', - 'Version 1 (`/api/…`) keeps working while the app moves over; it will be removed in 2.0.', + 'Version 1 (`/api/…`) was removed in 2.0: its addresses answer `410 Gone`. See the migration guide (MIGRATING-TO-2.md).', ].join('\n'), }, servers: [{ url: opts.serverUrl ?? '/api/v2' }], diff --git a/apps/events/backend/src/v2/resources/adminPrivacy.ts b/apps/events/backend/src/v2/resources/adminPrivacy.ts index 98abdf6..bb52820 100644 --- a/apps/events/backend/src/v2/resources/adminPrivacy.ts +++ b/apps/events/backend/src/v2/resources/adminPrivacy.ts @@ -88,7 +88,7 @@ v1Route({ method: 'post', path: '/privacy/operators', tag: 'Privacy', summary: ' v1Route({ method: 'put', path: '/privacy/operators/:id', tag: 'Privacy', summary: 'Change an operator', access: 'admin', params: idParams, body: loose, documented: { body: operatorInput.partial(), response: operator }, v1: privacy.updateOperator }); v1Route({ method: 'delete', path: '/privacy/operators/:id', tag: 'Privacy', summary: 'Remove an operator', access: 'admin', params: idParams, documented: { response: D.message }, v1: privacy.deleteOperator }); v1Route({ method: 'get', path: '/privacy/consent-log', tag: 'Privacy', summary: 'Consent given and withdrawn', access: 'admin', query: filters('type', 'page', 'q'), documented: { response: logPage(D.obj({ id: D.str, at: D.optDate, name: D.optStr })).describe('`type` news: email, channel, granted, source, ip; notice: email, version, source, ip; parental: child, event, status, signedName') }, v1: privacy.consentLog }); -v1Route({ method: 'get', path: '/privacy/access-log', tag: 'Privacy', summary: 'Who looked at sensitive information', access: 'admin', query: filters('page', 'action', 'sensitive', 'actorId', 'from', 'to'), documented: { response: logPage(D.obj({ id: D.str, at: D.date, actor: D.str, actorRole: D.optStr, action: D.str, what: D.optStr, records: D.optNum, eventId: D.optStr, ip: D.optStr, sensitive: D.bool })).extend({ actions: z.array(D.str), actors: z.array(D.obj({ id: D.str, name: D.str })) }) }, v1: privacy.accessLog }); +v1Route({ method: 'get', path: '/privacy/access-log', tag: 'Privacy', summary: 'Who looked at sensitive information', access: 'admin', query: filters('page', 'action', 'sensitive', 'actorId', 'from', 'to'), documented: { response: logPage(D.obj({ id: D.str, at: D.date, actor: D.str, actorRole: D.optStr, action: D.str, what: D.optStr, records: D.optNum, eventId: D.optStr, ip: D.optStr, sensitive: D.bool })).extend({ actions: z.record(z.string(), D.str).describe('Every action, with its label'), actors: z.array(D.obj({ id: D.str, name: D.str })) }) }, v1: privacy.accessLog }); v1Route({ method: 'get', path: '/privacy/readiness', tag: 'Privacy', summary: 'POPIA checklist', access: 'admin', documented: { response: D.obj({ score: D.num.describe('%'), passed: D.num, total: D.num, checks: z.array(D.obj({ key: D.str, label: D.str, ok: D.bool, detail: D.optStr, href: D.optStr, applies: D.bool })) }) }, v1: privacy.getReadiness }); v1Route({ method: 'get', path: '/privacy/retention', tag: 'Privacy', summary: 'How long information is kept', access: 'admin', documented: { response: retentionState }, v1: privacy.getRetention }); v1Route({ method: 'put', path: '/privacy/retention', tag: 'Privacy', summary: 'Change how long information is kept', access: 'admin', body: loose, documented: { body: D.obj({ policies: D.anyObj.describe('Per kind of information: { enabled, months }') }), response: retentionState }, v1: privacy.saveRetention }); diff --git a/apps/events/backend/src/v2/resources/ai.ts b/apps/events/backend/src/v2/resources/ai.ts new file mode 100644 index 0000000..2402b2c --- /dev/null +++ b/apps/events/backend/src/v2/resources/ai.ts @@ -0,0 +1,189 @@ +import { z } from 'zod'; +import { defineRoute } from '../route'; +import { single } from '../paging'; +import { id } from '../schemas'; +import { notFound } from '../errors'; +import { prisma } from '../legacy'; +import { aiStatus, getAiSettings, saveAiSettings, usageThisMonth, HELPERS, clearAiStatusCache } from '../../ai'; +import { draftEvent, summariseReport, draftMessage, summariseFeedback, improveText, REPORTS_WITHOUT_PEOPLE, type FeedbackQuestion } from '../../ai/helpers'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */ +const { campusIndependent, scopeBody } = require('../../utils/campusScope') as { campusIndependent(reason: string): any; scopeBody(targets: [string, string][], opts?: object): any }; +const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; +const { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; eventId?: string; records?: number }): Promise }; +const feedbackUtils = require('../../utils/feedback') as { summarise(fields: unknown[], answers: { fieldId: string; value: string }[]): any[] }; + +const helperFlags = z.object(Object.fromEntries(HELPERS.map(h => [h, z.boolean()])) as Record<(typeof HELPERS)[number], z.ZodBoolean>); + +const status = z.object({ + enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'), + capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'), + available: z.boolean().describe('false: the Hub couldn\'t be reached just now'), + capCents: z.number().describe('The monthly allowance, in cents'), + usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'), + usedPercent: z.number(), + renewsOn: z.string().nullable().describe('YYYY-MM-DD'), + helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'), +}); + +const settings = z.object({ + helpers: helperFlags, + dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'), +}); + +const use = z.object({ uses: z.number().int(), chargedCents: z.number() }); + +export const getAiStatus = defineRoute({ + method: 'get', + path: '/ai/status', + tag: 'AI', + summary: 'Whether to show the AI buttons', + description: 'Hidden when `enabled` is false; shown but disabled when `capReached` (until `renewsOn`, or until the allowance is raised). Cached for a minute; every AI call refreshes it.', + access: 'supervisor', + campusScope: 'campusIndependent (the site\'s AI allowance)', + middleware: [campusIndependent('the site\'s AI allowance')], + response: single(status), + async handler() { + return { data: await aiStatus() }; + }, +}); + +export const getAiUsage = defineRoute({ + method: 'get', + path: '/ai/usage', + tag: 'AI', + summary: 'AI use this month', + description: 'For Site settings → AI: the allowance, this site\'s switches, and this month\'s use per person, per helper and per day.', + access: 'admin', + response: single(z.object({ + status, + settings, + people: z.array(use.extend({ userId: z.string().nullable(), name: z.string() })), + helpers: z.array(use.extend({ helper: z.string() })), + days: z.array(use.extend({ day: z.string() })), + })), + async handler() { + clearAiStatusCache(); + const [s, settingsNow, usage] = await Promise.all([aiStatus({ fresh: true }), getAiSettings(), usageThisMonth()]); + return { data: { status: s, settings: settingsNow, ...usage } }; + }, +}); + +export const updateAiSettings = defineRoute({ + method: 'put', + path: '/ai/settings', + tag: 'AI', + summary: 'Switch helpers on or off, and set a daily limit', + access: 'admin', + body: z.object({ helpers: helperFlags.partial().optional(), dailyLimitPerPerson: z.number().int().min(0).max(1000).optional() }), + response: single(settings), + async handler({ body, user, req }) { + return { data: await saveAiSettings(body, user!, getClientIp(req)) }; + }, +}); + +// ─── The helpers ────────────────────────────────────────────────────────────── +// Each answer is a suggestion for a person to check: nothing is saved or sent by these routes. + +const withStatus = (output: T) => single(z.object({ output, status })); +const HELPER_SCOPE = 'campusIndependent (an AI suggestion from what is sent; nothing is read or changed)'; +const helperAccess = { access: 'supervisor' as const, campusScope: HELPER_SCOPE, middleware: [campusIndependent('an AI suggestion from what is sent; nothing is read or changed')] }; +const AI_DESCRIPTION = 'Goes through the Cross Events Hub, which counts it against the site\'s monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.'; + +const textList = z.array(z.string()); +const eventDraft = z.object({ + title: z.string(), summary: z.string(), description: z.string(), + startDate: z.string(), startTime: z.string(), endDate: z.string(), endTime: z.string(), + location: z.string(), capacity: z.number(), needsParentalConsent: z.boolean(), ageGroup: z.string(), + ticketOptions: z.array(z.object({ name: z.string(), priceRand: z.number(), description: z.string(), earlyBirdPriceRand: z.number(), earlyBirdUntil: z.string() })), + sessions: z.array(z.object({ date: z.string(), startTime: z.string(), endTime: z.string(), label: z.string() })), + costs: z.array(z.object({ item: z.string(), basis: z.string(), amountRand: z.number() })), + checks: textList, +}); + +export const aiDraftEvent = defineRoute({ + method: 'post', path: '/ai/draft-event', tag: 'AI', summary: 'Draft an event from a description', + description: `Fills in the event form from the organiser's notes. \`warnings\` are checked in code (a weekday that doesn't match its date, costs that a full event can't cover); \`draft.checks\` are the AI's own. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ notes: z.string().trim().min(10).max(4000) }), + response: withStatus(z.object({ draft: eventDraft, warnings: textList, totalCostRand: z.number(), breakEvenPlaces: z.number().nullable() })), + async handler({ body, user }) { + const { status: s, ...output } = await draftEvent(user!.id, body.notes); + return { data: { output, status: s } }; + }, +}); + +export const aiSummariseReport = defineRoute({ + method: 'post', path: '/ai/summarise-report', tag: 'AI', summary: 'Summarise a report', + description: `A few plain-language insights on a report as it is on screen. Only reports without people in them: ${REPORTS_WITHOUT_PEOPLE.join(', ')}. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ + reportKey: z.enum(REPORTS_WITHOUT_PEOPLE), + title: z.string().max(300), subtitle: z.string().max(500).optional(), + stats: z.array(z.object({ label: z.string().max(200), value: z.union([z.string().max(200), z.number()]) })).max(40).optional(), + columns: z.array(z.string().max(200)).max(40), + rows: z.array(z.array(z.union([z.string().max(500), z.number(), z.null()]).transform(v => v ?? ''))).max(5000), + }), + response: withStatus(z.object({ headline: z.string(), insights: z.array(z.object({ title: z.string(), detail: z.string() })), watchOut: textList })), + async handler({ body, user }) { + const { summary, status: s } = await summariseReport(user!.id, body); + return { data: { output: summary, status: s } }; + }, +}); + +export const aiDraftMessage = defineRoute({ + method: 'post', path: '/ai/draft-message', tag: 'AI', summary: 'Draft an email or WhatsApp message', + description: `Turns a short note into a message, using {{name}} and the event placeholders. With \`eventId\`, the event's title, start and place are given to the AI as facts. ${AI_DESCRIPTION}`, + access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])], + body: z.object({ channel: z.enum(['email', 'whatsapp']), note: z.string().trim().min(3).max(3000), eventId: id.optional() }), + response: withStatus(z.object({ subject: z.string(), body: z.string() })), + async handler({ body, user }) { + let event = null; + if (body.eventId) { + const e = await prisma.event.findUnique({ where: { id: body.eventId }, select: { title: true, startDate: true, location: true } }); + if (!e) throw notFound('The event'); + event = { title: e.title, start: e.startDate.toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }), location: e.location }; + } + const { message, status: s } = await draftMessage(user!.id, { channel: body.channel, note: body.note, event }); + return { data: { output: message, status: s } }; + }, +}); + +export const aiSummariseFeedback = defineRoute({ + method: 'post', path: '/ai/summarise-feedback', tag: 'AI', summary: 'Summarise an event\'s feedback', + description: `Themes, what people liked, what to improve and suggestions, from the event's feedback. Sent without who answered; contact details in comments are kept back. Recorded in the access log. ${AI_DESCRIPTION}`, + access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])], + body: z.object({ eventId: id }), + response: withStatus(z.object({ + overall: z.string(), liked: z.array(z.object({ theme: z.string(), mentions: z.number() })), improve: z.array(z.object({ theme: z.string(), mentions: z.number() })), + quotes: textList, nextTime: textList, responses: z.number(), + })), + async handler({ body, user, req }) { + const form = await prisma.feedbackForm.findUnique({ + where: { eventId: body.eventId }, + include: { event: { select: { title: true } }, fields: { orderBy: { order: 'asc' } }, responses: { include: { answers: true } }, _count: { select: { invites: true } } }, + }); + if (!form) throw notFound('Feedback for this event'); + if (!form.responses.length) throw Object.assign(notFound('Feedback answers for this event'), { reason: 'AI_NOTHING_TO_SUMMARISE' }); + // Never who answered: only the answers. + const answers = form.responses.flatMap(r => r.answers.map(a => ({ fieldId: a.fieldId, value: a.value }))); + const questions: FeedbackQuestion[] = feedbackUtils.summarise(form.fields, answers).map((q: any) => ({ + label: q.label, type: q.type, answered: q.answered, average: q.average, counts: q.counts, texts: q.texts?.map((t: { value: string }) => t.value), + })); + await logDataAccess(req, { action: 'ai_feedback', eventId: body.eventId, records: form.responses.length }); + const { summary, status: s } = await summariseFeedback(user!.id, { event: form.event, responses: form.responses.length, invited: form._count.invites, questions }); + return { data: { output: { ...summary, responses: form.responses.length }, status: s } }; + }, +}); + +export const aiImproveText = defineRoute({ + method: 'post', path: '/ai/improve-text', tag: 'AI', summary: 'Improve a piece of text', + description: `Fixes spelling and grammar and makes it clearer (\`improve\`), shorter (\`shorter\`) or only fixes mistakes (\`fix\`), keeping every fact. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ text: z.string().trim().min(3).max(8000), mode: z.enum(['improve', 'shorter', 'fix']).default('improve'), where: z.enum(['description', 'banner', 'message']).default('description') }), + response: withStatus(z.object({ text: z.string(), changes: textList })), + async handler({ body, user }) { + const { result, status: s } = await improveText(user!.id, body); + return { data: { output: result, status: s } }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/money.ts b/apps/events/backend/src/v2/resources/money.ts index b9b627d..891d861 100644 --- a/apps/events/backend/src/v2/resources/money.ts +++ b/apps/events/backend/src/v2/resources/money.ts @@ -204,7 +204,7 @@ v1Route({ }); v1Route({ method: 'get', path: `${cashupBase}/cash-by-user`, tag: 'Cash-ups', summary: 'Cash taken by each person', - access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, map: asEvent, documented: { response: D.obj({ rows: z.array(D.anyObj).describe('Per person: who, cash recorded, cash counted'), cashActualTotal: D.optRand, cashDenominations: D.anyObj.nullish() }) }, v1: cashup.getCashByRecordedUser, + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, map: asEvent, documented: { response: D.obj({ rows: z.array(D.anyObj).describe('Per person: who, cash recorded, cash counted'), cashActualTotal: D.optRand, cashDenominations: z.array(D.obj({ value: D.num.describe('The note or coin, in rand'), count: D.num })).describe('Counted cash by note and coin') }) }, v1: cashup.getCashByRecordedUser, }); v1Route({ method: 'put', path: `${cashupBase}/person-cash/:userId`, tag: 'Cash-ups', summary: 'Count one person\'s cash', diff --git a/apps/events/backend/tests/accountEnumeration.test.ts b/apps/events/backend/tests/accountEnumeration.test.ts index d804a8f..3848625 100644 --- a/apps/events/backend/tests/accountEnumeration.test.ts +++ b/apps/events/backend/tests/accountEnumeration.test.ts @@ -9,7 +9,8 @@ const mockDb = { }; jest.mock('../src/config/db', () => mockDb); const mockCompare = jest.fn(async () => false); -jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't' })); +const mockNeedsRehash = jest.fn(() => false); +jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't', needsRehash: (...a: unknown[]) => (mockNeedsRehash as jest.Mock)(...a) })); const mockSendMail = jest.fn(async () => undefined); jest.mock('../src/utils/email', () => ({ sendMail: (...a: unknown[]) => (mockSendMail as jest.Mock)(...a), buildPasswordResetEmail: () => ({ html: '', text: 'reset' }) })); jest.mock('../src/utils/notify', () => ({ waText: async () => undefined })); @@ -81,3 +82,27 @@ describe('sign-in', () => { expect(mockCompare).toHaveBeenCalledWith('guess', 'stand-in-hash'); }); }); + +describe('password re-hashing (2.0)', () => { + // Stop logIn at its first save, to see what it saves. + const firstSave = () => new Promise>(resolve => { + mockDb.user.update.mockImplementationOnce(async (args: { data: Record }) => { resolve(args.data); throw new Error('stop'); }); + }); + + test('a right password on an old hash saves a new hash', async () => { + mockDb.user.findFirst.mockResolvedValueOnce({ ...realUser, password: '$2a$10$old' }); + mockCompare.mockResolvedValueOnce(true as never); + mockNeedsRehash.mockReturnValueOnce(true); + const saved = firstSave(); + await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined); + expect(await saved).toMatchObject({ failedAttempts: 0, password: 'stand-in-hash' }); + }); + + test('a current hash is left as it is', async () => { + mockDb.user.findFirst.mockResolvedValueOnce(realUser); + mockCompare.mockResolvedValueOnce(true as never); + const saved = firstSave(); + await logIn({ identifier: realUser.email, password: 'right' }, { ip: '127.0.0.1', userAgent: 'test' } as never).catch(() => undefined); + expect(await saved).not.toHaveProperty('password'); + }); +}); diff --git a/apps/events/backend/tests/ai.test.ts b/apps/events/backend/tests/ai.test.ts new file mode 100644 index 0000000..8bbdabc --- /dev/null +++ b/apps/events/backend/tests/ai.test.ts @@ -0,0 +1,134 @@ +// AI helpers (2.0): what the buttons do, and how a helper call goes through the Hub (§3b). + +const mockCalls: Array> = []; +const mockSettings = new Map(); +const mockDb = { + appSetting: { + findUnique: jest.fn(async ({ where }: { where: { key: string } }) => (mockSettings.has(where.key) ? { key: where.key, value: mockSettings.get(where.key) } : null)), + upsert: jest.fn(async ({ where, update }: { where: { key: string }; update: { value: string } }) => { mockSettings.set(where.key, update.value); }), + }, + aiCall: { + count: jest.fn(async () => mockCalls.filter(c => c.outcome === 'ok').length), + create: jest.fn(async ({ data }: { data: Record }) => { mockCalls.push(data); return data; }), + deleteMany: jest.fn(async () => ({ count: 0 })), + }, + user: { findMany: jest.fn(async () => [{ email: 'admin@test.local' }]) }, +}; +jest.mock('../src/config/db', () => mockDb); + +const mockLicence = { connected: true, readOnly: false, state: 'active', claims: { limits: { aiMonthlyCapCents: 5000 } } as { limits: { aiMonthlyCapCents: number } } | null }; +jest.mock('../src/hub/licence', () => ({ licenceStatus: jest.fn(async () => mockLicence) })); + +class MockHubError extends Error { + constructor(message: string, public code: string, public statusCode: number, public data: unknown = null) { super(message); } +} +const mockPost = jest.fn(); +jest.mock('../src/hub/client', () => ({ PROTOCOL_VERSION: 1, HubError: MockHubError, signedPost: (...a: unknown[]) => mockPost(...a) })); +const mockMail = jest.fn(async (_m: unknown) => undefined); +jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true })); +jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) })); + +import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai'; + +const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over }); +const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 }; + +beforeEach(() => { + mockCalls.length = 0; + mockSettings.clear(); + mockPost.mockReset(); + mockMail.mockClear(); + mockLicence.connected = true; + mockLicence.readOnly = false; + mockLicence.claims = { limits: { aiMonthlyCapCents: 5000 } }; + clearAiStatusCache(); +}); + +describe('status', () => { + test('a licence without AI never asks the Hub', async () => { + mockLicence.claims = { limits: { aiMonthlyCapCents: 0 } }; + expect(await aiStatus()).toMatchObject({ enabled: false, capReached: false }); + mockLicence.connected = false; + expect((await aiStatus()).enabled).toBe(false); + expect(mockPost).not.toHaveBeenCalled(); + }); + + test('asks the Hub and caches its answer for a minute', async () => { + mockPost.mockResolvedValue(hubStatus()); + expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } }); + await aiStatus(); + expect(mockPost).toHaveBeenCalledTimes(1); + expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 }); + }); + + test('a Hub without AI (404) means off; an unreachable Hub keeps the buttons, marked unavailable', async () => { + mockPost.mockRejectedValueOnce(new MockHubError('Not found', 'NOT_FOUND', 404)); + expect((await aiStatus()).enabled).toBe(false); + clearAiStatusCache(); + mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502)); + expect(await aiStatus()).toMatchObject({ enabled: true, available: false }); + }); +}); + +describe('running a helper', () => { + test('sends the request to the Hub, logs the call, returns the answer', async () => { + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) }); + const r = await runHelper('draft_message', 'u1', req); + expect(r.output).toBe('Hi all!'); + expect(r.status.usedCents).toBe(100.31); + expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 }); + expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]); + }); + + test('a helper switched off, or the cap reached, never reaches the Hub', async () => { + mockPost.mockResolvedValue(hubStatus({ capReached: true })); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ code: 'FORBIDDEN', reason: 'AI_CAP_REACHED' }); + clearAiStatusCache(); + mockPost.mockResolvedValue(hubStatus()); + await saveAiSettings({ helpers: { draft_message: false } }, { id: 'a1', role: 'admin' }); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_HELPER_OFF' }); + expect(mockPost).not.toHaveBeenCalledWith('/api/installs/ai/complete', expect.anything(), expect.anything()); + }); + + test('the per-person daily limit', async () => { + await saveAiSettings({ dailyLimitPerPerson: 1 }, { id: 'a1', role: 'admin' }); + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'x', chargedCents: 0.1, status: hubStatus() }); + await runHelper('draft_message', 'u1', req); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ code: 'RATE_LIMITED', reason: 'AI_DAILY_LIMIT' }); + }); + + test('the Hub refusing at the cap updates the status, so the buttons disable at once', async () => { + mockPost.mockResolvedValueOnce(hubStatus()) + .mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) })); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') }); + expect((await aiStatus()).capReached).toBe(true); + expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 }); + }); + + test('admins are emailed once a month at 80%', async () => { + const at80 = hubStatus({ usedPercent: 81, usedCents: 4050 }); + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValue({ output: 'x', chargedCents: 1, status: at80 }); + await runHelper('draft_message', 'u1', req); + await runHelper('draft_message', 'u1', req); + expect(mockMail).toHaveBeenCalledTimes(1); + expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]); + }); +}); + +describe('Hub errors', () => { + test.each([ + ['AI_REFUSED', 'UNAVAILABLE', 'refused'], + ['AI_INCOMPLETE', 'UNAVAILABLE', 'incomplete'], + ['AI_OFF', 'FORBIDDEN', 'unavailable'], + ['HUB_UNREACHABLE', 'UNAVAILABLE', 'unavailable'], + ])('%s → %s, logged as %s', (hubCode, code, outcome) => { + const r = _internal.fromHubError({ code: hubCode, message: 'x' }); + expect(r.error.code).toBe(code); + expect(r.outcome).toBe(outcome); + }); + + test('today starts at midnight South African time', () => { + expect(_internal.startOfToday(new Date('2026-11-10T22:30:00Z')).toISOString()).toBe('2026-11-10T22:00:00.000Z'); + expect(_internal.startOfToday(new Date('2026-11-10T10:00:00Z')).toISOString()).toBe('2026-11-09T22:00:00.000Z'); + }); +}); diff --git a/apps/events/backend/tests/aiHelpers.test.ts b/apps/events/backend/tests/aiHelpers.test.ts new file mode 100644 index 0000000..0103352 --- /dev/null +++ b/apps/events/backend/tests/aiHelpers.test.ts @@ -0,0 +1,131 @@ +// The five AI helpers (2.0): what they send, what they keep back, and the checks done in code. + +const mockRun = jest.fn(); +jest.mock('../src/ai/index', () => ({ runHelper: (...a: unknown[]) => mockRun(...a) })); +jest.mock('../src/config/db', () => ({})); + +import { + todayLine, protect, restore, weekdayClashes, eventWarnings, reportText, feedbackText, + draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer, +} from '../src/ai/helpers'; + +const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} }; +const now = new Date('2026-10-30T08:00:00Z'); + +beforeEach(() => mockRun.mockReset()); + +const camp: EventDraftAnswer = { + title: 'Rooted Youth Camp', summary: '', description: '', startDate: '2027-03-14', startTime: '18:00', endDate: '2027-03-16', endTime: '14:00', + location: 'Camp Wartburg', capacity: 60, needsParentalConsent: true, ageGroup: 'Grades 8–12', + ticketOptions: [{ name: 'Camper', priceRand: 450, description: '', earlyBirdPriceRand: 400, earlyBirdUntil: '2027-01-31' }], + sessions: [], + costs: [ + { item: 'Venue', basis: 'R180 × 60 × 2', amountRand: 21600 }, { item: 'Bus', basis: '', amountRand: 6500 }, + { item: 'Speaker gift', basis: '', amountRand: 1000 }, { item: 'T-shirts', basis: 'R95 × 60', amountRand: 5700 }, + ], + checks: [], +}; + +describe('today and contact details', () => { + test('today is given in South African time', () => { + expect(todayLine(now)).toBe('Today is Friday 30 October 2026.'); + expect(todayLine(new Date('2026-10-30T22:30:00Z'))).toBe('Today is Saturday 31 October 2026.'); + }); + + test('emails, phone numbers and ID numbers never leave the site, and come back in the answer', () => { + const p = protect('Call Sarah on 082 555 1234 or +27 21 555 9876, email youth@church.co.za. ID 9001015009087. Bus R6 500 at 07:30.'); + // Emails are found first, then phone numbers, then ID numbers. + expect(p.text).toBe('Call Sarah on [[CONTACT2]] or [[CONTACT3]], email [[CONTACT1]]. ID [[CONTACT4]]. Bus R6 500 at 07:30.'); + expect(restore({ body: 'Questions? [[CONTACT1]] or [[CONTACT2]].', list: ['[[CONTACT3]]'] }, p.found)) + .toEqual({ body: 'Questions? youth@church.co.za or 082 555 1234.', list: ['+27 21 555 9876'] }); + }); + + test('the same detail twice gets one placeholder', () => { + expect(protect('a@b.co.za and again a@b.co.za').text).toBe('[[CONTACT1]] and again [[CONTACT1]]'); + }); +}); + +describe('checks done in code', () => { + test('a weekday that does not match its date', () => { + expect(weekdayClashes('Youth camp Fri 14 March to Sun 16 March', 2027)).toEqual([ + 'The notes say Friday 14 March, but 14 March 2027 is a Sunday. Check the dates.', + 'The notes say Sunday 16 March, but 16 March 2027 is a Tuesday. Check the dates.', + ]); + expect(weekdayClashes('Fri 14 March', 2025)).toEqual([]); + }); + + test('an event that loses money even when full', () => { + expect(eventWarnings('', camp)).toEqual([ + 'The costs in the notes come to R34 800, which needs 78 places at R450 — more than the 60 available. Even full, the event takes R27 000 (R24 000 if everyone books early), R7 800 short.', + ]); + expect(eventWarnings('', { ...camp, capacity: 80 })).toEqual([]); + expect(eventWarnings('', { ...camp, endDate: '2027-03-13' })).toContain('The end is before the start.'); + }); +}); + +describe('what the helpers send', () => { + test('draft an event: today\'s date, a schema, contact details kept back; code warnings added', async () => { + mockRun.mockResolvedValue({ output: { ...camp, description: 'Questions? [[CONTACT1]]' }, status }); + const r = await draftEvent('u1', 'Youth camp Fri 14 March, R450, 60 places. Questions: youth@church.co.za', now); + const [helper, user, req] = mockRun.mock.calls[0]; + expect([helper, user]).toEqual(['draft_event', 'u1']); + expect(req.system).toContain('Today is Friday 30 October 2026.'); + expect(req.input).not.toContain('youth@church.co.za'); + expect(req.schema.required).toContain('ticketOptions'); + expect(r.draft.description).toBe('Questions? youth@church.co.za'); + expect(r.totalCostRand).toBe(34800); + expect(r.breakEvenPlaces).toBe(78); + expect(r.warnings.some(w => w.includes('is a Sunday'))).toBe(true); + expect(r.warnings.some(w => w.includes('R7 800 short'))).toBe(true); + }); + + test('summarise a report: only reports without people', async () => { + await expect(summariseReport('u1', { reportKey: 'payments', title: 'Payments', columns: ['User'], rows: [['Jane']] })).rejects.toMatchObject({ reason: 'AI_REPORT_HAS_PEOPLE' }); + expect(mockRun).not.toHaveBeenCalled(); + mockRun.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status }); + await summariseReport('u1', { reportKey: 'revenue', title: 'Revenue Summary', stats: [{ label: 'Total', value: 'R66 550' }], columns: ['Event', 'Amount'], rows: [['Camp', 'R16 650']] }, now); + expect(mockRun.mock.calls[0][2].input).toBe('Report: Revenue Summary\nTotal: R66 550\nColumns: Event | Amount\nCamp | R16 650'); + }); + + test('report text is capped at 400 rows', () => { + const t = reportText({ reportKey: 'usage', title: 'T', columns: ['A'], rows: Array.from({ length: 450 }, (_, i) => [i]) }); + expect(t).toContain('(50 more rows not shown)'); + expect(t.split('\n')).toHaveLength(2 + 400 + 1); + }); + + test('feedback text: averages, counts and numbered comments, no names', () => { + expect(feedbackText({ title: 'Women\'s Conference' }, 112, 186, [ + { label: 'Overall', type: 'rating', answered: 112, average: 4.4 }, + { label: 'Come again?', type: 'yes_no', answered: 100, counts: [{ label: 'Yes', value: 90 }, { label: 'No', value: 10 }] }, + { label: 'Comments', type: 'text', answered: 2, texts: ['Hall B sound please fix it.', 'Loved the worship!'] }, + ])).toBe([ + 'Event: Women\'s Conference', 'Responses: 112 of 186 asked', 'Overall — average 4.4 (112 answers)', 'Come again? — Yes: 90, No: 10', + 'Comments — comments:', '1. Hall B sound please fix it.', '2. Loved the worship!', + ].join('\n')); + }); + + test('draft a message: WhatsApp has no subject; the event is given as facts', async () => { + mockRun.mockResolvedValue({ output: { subject: 'ignored', body: 'Hi {{name}}!' }, status }); + const r = await draftMessage('u1', { channel: 'whatsapp', note: 'bring a sleeping bag', event: { title: 'Youth Camp', start: 'Friday 14 March 2027, 18:00', location: 'Camp Wartburg' } }, now); + expect(r.message).toEqual({ subject: '', body: 'Hi {{name}}!' }); + expect(mockRun.mock.calls[0][2].input).toBe('Note: bring a sleeping bag\n\nEvent: Youth Camp, Friday 14 March 2027, 18:00, at Camp Wartburg'); + expect(mockRun.mock.calls[0][2].system).toContain('WhatsApp'); + expect(mockRun.mock.calls[0][2].system).toContain('{{event.title}}'); + }); + + test('draft a message without an event: no event placeholders offered', async () => { + mockRun.mockResolvedValue({ output: { subject: 'S', body: 'Hi {{name}}' }, status }); + await draftMessage('u1', { channel: 'email', note: 'the breakfast moves to the hotel' }, now); + const system = mockRun.mock.calls[0][2].system; + expect(system).toContain('Use no other {{…}} placeholders'); + expect(system).not.toContain('{{event.title}}'); + }); + + test('improve text: the mode and where it goes shape the instructions', async () => { + mockRun.mockResolvedValue({ output: { text: 'Fixed.', changes: [] }, status }); + await improveText('u1', { text: 'join us for are anual fun day', mode: 'fix', where: 'banner' }); + const req = mockRun.mock.calls[0][2]; + expect(req.system).toContain('a short banner across the top of the website'); + expect(req.system).toContain('Only fix spelling, grammar and punctuation'); + }); +}); diff --git a/apps/events/backend/tests/bulkRegistrations.test.js b/apps/events/backend/tests/bulkRegistrations.test.js index 4ea515e..63f521e 100644 --- a/apps/events/backend/tests/bulkRegistrations.test.js +++ b/apps/events/backend/tests/bulkRegistrations.test.js @@ -73,7 +73,7 @@ test('moving keeps the same lines and tickets, repriced; checks places; not othe test('payments and ticket changes are refused in licence read-only mode; cancelling is not', async () => { mockLicence.mockResolvedValueOnce({ readOnly: true }); await expect(bulk.runBulk(req, { action: 'markPaid', registrationIds: ['a'], method: 'cash' })).rejects.toMatchObject({ statusCode: 403 }); - expect(isBlocked('POST', '/api/registrations/bulk')).toBe(false); + expect(isBlocked('POST', '/api/v2/registrations/bulk')).toBe(false); }); test('allocating places each named person; a registration without names says so', async () => { diff --git a/apps/events/backend/tests/campusScopeRoutes.test.js b/apps/events/backend/tests/campusScopeRoutes.test.js deleted file mode 100644 index 3f3d66a..0000000 --- a/apps/events/backend/tests/campusScopeRoutes.test.js +++ /dev/null @@ -1,46 +0,0 @@ -// Every staff/supervisor route must say how it handles campus-scoped staff (utils/campusScope.js): -// scopeEvent(...), scopeList, unscopedOnly or campusIndependent('reason'). A route that says -// nothing would show a campus-limited supervisor every campus's data, so this fails on it. -const fs = require('fs'); -const path = require('path'); -const { staff, supervisor } = require('../src/middleware/authMiddleware'); - -const ROUTES_DIR = path.join(__dirname, '..', 'src', 'routes'); - -function staffRoutes() { - const out = []; - for (const file of fs.readdirSync(ROUTES_DIR).filter(f => f.endsWith('.js'))) { - const router = require(path.join(ROUTES_DIR, file)); - for (const layer of router.stack || []) { - if (!layer.route) continue; - for (const method of Object.keys(layer.route.methods)) { - // router.route('/x').get(...).put(...) puts every method's handlers on one route, so the - // role is checked per method (admin-only methods are never campus-scoped). - const forMethod = layer.route.stack.filter(s => s.method === method || s.method === undefined).map(s => s.handle); - if (!forMethod.includes(staff) && !forMethod.includes(supervisor)) continue; - const marker = forMethod.find(h => h && h.campusScope); - out.push({ file, method: method.toUpperCase(), path: layer.route.path, marker: marker ? marker.campusScope : null }); - } - } - } - return out; -} - -describe('campus scope on staff and supervisor routes', () => { - const routes = staffRoutes(); - - test('finds the staff and supervisor routes', () => { - expect(routes.length).toBeGreaterThan(100); - }); - - test('every one says how it handles campus-scoped staff', () => { - const missing = routes.filter(r => !r.marker).map(r => `${r.file} ${r.method} ${r.path}`); - expect(missing).toEqual([]); - }); - - test('a campus-independent route gives a reason', () => { - for (const r of routes.filter(x => x.marker && x.marker.startsWith('independent'))) { - expect(r.marker.length).toBeGreaterThan('independent: '.length + 5); - } - }); -}); diff --git a/apps/events/backend/tests/eventClone.test.js b/apps/events/backend/tests/eventClone.test.js index 8fd1491..39ff74a 100644 --- a/apps/events/backend/tests/eventClone.test.js +++ b/apps/events/backend/tests/eventClone.test.js @@ -26,6 +26,6 @@ describe('event cloning', () => { }); test('copying setup is blocked in licence read-only mode', () => { - expect(isBlocked('POST', '/api/events/abc/copy-from')).toBe(true); + expect(isBlocked('POST', '/api/v2/events/abc/copy-from')).toBe(true); }); }); diff --git a/apps/events/backend/tests/hub.test.js b/apps/events/backend/tests/hub.test.js index 0b9d249..83cc908 100644 --- a/apps/events/backend/tests/hub.test.js +++ b/apps/events/backend/tests/hub.test.js @@ -78,35 +78,7 @@ describe('heartbeat report', () => { }); describe('read-only mode', () => { - test.each([ - ['POST', '/api/events'], - ['PUT', '/api/events/ev_1'], - ['PUT', '/api/events/options/opt_1'], - ['PUT', '/api/events/variants/var_1'], - ['POST', '/api/registrations'], - ['POST', '/api/registrations/manual'], - ['PUT', '/api/registrations/abc/options'], - ['POST', '/api/payments'], - ['POST', '/api/payments/checkout'], - ['POST', '/api/payments/pay/chk_1'], - ['POST', '/api/waitlist'], - ])('%s %s is blocked', (m, p) => expect(isBlocked(m, p)).toBe(true)); - - test.each([ - ['POST', '/api/tickets/scan/QR123'], - ['GET', '/api/events'], - ['PUT', '/api/events/ev_1/notify-recipients'], - ['PUT', '/api/registrations/abc'], - ['POST', '/api/payments/refund'], - ['POST', '/api/privacy/me/requests'], - ['POST', '/api/hub/connect'], - ['POST', '/api/hub/update-request/cancel'], - ['POST', '/api/hub/update-snooze'], - ['POST', '/api/users/login'], - ['POST', '/api/reports/pdf'], - ])('%s %s keeps working', (m, p) => expect(isBlocked(m, p)).toBe(false)); - - // 1.52.3: the screens use /api/v2, so its routes must be blocked too. + // /api/v2 only (2.0 removed v1). test.each([ ['POST', '/api/v2/events'], ['PATCH', '/api/v2/events/ev_1'], diff --git a/apps/events/backend/tests/impersonation.test.js b/apps/events/backend/tests/impersonation.test.js index 357e1a7..26a6f2c 100644 --- a/apps/events/backend/tests/impersonation.test.js +++ b/apps/events/backend/tests/impersonation.test.js @@ -20,10 +20,10 @@ describe('allowedWhileImpersonating', () => { }); test('except ending the session and logging page views', () => { - expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/end')).toBe(true); - expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/log?x=1')).toBe(true); - expect(allowedWhileImpersonating('DELETE', '/api/admin/impersonate/end')).toBe(false); - expect(allowedWhileImpersonating('POST', '/api/admin/impersonate/end/../../users')).toBe(false); + expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end')).toBe(true); + expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/log?x=1')).toBe(true); + expect(allowedWhileImpersonating('DELETE', '/api/v2/me/impersonation/end')).toBe(false); + expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end/../../users')).toBe(false); }); }); diff --git a/apps/events/backend/tests/links.test.ts b/apps/events/backend/tests/links.test.ts index 53cc829..802b92c 100644 --- a/apps/events/backend/tests/links.test.ts +++ b/apps/events/backend/tests/links.test.ts @@ -10,7 +10,7 @@ jest.mock('../src/controllers/privacyController', () => ({ oneClickUnsubscribe: (req: { params: { token: string }; body: unknown }, res: { json(b: unknown): void }) => { mockCalls.push({ name: 'one-click', body: req.body }); res.json({ ok: true }); }, })); -import { webhooksRouter, linksRouter, legacyLinkRedirects } from '../src/v2/links'; +import { webhooksRouter, linksRouter, legacyLinkRedirects, legacyV1Router, v1Removed } from '../src/v2/links'; // The same order and raw-body handling as app.js. function app() { @@ -27,7 +27,9 @@ function app() { a.use(express.json()); a.use('/api/v2', linksRouter); a.use(legacyLinkRedirects); - a.post('/api/privacy/unsubscribe/:token/one-click', (_req, res) => { mockCalls.push({ name: 'v1 one-click' }); res.json({ ok: true }); }); + a.use('/api', legacyV1Router); + a.use('/api', v1Removed); + a.use((_req, res) => { res.status(404).json({ notFound: true }); }); return a; } @@ -72,6 +74,24 @@ describe('links in sent messages', () => { expect(mockCalls[0]).toEqual({ name: 'one-click', body: { 'List-Unsubscribe': 'One-Click' } }); const old = await request(app()).post('/api/privacy/unsubscribe/tok/one-click').type('form').send('List-Unsubscribe=One-Click'); expect(old.status).toBe(200); - expect(mockCalls[1].name).toBe('v1 one-click'); + expect(mockCalls[1]).toEqual({ name: 'one-click', body: { 'List-Unsubscribe': 'One-Click' } }); + }); +}); + +describe('v1, removed in 2.0', () => { + test("WAWP's oldest webhook address still reaches the handler", async () => { + await request(app()).post('/api/whatsapp/webhook?secret=s3').send({ event: 'message' }); + expect(mockCalls[0]).toEqual({ name: 'whatsapp', body: { event: 'message' }, query: { secret: 's3' } }); + }); + + test('any other v1 address answers 410 and points at v2', async () => { + const res = await request(app()).get('/api/events'); + expect(res.status).toBe(410); + expect(res.body).toMatchObject({ code: 'API_V1_REMOVED', message: expect.stringContaining('/api/v2') }); + expect((await request(app()).post('/api/users/login').send({})).status).toBe(410); + }); + + test('an unknown v2 address is still a 404', async () => { + expect((await request(app()).get('/api/v2/nothing-here')).status).toBe(404); }); }); diff --git a/apps/events/backend/tests/passwords.test.js b/apps/events/backend/tests/passwords.test.js new file mode 100644 index 0000000..c1ac8d5 --- /dev/null +++ b/apps/events/backend/tests/passwords.test.js @@ -0,0 +1,37 @@ +// 2.0: new passwords are hashed with Argon2id; bcrypt hashes from before still work and are +// re-hashed the next time the person signs in (services/auth.ts logIn). +const bcrypt = require('bcryptjs'); +const { hashPassword, comparePassword, needsRehash } = require('../src/config/auth'); + +describe('password hashing', () => { + test('new hashes are Argon2id and check out', async () => { + const hash = await hashPassword('Correct-horse-1'); + expect(hash.startsWith('$argon2id$')).toBe(true); + expect(await comparePassword('Correct-horse-1', hash)).toBe(true); + expect(await comparePassword('wrong', hash)).toBe(false); + expect(needsRehash(hash)).toBe(false); + }); + + test('two hashes of the same password differ (salted)', async () => { + expect(await hashPassword('same')).not.toBe(await hashPassword('same')); + }); + + test('old bcrypt hashes still sign in, and are marked for re-hashing', async () => { + const old = await bcrypt.hash('Legacy-pass-1', 10); + expect(await comparePassword('Legacy-pass-1', old)).toBe(true); + expect(await comparePassword('nope', old)).toBe(false); + expect(needsRehash(old)).toBe(true); + }); + + test('anything else never matches', async () => { + for (const stored of ['', null, undefined, 'plain-text', '$argon2id$broken']) { + expect(await comparePassword('plain-text', stored)).toBe(false); + } + expect(await comparePassword(undefined, await hashPassword('x'))).toBe(false); + }); + + test('weaker Argon2 settings are re-hashed too', () => { + expect(needsRehash('$argon2id$v=19$m=4096,t=3,p=1$c2FsdHNhbHQ$aGFzaGhhc2g')).toBe(true); + expect(needsRehash('$argon2i$v=19$m=19456,t=2,p=1$c2FsdHNhbHQ$aGFzaGhhc2g')).toBe(true); + }); +}); diff --git a/apps/events/backend/tests/seasonPass.test.js b/apps/events/backend/tests/seasonPass.test.js index 5a03634..c8d732a 100644 --- a/apps/events/backend/tests/seasonPass.test.js +++ b/apps/events/backend/tests/seasonPass.test.js @@ -112,9 +112,9 @@ describe('season passes', () => { }); test('making, changing and buying passes is blocked in licence read-only mode', () => { - expect(isBlocked('POST', '/api/season-passes')).toBe(true); - expect(isBlocked('PUT', '/api/season-passes/p1')).toBe(true); - expect(isBlocked('POST', '/api/season-passes/p1/buy')).toBe(true); - expect(isBlocked('POST', '/api/season-passes/purchases/pp1/checkout')).toBe(true); + expect(isBlocked('POST', '/api/v2/season-passes')).toBe(true); + expect(isBlocked('PATCH', '/api/v2/season-passes/p1')).toBe(true); + expect(isBlocked('POST', '/api/v2/season-passes/p1/buy')).toBe(true); + expect(isBlocked('POST', '/api/v2/season-pass-purchases/pp1/checkout')).toBe(true); }); }); diff --git a/apps/events/backend/tests/series.test.js b/apps/events/backend/tests/series.test.js index 3067b47..4acfbfd 100644 --- a/apps/events/backend/tests/series.test.js +++ b/apps/events/backend/tests/series.test.js @@ -41,9 +41,9 @@ describe('event series', () => { }); test('creating and changing series is blocked in licence read-only mode; following is not', () => { - expect(isBlocked('POST', '/api/series')).toBe(true); - expect(isBlocked('PUT', '/api/series/abc')).toBe(true); - expect(isBlocked('POST', '/api/series/abc/follow')).toBe(false); + expect(isBlocked('POST', '/api/v2/series')).toBe(true); + expect(isBlocked('PATCH', '/api/v2/series/abc')).toBe(true); + expect(isBlocked('PUT', '/api/v2/series/abc/follow')).toBe(false); }); describe('year-on-year comparison', () => { diff --git a/apps/events/backend/tests/v2.test.ts b/apps/events/backend/tests/v2.test.ts index 58c3a62..dd1fdb8 100644 --- a/apps/events/backend/tests/v2.test.ts +++ b/apps/events/backend/tests/v2.test.ts @@ -5,11 +5,17 @@ import request from 'supertest'; // way everywhere, and produce the OpenAPI document. const mockDb = { - event: { findMany: jest.fn(), count: jest.fn(), findFirst: jest.fn() }, + event: { findMany: jest.fn(), count: jest.fn(), findFirst: jest.fn(), findUnique: jest.fn() }, user: { findUnique: jest.fn() }, registration: { findMany: jest.fn(), count: jest.fn(), findUnique: jest.fn(), findUniqueOrThrow: jest.fn() }, + feedbackForm: { findUnique: jest.fn() }, }; jest.mock('../src/config/db', () => mockDb); +// AI helpers: everything real except the call to the Hub. +const mockRunHelper = jest.fn(); +jest.mock('../src/ai/index', () => ({ ...jest.requireActual('../src/ai/index'), runHelper: (...a: unknown[]) => mockRunHelper(...a) })); +const mockAccessLog = jest.fn(async () => undefined); +jest.mock('../src/utils/accessLog', () => ({ logDataAccess: (...a: unknown[]) => mockAccessLog(...(a as [])) })); jest.mock('../src/utils/campuses', () => ({ campusesEnabled: jest.fn().mockResolvedValue(false), resolveCampusFilter: jest.fn(async (v: string) => v), @@ -386,24 +392,6 @@ describe('check-in', () => { expect(res.body.data.ticket).toMatchObject({ attendee: 'Lulu', bookedBy: 'Thandi', ticketOptionId: 'o1', remaining: 2, consentStatus: 'not_required' }); }); }); - -describe('v1 deprecation headers', () => { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const { successorOf } = require('../src/v2/deprecation'); - test('v1 endpoints with a v2 replacement point at it; the rest say nothing', () => { - expect(successorOf('GET', '/api/events')).toBe('/api/v2/events'); - expect(successorOf('GET', '/api/events/e1')).toBe('/api/v2/events/e1/full'); - expect(successorOf('PUT', '/api/events/options/o1')).toBe('/api/v2/ticket-options/o1'); - expect(successorOf('DELETE', '/api/events/e1/attachments/a1')).toBe('/api/v2/events/e1/attachments/a1'); - expect(successorOf('GET', '/api/events/all')).toBe('/api/v2/events/manage'); - expect(successorOf('PUT', '/api/events/e1')).toBe('/api/v2/events/e1'); - expect(successorOf('DELETE', '/api/registrations/r1')).toBe('/api/v2/registrations/r1/cancel'); - expect(successorOf('POST', '/api/tickets/scan/QR1')).toBe('/api/v2/checkin/QR1'); - expect(successorOf('GET', '/api/reports/summary')).toBeNull(); - expect(successorOf('GET', '/api/v2/events')).toBeNull(); - }); -}); - describe('shared middleware on v2', () => { test("v1-style refusals become v2 errors, keeping the specific code as reason", async () => { // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -693,3 +681,82 @@ describe('money (v1 handlers behind v2 routes)', () => { expect(res.body.data).toEqual({ params: { lineId: 'l9' }, body: { resolution: 'paid' } }); }); }); + +describe('AI helpers (2.0)', () => { + const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } }; + + test('supervisors only', async () => { + signedIn = { id: 's1', role: 'staff' }; + expect((await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there' })).status).toBe(403); + expect(mockRunHelper).not.toHaveBeenCalled(); + }); + + test('improve text: the answer and the new status', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + mockRunHelper.mockResolvedValue({ output: { text: 'Hello there.', changes: ['Capital letter'] }, status: st }); + const res = await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there', mode: 'fix', where: 'banner' }); + expect(res.status).toBe(200); + expect(res.body.data).toEqual({ output: { text: 'Hello there.', changes: ['Capital letter'] }, status: st }); + expect(mockRunHelper.mock.calls[0][0]).toBe('improve_text'); + }); + + test('summarise a report: reports with people in them are refused by validation', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + const res = await request(app).post('/api/v2/ai/summarise-report').send({ reportKey: 'payments', title: 'Payments', columns: ['User'], rows: [['Jane']] }); + expect(res.status).toBe(400); + expect(mockRunHelper).not.toHaveBeenCalled(); + }); + + test('draft an event: the draft with warnings worked out in code', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + const draft = { + title: 'Camp', summary: '', description: '', startDate: '2027-03-14', startTime: '18:00', endDate: '2027-03-16', endTime: '14:00', location: '', capacity: 60, needsParentalConsent: true, ageGroup: '', + ticketOptions: [{ name: 'Camper', priceRand: 450, description: '', earlyBirdPriceRand: 0, earlyBirdUntil: '' }], sessions: [], + costs: [{ item: 'Venue', basis: '', amountRand: 34800 }], checks: [], + }; + mockRunHelper.mockResolvedValue({ output: draft, status: st }); + const res = await request(app).post('/api/v2/ai/draft-event').send({ notes: 'Camp Fri 14 March, R450, 60 places' }); + expect(res.status).toBe(200); + expect(res.body.data.output).toMatchObject({ totalCostRand: 34800, breakEvenPlaces: 78 }); + expect(res.body.data.output.warnings.join(' ')).toMatch(/is a Sunday.*R7 800 short/); + }); + + test('draft a message: the event is given as facts', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + mockDb.event.findUnique.mockResolvedValue({ title: 'Youth Camp', startDate: new Date('2027-03-12T16:00:00Z'), location: 'Camp Wartburg' }); + mockRunHelper.mockResolvedValue({ output: { subject: '', body: 'Hi {{name}}!' }, status: st }); + const res = await request(app).post('/api/v2/ai/draft-message').send({ channel: 'whatsapp', note: 'bring a sleeping bag', eventId: '11111111-1111-4111-8111-111111111111' }); + expect(res.status).toBe(200); + expect(res.body.data.output).toEqual({ subject: '', body: 'Hi {{name}}!' }); + expect(mockRunHelper.mock.calls[0][2].input).toContain('Event: Youth Camp'); + }); + + test('summarise feedback: answers without who gave them, and an access-log entry', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + mockDb.feedbackForm.findUnique.mockResolvedValue({ + event: { title: 'Conference' }, _count: { invites: 10 }, + fields: [{ id: 'f1', type: 'rating', label: 'Overall' }, { id: 'f2', type: 'textarea', label: 'Comments' }], + responses: [ + { userId: 'u1', user: { name: 'Jane Doe' }, answers: [{ fieldId: 'f1', value: '5' }, { fieldId: 'f2', value: 'Loved it, call me on 082 555 1234' }] }, + { userId: 'u2', user: { name: 'John Roe' }, answers: [{ fieldId: 'f1', value: '3' }] }, + ], + }); + mockRunHelper.mockResolvedValue({ output: { overall: 'Good.', liked: [], improve: [], quotes: [], nextTime: [] }, status: st }); + const res = await request(app).post('/api/v2/ai/summarise-feedback').send({ eventId: '11111111-1111-4111-8111-111111111111' }); + expect(res.status).toBe(200); + expect(res.body.data.output.responses).toBe(2); + const sent = mockRunHelper.mock.calls[0][2].input; + expect(sent).toContain('Overall — average 4'); + expect(sent).not.toMatch(/Jane|John|082 555 1234/); + expect(mockAccessLog).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ action: 'ai_feedback', records: 2 })); + }); + + test('Hub errors keep their reason', async () => { + signedIn = { id: 's1', role: 'supervisor' }; + const { ApiError } = jest.requireActual('../src/v2/errors'); + mockRunHelper.mockRejectedValue(Object.assign(new ApiError('FORBIDDEN', 'Used up.'), { reason: 'AI_CAP_REACHED' })); + const res = await request(app).post('/api/v2/ai/improve-text').send({ text: 'hello there' }); + expect(res.status).toBe(403); + expect(res.body.error).toMatchObject({ code: 'FORBIDDEN', reason: 'AI_CAP_REACHED' }); + }); +}); diff --git a/apps/events/backend/tests/v2CampusScope.test.ts b/apps/events/backend/tests/v2CampusScope.test.ts new file mode 100644 index 0000000..6b683b6 --- /dev/null +++ b/apps/events/backend/tests/v2CampusScope.test.ts @@ -0,0 +1,53 @@ +// Every staff/supervisor route on /api/v2 must really check campus-scoped staff (utils/campusScope.js). +// A route has to declare `campusScope` (start-up fails otherwise), but the declaration is only text: +// the check itself is a marked middleware — scopeEvent(...), scopeBody(...), scopeList, +// unscopedOnly, campusIndependent('reason') or scopeBroadcast(...). A route without one would show +// a campus-limited supervisor every campus's data, so this fails on it. +// +// (Until 2.0 the same test ran over the v1 route files, which held the markers.) +// +// The routes below check campuses inside their TypeScript service or handler instead, as their +// `campusScope` text says. Adding a route here means its handler does the check itself. +const CHECKED_IN_HANDLER = new Set([ + 'GET /events/manage', 'POST /events', 'GET /sections', 'POST /uploads/event-image', + 'GET /series', 'POST /series', 'PATCH /series/:id', 'GET /series/:id/compare', + 'GET /season-passes', 'POST /season-passes', 'PATCH /season-passes/:id', 'DELETE /season-passes/:id', + 'GET /coupons', 'GET /coupons/redemptions', 'GET /coupons/:id', 'POST /coupons', 'PATCH /coupons/:id', + 'GET /campuses/:id/audience', 'GET /registrations', + 'GET /saved-filters', 'POST /saved-filters', 'PUT /saved-filters/:id', 'DELETE /saved-filters/:id', + 'GET /checkin/:qrCode', 'POST /checkin/:qrCode', +]); + +/* eslint-disable @typescript-eslint/no-require-imports */ +const { v2Router } = require('../src/v2'); +const { routes } = require('../src/v2/route'); + +type Route = { method: string; path: string; access: string; campusScope?: string; middleware?: { campusScope?: string }[] }; + +describe('campus scope on v2 staff and supervisor routes', () => { + v2Router(); + const staffRoutes = (routes as Route[]).filter(r => r.access === 'staff' || r.access === 'supervisor'); + const key = (r: Route) => `${r.method.toUpperCase()} ${r.path}`; + const marker = (r: Route) => (r.middleware || []).find(h => h && h.campusScope)?.campusScope; + + test('finds the staff and supervisor routes', () => { + expect(staffRoutes.length).toBeGreaterThan(150); + }); + + test('each one has a campus-scope middleware, or checks in its handler', () => { + const missing = staffRoutes.filter(r => !marker(r) && !CHECKED_IN_HANDLER.has(key(r))).map(key); + expect(missing).toEqual([]); + }); + + test('the handler-checked list holds only real staff routes without a middleware', () => { + const real = new Set(staffRoutes.filter(r => !marker(r)).map(key)); + expect([...CHECKED_IN_HANDLER].filter(k => !real.has(k))).toEqual([]); + }); + + test('a campus-independent route gives a reason', () => { + for (const r of staffRoutes) { + const m = marker(r); + if (m && m.startsWith('independent')) expect(m.length).toBeGreaterThan('independent: '.length + 5); + } + }); +}); diff --git a/apps/events/backend/tests/volunteers.test.js b/apps/events/backend/tests/volunteers.test.js index eabcbb1..2d53505 100644 --- a/apps/events/backend/tests/volunteers.test.js +++ b/apps/events/backend/tests/volunteers.test.js @@ -80,13 +80,13 @@ describe('reserved tickets', () => { describe('read-only licence', () => { test.each([ - ['POST', '/api/volunteers/roles/r1/sign-up'], - ['POST', '/api/volunteers/manage/events/e1/roles'], - ['POST', '/api/volunteers/manage/roles/r1/assign'], + ['POST', '/api/v2/volunteer-roles/r1/sign-up'], + ['POST', '/api/v2/events/e1/volunteer-roles'], + ['POST', '/api/v2/volunteer-roles/r1/assign'], ])('%s %s is blocked', (m, p) => expect(isBlocked(m, p)).toBe(true)); test.each([ - ['POST', '/api/volunteers/check-in'], - ['POST', '/api/volunteers/swaps/w1/accept'], - ['DELETE', '/api/volunteers/slots/s1'], + ['POST', '/api/v2/volunteering/check-in'], + ['POST', '/api/v2/volunteer-swaps/w1/accept'], + ['DELETE', '/api/v2/volunteer-slots/s1'], ])('%s %s keeps working', (m, p) => expect(isBlocked(m, p)).toBe(false)); }); diff --git a/apps/events/docs/HANDOVER.md b/apps/events/docs/HANDOVER.md index 8f52988..ea6f482 100644 --- a/apps/events/docs/HANDOVER.md +++ b/apps/events/docs/HANDOVER.md @@ -1,6 +1,6 @@ # Handover — where things stand and how to carry on -Last updated: 2026-11-02, after **1.52.2** (and Hub 1.5.0). The plan itself is in +Last updated: 2026-11-02, after **2.0.0** and Hub **1.6.1**. The plan itself is in [ROADMAP-v2.md](./ROADMAP-v2.md) (decisions table at the end); the previous round of features is in [FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md). @@ -12,8 +12,13 @@ encrypted settings unreadable or break existing installs. ## Done so far (road to 2.0) +**2.0.0 is released** (2026-11-02). What changed for integrations and servers is in +[MIGRATING-TO-2.md](../MIGRATING-TO-2.md). + | Version | What | |---------|------| +| **2.0.0** | **AI helpers** (draft an event, draft a message, summarise a report or feedback, improve text — `backend/src/ai/`, through the Hub with a rand cap per licence; eval set `npm run ai:eval`); **API v1 removed** (410 `API_V1_REMOVED`; provider webhooks and links in sent messages still answered — [v1 removed](#v1-removed-20)); **Argon2id passwords** with re-hashing at sign-in ([Passwords](#passwords-20)); `node-fetch` removed; React Compiler lint rules back to errors (`lib/hooks.ts`, see [Next.js 16](#nextjs-16-1515)); campus-scope route test on v2 (`tests/v2CampusScope.test.ts`); migration guide `MIGRATING-TO-2.md`. Migration `20261030120000_ai_helpers`. Needs Hub 1.6.0+ for AI | +| 1.52.3 | **Urgent fix:** licence read-only mode blocks the `/api/v2` routes too (`src/hub/readOnly.js` only listed v1 paths, and the screens have used v2 since 1.51.15). A test checks each blocked v2 path is a real route | | 1.52.2 | `scripts/deploy.sh` stops first (listing them) when files in the install were changed or added by hand; `--check` runs only that; runs from a copy outside the install too; `ALLOW_LOCAL_CHANGES=1` overrides | | 1.52.1 | **API documentation complete:** every v2 route documents its body, answer and parameters — the ~300 answered by v1 handlers through `documented` shapes (`src/v2/docs.ts`), shown but not enforced, logged outside production when they don't fit; empty bodies say "No body needed". Test `tests/v2Docs.test.ts` | | 1.52.0 | **Urgent fix + Corrections:** required attendee forms no longer leave paid door/manual registrations without tickets — popup with "Fill in later" (`Registration.formWaivedAt`, `POST /api/v2/registrations/{id}/form-later`); one form per person on picked sessions; forms with no questions don't hold tickets; kiosk asks for the forms the server says are missing. Admin **Corrections** page (`src/services/corrections.ts`, `/api/v2/corrections/…`): issue missing tickets, pay later (`ticketsReleasedAt`), make it free (`complimentaryDiscount`), check in after the event. Migration `20261102120000_corrections`. e2e `e2e/corrections.spec.ts` | @@ -79,28 +84,28 @@ encrypted settings unreadable or break existing installs. ## Next up -Hub 1.1.0 is deployed with update requests rolled out, and `scripts/install.sh` has been tried on -a test server (both done 2026-10-28). - -1. **2.0.0** — AI helpers (§15), v1 removed, a migration guide, and marketing site/docs for - selling. Every endpoint is on v2 since 1.51.16. Keep answering the v1 webhook paths and the - old links in sent messages (`src/v2/links.ts`) after v1 goes: providers and old emails still - use them. +1. **After 2.0.0:** + - **Deploy:** `bash scripts/deploy.sh --check`, then `bash scripts/deploy.sh v2.0.0` on each server + (installs on 1.52.x ask through Request update as usual). Before updating an install that has + its own integration, look in the nginx access log for `/api/` calls that aren't `/api/v2/`, + the webhooks or the old links — those get 410 after the update (MIGRATING-TO-2.md). + - **AI for a church:** set the licence's monthly AI cap above R0 on the Hub (Hub 1.6.0+); with + no cap the buttons don't show. + - **Marketing site** (roadmap §17): a simple static HTML site — Cross Code as the main site, + with a Cross Events page, in its own repo. Questions still open: see the roadmap's "Still + open". + - Testing AI locally: run the Hub (`../events-hub`, port 5200), set Settings → AI there, give a + test licence an AI cap, and start Cross Events with `HUB_URL=http://localhost:5200`. 2. **AI rules** (decided 2026-10-29, roadmap §15): the AI buttons show only when the licence's monthly cap is above R0, and are disabled (not hidden) once it's reached. The Hub charges the real cost plus a markup % (a default and a per-licence override) and counts the cap in charged - rand. AI endpoints are `/api/v2` only. Check Claude Haiku 5.5's current prices before setting - the markup and caps. -3. **Clean-ups before or with 2.0:** - - Turn the React Compiler lint rules back to errors (see [Next.js 16](#nextjs-16-1515)) — every - screen is on v2 now, but they're still `warn` in `frontend/eslint.config.mjs`. - - `node-fetch` is still listed in `backend/package.json` though nothing in `src/` uses it — - remove it. - - Password hashing upgrade with rehash-on-login (roadmap §14) isn't done: still `bcryptjs`. - Decide whether it's in 2.0. -4. **Later:** move from ExcelTS — deprecated in favour of `documonster` by the same author - (pre-1.0 in Oct 2026) — once documonster is stable. After 1.51.7 has run everywhere, the old - `pgboss` schema can be dropped (`DROP SCHEMA pgboss CASCADE;`). + rand. AI endpoints are `/api/v2` only. The model is set on the Hub (Settings → AI); its list + prices live in `events-hub/backend/src/utils/aiModels.js`. +3. **Later (2.x):** move the v1 controllers behind `v1Route` into TypeScript services (the v2 API + doesn't change); remove the handlers no v2 route uses any more (e.g. the v1 scan handler and + `v1ScanResponse`, `v1Status` in `services/errors.ts`). Move from ExcelTS to `documonster` once + it is stable. After 1.51.7 has run everywhere, drop the old `pgboss` schema + (`DROP SCHEMA pgboss CASCADE;`). Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026-10-28). @@ -117,8 +122,8 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 - **Changelog:** add entries to `[Unreleased]` as you go, in plain language. CHANGELOG.md is the full log; WHATS-NEW.md is what churches see before updating (the Hub reads it from main every 15 minutes, for tagged versions only and sets the latest version from the tags — nothing to do in the Hub). -- **Docs to keep in step:** CHANGELOG.md, FEATURES.md, README.md, SETTINGS.md, - backend/API_DOCUMENTATION.md, the `/docs` route list in `backend/src/app.js` (v2 documents itself), and +- **Docs to keep in step:** CHANGELOG.md, FEATURES.md, README.md, SETTINGS.md (the API documents + itself at `/docs/v2`; `backend/API_DOCUMENTATION.md` only points there), and in-app help in `frontend/src/content/help/` (register new pages in `registry.ts`). - **Prisma migrations:** `npx prisma migrate dev --create-only --name x` against a local DB. Prisma 7 keeps adding an unrelated `_EventNotifyRecipients` primary-key/index @@ -573,10 +578,27 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 - Turbopack for dev and build (the default). Lint with `npm run lint` / `npx eslint src` (`next lint` is gone). There's no middleware/proxy file — add `src/proxy.ts` (Next 16's name) only if needed. -- **React Compiler lint rules are warnings, not errors** (`eslint.config.mjs`): 181 existing places, - mostly `useEffect(() => { load(); }, [...])`. The plan was to fix them as each screen moved onto - v2; every screen is on v2 now (1.51.15) but the rules are still `warn` — fix what's left and turn - them back to errors before or with 2.0. Don't add new ones. +- **React Compiler lint rules are errors** again (2.0; they were warnings from 1.51.5 with 181 + places to fix). How the code meets them — `frontend/src/lib/hooks.ts`: + - **State that follows other state or props** ("when the event changes, start the form again", + "each time the popup opens, clear it"): `useStateSync(update, deps)` — updates while rendering + (React's "adjusting state when a prop changes"). Deps must be stable values: a new array or + object each render loops (e.g. key on `campuses[0]?.id`, not the list). Prefer computing in + render, or setting it in the event handler that causes the change. + - **Loading from the API or reading the browser** (localStorage, the URL, a cookie, browser + events) and setting state from it: `useExternalEffect(run, deps)` — `useEffect` under a name that + says why. Both hooks' deps are checked by exhaustive-deps (`additionalHooks` in + `eslint.config.mjs`); to reload when something not used in the body changes, name it inside + (`void user;`). + - **Search results that clear when the box is emptied:** don't clear them in the effect — show + `query ? results : []` and let the effect only set state when the answer comes. + - **Time:** `useNow()` in client components (re-renders every minute); server components may + call `Date.now()` with the disable comment that says why (one render per request). + - **Navigation:** `useRouter().push()`; `hardNavigate()` (`lib/navigation.ts`) only where the + whole app must start again (signing out, impersonation, the 2FA redirect in `lib/api.ts`); + `window.location.assign(url)` for payment providers. + - The one deliberate exception is `useAnchorRect` (events page): measuring the DOM in + `useLayoutEffect` before paint. - `eslint-config-next` 16's bundled plugins (react, import, jsx-a11y) don't list ESLint 10 as a peer yet; they work, and npm notes the override. Revisit when they publish ESLint 10 support. @@ -633,6 +655,34 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 `utils/webhooks.js`; `tests/webhooks.test.js` fails if an example and `buildPayload` differ in shape. +## v1 removed (2.0) + +- `/api/…` answers **410** `API_V1_REMOVED` (`v1Removed` in `src/v2/links.ts`), except what outside + senders still use: `/api/webhooks/yoco|payfast|whatsapp` (`routes/webhookRoutes.js`, before the + JSON parser), WAWP's oldest `/api/whatsapp/webhook` and a mail app's one-click POST to + `/api/privacy/unsubscribe/:token/one-click` (`legacyV1Router`), and the 308s for links in sent + messages (`legacyLinkRedirects`). `/docs` redirects to `/docs/v2`. +- Only three v1 route files are left: `webhookRoutes.js`, and `dashboardRoutes.js` / + `savedFilterRoutes.js`, whose handlers v2 runs as routers. The controllers stay — `v1Route` runs + them behind v2 routes. +- **Path lists name v2 paths:** `hub/readOnly.js` (add any new "create" route there, with a test in + `tests/hub.test.js`, which also checks each pattern is a real route), `ALLOWED_WRITES` in + `utils/impersonation.js`. +- **Campus scope test** is `tests/v2CampusScope.test.ts`: every staff/supervisor v2 route has a + marked middleware (`scopeEvent`, `scopeBody`, `scopeList`, `campusIndependent`…) or is listed in + `CHECKED_IN_HANDLER` because its service checks campuses itself. +- e2e calls v2 only: `v2(page, role, method, url, body)` in `e2e/fixtures.ts` returns `data`. + Playwright waits for `/api/v2/setup/needed`. + +## Passwords (2.0) + +- `src/config/auth.js`: `hashPassword` is Argon2id (`@node-rs/argon2`, 19 MiB, 2 passes, 1 lane — + OWASP's minimum; prebuilt binaries, nothing to compile). `comparePassword` checks Argon2 and the + bcrypt hashes from before 2.0 (`bcryptjs` stays for that). `needsRehash` is true for bcrypt or + weaker Argon2 settings; `logIn` (`services/auth.ts`) saves a new hash after a right password. +- Raising the settings later: change `ARGON2` — everyone is re-hashed at their next sign-in. + Tests: `tests/passwords.test.js`, and the re-hash in `tests/accountEnumeration.test.ts`. + ## Known gaps / follow-ups - WhatsApp STOP only works once someone pastes the webhook URL from Site settings → WhatsApp diff --git a/apps/events/docs/ROADMAP-v2.md b/apps/events/docs/ROADMAP-v2.md index c4720f9..8b1129c 100644 --- a/apps/events/docs/ROADMAP-v2.md +++ b/apps/events/docs/ROADMAP-v2.md @@ -11,9 +11,20 @@ sold — trustworthy (POPIA), flexible (multi-day events, several payment providers), maintainable (tests, CI, typed backend, versioned API), and with **AI helpers** as the headline feature (§15). -**Status (2026-10-30):** all features in this document are approved, and everything before 2.0.0 -has shipped (1.32.0 – 1.51.17). **Next: 2.0.0** — AI helpers (§15) and v1 removed. The full -version list is in [HANDOVER.md](./HANDOVER.md) and the [build order](#suggested-build-order) below. +**Status (2026-11-02):** everything in this document has shipped — 1.32.0 – 1.52.3, then +**2.0.0 (released 2026-11-02)**, built on `release/2.0` in parts — except the marketing site +(§17), which lives in its own repo and waits on the questions under "Still open": + +| # | Part | Where | State | +|---|------|-------|-------| +| 1 | AI proxy: key, metering in rand, caps, markup, usage views; model list with prices (Sonnet 5.5 default) | Hub 1.6.0 – 1.6.1 (`events-hub`) | ✅ tagged; real Claude calls tested 2026-10-30 | +| 2 | AI plumbing: `/api/v2/ai/status`, usage, Site settings → AI, ``, `useAiStatus()`, `AiCall` log, Anthropic operator entry | 2.0.0 | ✅ | +| 3 | The five helpers (§15) with their buttons, an eval set, privacy notice text | 2.0.0 | ✅ eval 19/19 through a local Hub (2026-10-30) | +| 4 | v1 removed (webhook paths and old message links keep working); clean-ups: Argon2id passwords with rehash-on-login, `node-fetch` gone, React Compiler lint rules back to errors | 2.0.0 | ✅ | +| 5 | Migration guide (`MIGRATING-TO-2.md`), docs | 2.0.0 | ✅ | +| 6 | Marketing site: Cross Code with a Cross Events page (§17) | its own repo | to do — repo, domain, hosting, prices and contact route still to decide | + +The full version list is in [HANDOVER.md](./HANDOVER.md) and the [build order](#suggested-build-order) below. - **Multi-day events** (§1): 1.33.0 phase A (sessions, late joining, per-session check-in, attendance register, reminders, certificates); 1.35.0 phase B (pick sessions, per-session @@ -68,8 +79,9 @@ Removed from scope (2026-10-28): Wallet passes (§7) and languages (§10). 14. [Foundations (platform work)](#14-foundations-platform-work) 15. [AI helpers (2.0 headline)](#15-ai-helpers-20-headline) 16. [AI: later stages](#16-ai-later-stages) -17. [Suggested build order](#suggested-build-order) -18. [Decisions](#decisions-2026-10-22) +17. [Marketing site (Cross Code)](#17-marketing-site-cross-code) +18. [Suggested build order](#suggested-build-order) +19. [Decisions](#decisions-2026-10-22) --- @@ -833,7 +845,7 @@ keep adding to. | Split big controllers | `registrationController` (2.3k lines), `eventController`, `paymentController` → services by domain. Done **as each feature touches them**, not as a big-bang rewrite. Partly done (1.51.1 – 1.51.10); the handlers behind `v1Route` are a 2.x clean-up | | TypeScript backend ✅ | Incremental (`allowJs`), new code in TS first; share zod schemas/types with the frontend (1.51.0) | | API v2 ✅ | `/api/v2` with consistent errors, pagination and an OpenAPI spec (replaces the hand-written API docs). `/api` (v1) kept during the transition; every endpoint on v2 since 1.51.16 | -| Dependencies | Express 5 ✅ (1.51.3); native `fetch` ✅ (nothing uses `node-fetch` any more — it's still in `backend/package.json`, to remove); password hashing upgrade with rehash-on-login — **not done** (still `bcryptjs`), decide whether it's in 2.0 | +| Dependencies | Express 5 ✅ (1.51.3); native `fetch` ✅ (`node-fetch` removed in 2.0); password hashing ✅ in 2.0 — Argon2id (`@node-rs/argon2`), bcrypt hashes re-hashed at the next sign-in | --- @@ -860,14 +872,18 @@ never saves, sends or publishes by itself. ### Provider and model -- **One provider: Claude (Anthropic), model Claude Haiku 5.5** — the cheapest - current model ($0.10 per million input tokens, $0.50 per million output, for - prompts under 100K tokens; prices as of 2026-10 — **check them against Anthropic's pricing - page before setting the markup and caps**). Good enough for drafting and - summarising; a helper can move to a bigger model later if quality needs it. -- **Rough cost:** a helper call is ~2,000–10,000 tokens in and ~500 out, so well under - US$0.002 per click — about R1.50–R3 per thousand clicks. Fixed instructions are - prompt-cached, which makes repeat calls cheaper still. +- **One provider: Claude (Anthropic), model Claude Sonnet 5.5** for every helper (decided + 2026-10-30) — $2 per million input tokens, $10 per million output (October 2026 list prices). + First planned as Haiku 5.5 ($0.10 / $0.50) for cost; a trial of all five helpers on both + (2026-10-30) found Haiku wrong on a report figure, over-counting feedback themes and misspelling + words in messages, while Sonnet was right on all of them. One model for all helpers, no + per-helper choice. The model is a setting on the Hub (Settings → AI: a list with prices filled + in, Hub 1.6.1), so changing it later needs no Cross Events release. +- **Measured cost** (trial, charged at R17/$ and 5% markup): R0.02 – R0.31 per use with Sonnet — + a WhatsApp message about R0.02, a report summary R0.17 – R0.22, a full event draft with costs + R0.31. A typical church month (10 event drafts, 20 messages, 20 text improvements, 10 reports, 4 + feedback summaries) comes to about R8.33, so a R50 allowance covers it about 6 times. Fixed + instructions are prompt-cached, which makes repeat calls cheaper still. - Structured output (a JSON schema) for "Draft an event", so the reply maps straight onto the event form and is validated before it's shown. @@ -940,6 +956,23 @@ an install (one leaked install would leak it for everyone), so: looks like) to check quality when changing the prompt or model. - Help content, audit log entries (AI settings changed), CHANGELOG, FEATURES.md, SETTINGS.md. +### Progress (2026-10-30) + +- **Done — Hub 1.6.0:** `POST /api/installs/ai/status` and `/api/installs/ai/complete` (protocol §3b); + the worst case of each call held against the cap in a locked transaction; Settings → AI (key, + model, prices, exchange rate, default markup, test button, use per site); markup override per + licence; AI use (real cost, charged, profit) on the install page. Tested with real calls: a plain + message (118 tokens in, 70 out, ~1.3 s) and a JSON-schema event draft (483 in, 95 out, ~3 s), each + charged a fraction of a cent (R0.0008 – R0.0017 at R17/$ and 5% markup). +- **Done — Cross Events, `release/2.0`:** `backend/src/ai/` (status from the licence token, then + the Hub, cached a minute; per-helper switches; per-person daily limit; `AiCall` log; 80% email), + `/api/v2/ai/status`, `/ai/usage`, `/ai/settings`, the `UNAVAILABLE` (503) error code, + `frontend/src/lib/ai.ts` (`runAi`, which posts to `/api/v2/ai/`), + `useAiStatus()`, `` / ``, Site settings → AI. +- **Next:** the helpers in `backend/src/ai/helpers.ts` (prompt, schema, `maxTokens`, and what each + sends — no personal information), their `/api/v2/ai/` routes, the buttons on the five + screens, the eval set, and the privacy notice text (a `BUILT_IN_UPDATES` entry). + --- ## 16. AI: later stages @@ -993,6 +1026,25 @@ income justify the hardware: --- +## 17. Marketing site (Cross Code) + +Part of 2.0 (decided 2026-10-30): a **simple static HTML site** for selling, not part of the app. + +- **Cross Code** (Joshua's company) is the main site: who we are, what we make, contact. +- **Cross Events** has its own page: what it does for a church (registrations and payments, + multi-day events, kids check-in, volunteer rosters, series and season passes, campuses, POPIA + toolkit, the AI helpers), how it's set up (one site and database per church, updates on request, + support through the Hub), and how to get in touch for a licence. +- **Cross Events is the only product on sale for now.** The site is laid out so more products can + be added later — planned: a **church app** and a **full church website** — without a redesign + (shown as "coming later" at most, until they exist). +- Plain HTML and CSS (no build step, no framework), fast on a phone, no tracking cookies. +- **To decide before building:** the repository (its own, e.g. `joshua/crosscode-site`, not this + one), the domain(s) (e.g. crosscode.co.za, with Cross Events at /cross-events or its own domain), + hosting, pricing shown or "contact us", and the contact route (email address or a form). + +--- + ## Suggested build order | Phase | Version | Features | Why | @@ -1010,7 +1062,7 @@ income justify the hardware: | 10 | 1.49.0 ✅ – 1.49.2 ✅, 1.50.0 ✅, 1.50.1 ✅, 1.50.2 ✅ | Admin dashboard/Ctrl+K/bulk actions/saved filters, Accessibility pass, pagination and search on long lists, event picker and webhook guide (Afrikaans removed from scope) | Polish before the big release | | 11 | 1.51.0 ✅, 1.51.1 ✅, 1.51.2 ✅, 1.51.3 ✅ | TypeScript backend + OpenAPI + `/api/v2` alongside v1: 1.51.0 foundations (build, launcher, route declarations, errors, paging, OpenAPI at `/docs/v2`, first read endpoints); 1.51.1 registrations and payments as TS services, typed frontend calls; 1.51.2 check-in and accounts; 1.51.3 Express 5, the scanner on v2, v1 deprecation headers, v2-shaped shared middleware | The breaking-change groundwork | | 11b | 1.51.4 ✅ – 1.51.16 ✅ | **Every endpoint on v2 before 2.0** (decided 2026-10-29): 1.51.4 dependency audit and Node 24 LTS; 1.51.5 Next.js 16 and ESLint 10 (ESLint 9 is out of support); 1.51.6 the complete command palette and ExcelTS instead of exceljs; 1.51.7 setting events up (the staff list, create, change, deactivate, copy-from, notification recipients) and pg-boss 11; 1.51.8 the rest of event set-up (the event in full, ticket options and variants, attachments, sections, costs, uploads, calendar file, alias); 1.51.9 series, season passes, bundles, coupons and campuses; 1.51.10 managing registrations (the staff lists, status, at the door, bulk actions, items, coupons, attendees, attendee forms); 1.51.11 money, staff side (payments, cashup, provider transactions, waitlist, sponsorship, consent, form builder, feedback); 1.51.12 tickets and attendance, staff side (tickets, scan locks, attendance, allocations); 1.51.13 kids check-in and volunteer rosters; 1.51.14 people and messaging (users, WhatsApp, broadcasts, scheduled emails, automations, banner, saved filters, dashboard, stats, analytics, reports); 1.51.15 privacy and admin (privacy, admin, settings, setup, Hub, outbound webhooks, backups); 1.51.16 **incoming webhooks and links in sent messages**: Yoco, PayFast and WAWP webhooks and the links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds, waitlist offers) get v2 URLs — new messages and provider registrations use them, and the v1 paths keep answering (links by a 308 redirect to v2, provider webhooks handled by the same code, since providers may not follow a redirect on a POST). Each puts its area's endpoints on v2 (1.51.1 – 1.51.10 by moving the logic into TS services; from 1.51.11 by `v1Route`, which runs the v1 handler behind a v2 route — moving those handlers into TS services is a 2.x clean-up that doesn't change the API), its screens onto `apiV2`, and its v1 routes into `SUCCESSORS`. Then 1.51.17, a security fix (forgot password and sign-in don't reveal accounts) | 2.0 can then remove v1 | -| 12 | **2.0.0** | **AI helpers** (§15 — headline feature: draft an event, summarise reports and feedback, draft messages, improve text; through the Hub with a rand cap per licence), v1 removed (all of it is on v2 by then; the old webhook URLs and links already sent in messages keep forwarding to v2), migration guide, marketing site/docs for selling | The release. AI needs the Hub (phase 6) for the key, metering and caps | +| 12 | **2.0.0** ✅ | **AI helpers** (§15 — headline feature: draft an event, summarise reports and feedback, draft messages, improve text; through the Hub with a rand cap per licence), v1 removed (all of it is on v2 by then; the old webhook URLs and links already sent in messages keep forwarding to v2), migration guide, docs, and the marketing site (§17: a static Cross Code site with a Cross Events page). Released 2026-11-02 (built on `release/2.0` in parts); the marketing site follows in its own repo | The release. AI needs the Hub (phase 6) for the key, metering and caps | Each phase should add matching help content (`frontend/src/content/help/`), audit log entries, Jest tests, a CHANGELOG entry, and updates to FEATURES.md @@ -1045,10 +1097,13 @@ feature. | — | Income in the heartbeat | Included, as **ranges** only (R0–R1 000, R1 001–R5 000, …), never exact amounts (2026-10-23) | | — | Licence plans | One plan for now (2026-10-23) | | — | AI in 2.0 | The **headline feature of 2.0**: one-button helpers only (draft an event, summarise reports and feedback, draft messages, improve text) — no chat yet (2026-10-24) | -| — | AI provider and key | One provider, **Claude** (Haiku 5.5 to start, for cost). Joshua provides the key; installs call AI **through the Hub**, which holds the key and meters usage (2026-10-24) | +| — | AI provider and key | One provider, **Claude**. Joshua provides the key; installs call AI **through the Hub**, which holds the key and meters usage (2026-10-24). Model: **Sonnet 5.5 for every helper** (2026-10-30, after the Haiku/Sonnet trial; was Haiku 5.5 for cost), chosen on the Hub | | — | AI cost limits | A **monthly rand cap per install**, set in the Hub per licence to match what the church pays; admins see their usage in Site settings → AI (2026-10-24) | | — | v1 in 2.0 | **Every endpoint moves to v2 before 2.0** (1.51.7 – 1.51.16, by area), then 2.0 removes v1. Changed the same day from "retire only what's replaced". Incoming webhooks (Yoco, PayFast, WAWP) and links in emails and WhatsApp (unsubscribe, consent, ticket transfer, calendar feeds) also get v2 URLs (1.51.16); their v1 paths keep working — links redirect (308) to v2, provider webhooks are handled by the same code — because old messages and provider registrations still use them (2026-10-29) | | — | AI buttons and markup | AI buttons show only when the licence's monthly cap is **above R0**. When the cap is reached they stay visible but **disabled** until next month or until the cap is raised. Usage is charged at the real cost **plus a markup %** set in the Hub (a default, plus an override per licence). The markup covers small overruns and is the profit. The cap is counted in charged rand, and each call is checked against its worst-case cost before it's sent (2026-10-29) | +| — | Building 2.0 | On a `release/2.0` branch with a WIP commit per part, tagged 2.0.0 only when everything is in; the Hub's AI proxy ships first as its own release (Hub 1.6.0) (2026-10-30) | +| — | Marketing site | Part of 2.0: a simple static HTML site — Cross Code as the main site, with a page for Cross Events, the only product on sale for now. Laid out to add a church app and a full church website later. Repo, domain and hosting still to decide (2026-10-30) | +| — | 2.0 clean-ups | All in 2.0 (2026-11-02): v1 removed, Argon2id passwords with rehash-on-login, `node-fetch` removed, React Compiler lint rules back to errors | | — | AI later | Ask AI (read-only, tools only), help/navigation assistant, actions with confirmation, more helpers, and long-term **self-hosted** AI behind the same Hub endpoint — not tied to versions (2026-10-24) | | — | POPIA: message kinds | Bulk messages are either **Event updates** (to registrants — still sent after unsubscribing) or **News & announcements** (marketing — opt-in, one-click unsubscribe). Every bulk email links to the preferences (2026-10-23) | | — | POPIA: existing users | Kept opted in to news (logged as "existing account"), asked once at their next login to confirm or opt out. New sign-ups choose with an unticked box (2026-10-23) | @@ -1070,4 +1125,5 @@ feature. ## Still open -Nothing for now. +- **Marketing site (§17):** repository, domain(s), hosting, whether prices are shown, and the + contact route. diff --git a/apps/events/docs/hub-protocol.md b/apps/events/docs/hub-protocol.md index d4f143c..342c101 100644 --- a/apps/events/docs/hub-protocol.md +++ b/apps/events/docs/hub-protocol.md @@ -178,6 +178,65 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) history. Rate-limited with update requests. A Hub older than 1.4.0 answers `404 NOT_FOUND`. - **"Not now"** (no reminders until the next version) stays on the install; the Hub isn't told. +## 3b. AI (Cross Events 2.0, Hub 1.6.0) + +Installs never hold the Claude API key. Each AI helper call goes through the Hub, which adds the +key, checks the licence's monthly cap, calls Claude and meters the call. Both requests are signed +exactly like the heartbeat. The install keeps its prompts; the Hub stores **no prompt or response +text** — only the install, helper name, tokens, cost and time. + +### Status + +``` +POST /api/installs/ai/status +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ "protocolVersion": 1 } +→ 200 { "enabled": true, "capReached": false, "capCents": 5000, "usedCents": 812.4, + "usedPercent": 16, "renewsOn": "2026-12-01" } +``` + +- **`enabled: false`** — hide the AI buttons everywhere: the licence's cap is R0, the licence isn't + active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up. +- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it + renews on 1 December"). Reached means there isn't room left for even a small call. +- Amounts are cents (rand) as **charged** to the church, with fractions (a call costs a fraction of a + cent). The month is South African time; `renewsOn` is the 1st of the next month. + +### A helper call + +``` +POST /api/installs/ai/complete +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ + "protocolVersion": 1, + "helper": "draft_event", // lower-case name, for usage reports + "system": "…", // the helper's fixed instructions (cached by Claude) + "input": "…", // this request's text + "schema": { … }, // optional JSON schema: the reply is JSON in that shape + "maxTokens": 2000, // 1–8000 + "effort": "low" // optional: low (default) | medium | high +} +→ 200 { "output": "…" | { … }, // text, or the parsed JSON when a schema was given + "usage": { "inputTokens": 1840, "outputTokens": 420 }, + "chargedCents": 0.31, + "status": { …as above… } } +``` + +- **Errors** are `{ code, message, status }` — `status` is the new AI status, so buttons can disable + straight after the call that used up the allowance: + - `402 AI_CAP_REACHED` — this call could pass the cap (checked before calling Claude). + - `403 AI_OFF` (cap R0) · `403 LICENCE_INACTIVE` · `503 AI_NOT_CONFIGURED` (Hub not set up). + - `422 AI_REFUSED` — Claude declined. `502 AI_INCOMPLETE` — the answer hit `maxTokens`. + `502 AI_FAILED` — not usable (e.g. JSON in the wrong shape). These still cost what was used. + - `503 AI_BUSY` / `503 AI_UNAVAILABLE` — Claude unreachable or rate-limited; nothing is charged. + - `400 BAD_REQUEST`, `413 AI_INPUT_TOO_LARGE` (about 90 000 tokens), and the §3 errors. +- **Metering:** real cost = tokens × the model's price × the exchange rate set in the Hub; charged = + real × (1 + markup). The cap counts charged rand. Before calling Claude the Hub holds the worst + case (an over-estimate of the prompt, plus `maxTokens`) against the cap in one transaction per + install, so calls at the same moment can't pass it; afterwards the hold becomes the real amount. +- Rate-limited to 60 a minute per IP (against runaway loops; money is limited by the cap). +- A Hub older than 1.6.0 answers `404 NOT_FOUND`: the install treats that as "AI off". + ## 4. Licence token `hel1..` — `payload` is base64url JSON, `signature` is the base64url @@ -195,7 +254,7 @@ Ed25519 signature of the ASCII string `hel1.`. "graceDays": 14, "issuedAt": "2026-10-24T08:15:00.000Z", "validUntil": "2026-11-23T08:15:00.000Z", // issuedAt + 30 days - "limits": { "aiMonthlyCapCents": 0 } + "limits": { "aiMonthlyCapCents": 0 } // the AI cap (§3b); 0 = AI off } ``` @@ -221,8 +280,3 @@ grace starts). Blocking the Hub can't keep a suspended licence active for more t fields to a heartbeat or a token doesn't need a new version — both sides ignore fields they don't know. - The Hub accepts protocol `N` and `N-1`; anything else is `400 UNSUPPORTED_PROTOCOL`. - -## 6. Later (not in v1) - -- **AI proxy** (Cross Events 2.0): `POST /api/ai/complete`, signed like the heartbeat; the Hub holds - the Claude API key, meters each call in rand and enforces `limits.aiMonthlyCapCents`. diff --git a/apps/events/e2e/api-v2.spec.ts b/apps/events/e2e/api-v2.spec.ts index b0240ff..8357b93 100644 --- a/apps/events/e2e/api-v2.spec.ts +++ b/apps/events/e2e/api-v2.spec.ts @@ -68,7 +68,7 @@ test.describe("API v2", () => { // A free ticket for the user, then check it in twice through v2. const event = (await (await request.get(`${API}/api/v2/events/${seed().events.free}`)).json()).data; await request.post(`${API}/api/v2/registrations`, { headers, data: { eventId: event.id, options: [{ eventOptionId: event.ticketOptions[0].id, quantity: 1 }] } }); - const tickets = await (await request.get(`${API}/api/tickets/mytickets`, { headers })).json(); + const tickets = (await (await request.get(`${API}/api/v2/me/tickets`, { headers })).json()).data; const qr = tickets.find((t: { eventId: string; qrCode: string }) => t.eventId === event.id).qrCode; const staff = { Authorization: `Bearer ${seed().users.staff.token}` }; @@ -84,17 +84,14 @@ test.describe("API v2", () => { expect((await (await request.post(`${API}/api/v2/checkin/NOT-A-CODE`, { headers: staff, data: {} })).json()).error.code).toBe("NOT_FOUND"); }); - test("v1 endpoints with a v2 version say so", async ({ request }) => { + test("v1 is gone in 2.0, except webhooks and links in messages already sent", async ({ request }) => { const v1 = await request.get(`${API}/api/events`); - expect(v1.headers()["deprecation"]).toMatch(/^@\d+$/); - expect(v1.headers()["link"]).toBe(`; rel="successor-version"`); - const all = await request.get(`${API}/api/events/all`, { headers: { Authorization: `Bearer ${seed().users.staff.token}` } }); - expect(all.headers()["link"]).toBe(`; rel="successor-version"`); - expect((await request.get(`${API}/api/settings/needs-setup`)).headers()["link"]).toBe(`; rel="successor-version"`); - // Incoming webhooks: the v1 address still works (same handler) and names its v2 one. - const hook = await request.post(`${API}/api/webhooks/whatsapp`, { data: {} }); - expect(hook.status()).toBe(200); - expect(hook.headers()["link"]).toBe(`; rel="successor-version"`); + expect(v1.status()).toBe(410); + expect((await v1.json()).code).toBe("API_V1_REMOVED"); + expect((await request.post(`${API}/api/users/login`, { data: {} })).status()).toBe(410); + // Incoming webhooks: the v1 addresses still reach the same handlers. + expect((await request.post(`${API}/api/webhooks/whatsapp`, { data: {} })).status()).toBe(200); + expect((await request.post(`${API}/api/whatsapp/webhook`, { data: {} })).status()).toBe(200); expect((await request.post(`${API}/api/v2/webhooks/whatsapp`, { data: { event: "noop" } })).status()).toBe(200); // A calendar link in an email already sent goes to its v2 address. const ics = await request.get(`${API}/api/events/${seed().events.conference}/ics`, { maxRedirects: 0 }); @@ -102,6 +99,9 @@ test.describe("API v2", () => { expect(ics.headers()["location"]).toBe(`/api/v2/events/${seed().events.conference}/calendar.ics`); const followed = await request.get(`${API}/api/events/${seed().events.conference}/ics`); expect(followed.headers()["content-type"]).toContain("text/calendar"); + // The old API reference sends people to the v2 one. + const docs = await request.get(`${API}/docs`, { maxRedirects: 0 }); + expect(docs.headers()["location"]).toBe("/docs/v2"); }); test("staff list every event; supervisors create, change and admins deactivate", async ({ request }) => { diff --git a/apps/events/e2e/bulk.spec.ts b/apps/events/e2e/bulk.spec.ts index 6033be7..13203ed 100644 --- a/apps/events/e2e/bulk.spec.ts +++ b/apps/events/e2e/bulk.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, loginAs, api } from "./fixtures"; +import { test, expect, loginAs, api, v2 } from "./fixtures"; // Bulk actions on the registrations list (1.49.1): tick several, mark them paid, move them to // another ticket, cancel — each through the same rules as one at a time. @@ -14,15 +14,15 @@ test.describe.serial("bulk actions on registrations", () => { test.beforeAll(async ({ browser }) => { const page = await browser.newPage(); const start = new Date(Date.now() + 20 * 864e5); - event = await api(page, "admin", "POST", "/api/events", { + event = await v2(page, "admin", "POST", "/api/v2/events", { title: "E2E Bulk Night", startDate: start.toISOString(), endDate: new Date(start.getTime() + 3 * 3600e3).toISOString(), price: 100, location: "Church hall", }); - const full = await api(page, "admin", "GET", `/api/events/${event.id}`); + const full = await v2(page, "admin", "GET", `/api/v2/events/${event.id}/full`); main = full.eventOptions!.find(o => o.isMainTicket)!.id; - vip = (await api<{ id: string }>(page, "admin", "POST", `/api/events/${event.id}/options`, { name: "VIP", price: 150, isMainTicket: true })).id; + vip = (await v2<{ id: string }>(page, "admin", "POST", `/api/v2/events/${event.id}/ticket-options`, { name: "VIP", price: 150, isMainTicket: true })).id; for (const role of ["staff", "supervisor", "user"] as const) { - regs.push((await api<{ id: string }>(page, role, "POST", "/api/registrations", { eventId: event.id, options: [{ eventOptionId: main, quantity: 1 }] })).id); + regs.push((await v2<{ id: string }>(page, role, "POST", "/api/v2/registrations", { eventId: event.id, options: [{ eventOptionId: main, quantity: 1 }] })).id); } await page.close(); }); @@ -45,7 +45,7 @@ test.describe.serial("bulk actions on registrations", () => { await expect(page.getByTestId("bulk-result")).toContainText("3 done"); for (const id of regs) { - const r = await api(page, "admin", "GET", `/api/registrations/${id}`); + const r = await v2(page, "admin", "GET", `/api/v2/registrations/${id}/full`); expect(r.status).toBe("paid"); expect(r.payments?.map(p => [p.amount, p.method])).toEqual([[100, "cash"]]); } @@ -64,7 +64,7 @@ test.describe.serial("bulk actions on registrations", () => { await bar.getByRole("button", { name: /Move to another ticket/ }).click(); await expect(page.getByTestId("bulk-result")).toContainText("2 done"); - const moved = await Promise.all(regs.map(id => api(page, "admin", "GET", `/api/registrations/${id}`))); + const moved = await Promise.all(regs.map(id => v2(page, "admin", "GET", `/api/v2/registrations/${id}/full`))); const onVip = moved.filter(r => r.registrationOptions?.some(o => o.eventOptionId === vip)); expect(onVip).toHaveLength(2); // R150 now, R100 paid: they owe the difference. @@ -73,14 +73,14 @@ test.describe.serial("bulk actions on registrations", () => { await bar.getByRole("button", { name: "Clear selection" }).click(); const left = moved.find(r => !r.registrationOptions?.some(o => o.eventOptionId === vip))!; await page.getByRole("checkbox", { name: /^Select / }).nth(2).check(); - const selectedId = (await api(page, "admin", "GET", `/api/registrations/${left.id}`)).id; + const selectedId = (await v2(page, "admin", "GET", `/api/v2/registrations/${left.id}/full`)).id; expect(selectedId).toBe(left.id); const bar2 = page.getByTestId("bulk-bar"); await bar2.getByLabel("Bulk action").selectOption("cancel"); page.once("dialog", d => d.accept()); await bar2.getByRole("button", { name: /Cancel — 1/ }).click(); await expect(page.getByTestId("bulk-result")).toContainText("1 done"); - const cancelled = (await Promise.all(regs.map(id => api(page, "admin", "GET", `/api/registrations/${id}`)))).filter(r => r.status === "cancelled"); + const cancelled = (await Promise.all(regs.map(id => v2(page, "admin", "GET", `/api/v2/registrations/${id}/full`)))).filter(r => r.status === "cancelled"); expect(cancelled).toHaveLength(1); }); }); diff --git a/apps/events/e2e/campus-scoped.spec.ts b/apps/events/e2e/campus-scoped.spec.ts index 952bd92..66ebac6 100644 --- a/apps/events/e2e/campus-scoped.spec.ts +++ b/apps/events/e2e/campus-scoped.spec.ts @@ -1,13 +1,13 @@ -import { test, expect, seed, api, loginAs, API } from "./fixtures"; +import { test, expect, seed, api, loginAs, API, v2 } from "./fixtures"; // Campus-scoped staff (1.44.0): the seeded staff member and supervisor are limited to E2E South // for these tests; afterwards the limits are cleared and campuses turned off again. test.describe("campus-scoped staff", () => { test.beforeAll(async ({ browser }) => { const page = await browser.newPage(); - await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: true }); + await v2(page, "admin", "PUT", "/api/v2/campuses/enabled", { enabled: true }); for (const role of ["staff", "supervisor"] as const) { - await api(page, "admin", "PUT", `/api/users/${seed().users[role].id}`, { scopedCampusIds: [seed().campuses.south.id] }); + await v2(page, "admin", "PATCH", `/api/v2/users/${seed().users[role].id}`, { scopedCampusIds: [seed().campuses.south.id] }); } await page.close(); }); @@ -15,17 +15,17 @@ test.describe("campus-scoped staff", () => { test.afterAll(async ({ browser }) => { const page = await browser.newPage(); for (const role of ["staff", "supervisor"] as const) { - await api(page, "admin", "PUT", `/api/users/${seed().users[role].id}`, { scopedCampusIds: [] }); + await v2(page, "admin", "PATCH", `/api/v2/users/${seed().users[role].id}`, { scopedCampusIds: [] }); } - await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: false }); + await v2(page, "admin", "PUT", "/api/v2/campuses/enabled", { enabled: false }); await page.close(); }); test("the scanner refuses another campus's ticket and says which campus", async ({ page }) => { - const scan = (qr: string) => page.request.get(`${API}/api/tickets/scan-preview/${encodeURIComponent(qr)}`, { headers: { Authorization: `Bearer ${seed().users.staff.token}` } }); + const scan = (qr: string) => page.request.get(`${API}/api/v2/checkin/${encodeURIComponent(qr)}`, { headers: { Authorization: `Bearer ${seed().users.staff.token}` } }); const north = await scan(seed().northTicketQr); expect(north.status()).toBe(403); - expect((await north.json()).message).toBe("This ticket is for an event at E2E North."); + expect((await north.json()).error.message).toBe("This ticket is for an event at E2E North."); // The course is for all campuses, so it scans. expect((await scan(seed().course.qrCode)).status()).toBe(200); }); @@ -46,7 +46,7 @@ test.describe("campus-scoped staff", () => { }); test("another campus's registrations are not found for a scoped supervisor", async ({ page }) => { - const res = await page.request.get(`${API}/api/registrations/event/${seed().events.free}`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } }); + const res = await page.request.get(`${API}/api/v2/events/${seed().events.free}/registrations`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } }); expect(res.status()).toBe(404); }); }); diff --git a/apps/events/e2e/campuses.spec.ts b/apps/events/e2e/campuses.spec.ts index da2c53a..f2c800c 100644 --- a/apps/events/e2e/campuses.spec.ts +++ b/apps/events/e2e/campuses.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, api, API } from "./fixtures"; +import { test, expect, seed, api, API, v2 } from "./fixtures"; // Multi-campus. The campuses and the two events' campuses are seeded (e2e/support/prepare-db.js) // with campuses off; these tests turn them on, and off again afterwards so the other specs see a @@ -6,13 +6,13 @@ import { test, expect, seed, api, API } from "./fixtures"; test.describe("campuses", () => { test.beforeAll(async ({ browser }) => { const page = await browser.newPage(); - await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: true }); + await v2(page, "admin", "PUT", "/api/v2/campuses/enabled", { enabled: true }); await page.close(); }); test.afterAll(async ({ browser }) => { const page = await browser.newPage(); - await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: false }); + await v2(page, "admin", "PUT", "/api/v2/campuses/enabled", { enabled: false }); await page.close(); }); @@ -38,8 +38,8 @@ test.describe("campuses", () => { }); test("a campus with events can't be deleted", async ({ page }) => { - const res = await page.request.delete(`${API}/api/campuses/${seed().campuses.north.id}`, { headers: { Authorization: `Bearer ${seed().users.admin.token}` } }); + const res = await page.request.delete(`${API}/api/v2/campuses/${seed().campuses.north.id}`, { headers: { Authorization: `Bearer ${seed().users.admin.token}` } }); expect(res.status()).toBe(409); - expect((await res.json()).code).toBe("CAMPUS_HAS_EVENTS"); + expect((await res.json()).error.reason).toBe("CAMPUS_HAS_EVENTS"); }); }); diff --git a/apps/events/e2e/event-picker.spec.ts b/apps/events/e2e/event-picker.spec.ts index f2477bf..db80a5b 100644 --- a/apps/events/e2e/event-picker.spec.ts +++ b/apps/events/e2e/event-picker.spec.ts @@ -1,12 +1,12 @@ import AxeBuilder from "@axe-core/playwright"; -import { test, expect, loginAs, api } from "./fixtures"; +import { test, expect, loginAs, api, v2 } from "./fixtures"; // 1.50.2: event dropdowns are a searchable picker — upcoming events first, past ones a click // away, and typing searches them all. test.describe("event picker", () => { test("opens on upcoming events; past ones are behind a button or found by searching", async ({ page }) => { const start = new Date(Date.now() - 40 * 864e5); - await api(page, "supervisor", "POST", "/api/events", { + await v2(page, "supervisor", "POST", "/api/v2/events", { title: "E2E Picker Old Gathering", description: "A past event for the picker test.", price: 0, location: "1 Test Street, Pretoria", startDate: start.toISOString(), endDate: new Date(start.getTime() + 2 * 3600e3).toISOString(), }); diff --git a/apps/events/e2e/excel.spec.ts b/apps/events/e2e/excel.spec.ts index 3b16c4c..a673dff 100644 --- a/apps/events/e2e/excel.spec.ts +++ b/apps/events/e2e/excel.spec.ts @@ -16,7 +16,7 @@ async function open(body: Buffer) { test.describe("Excel exports", () => { test("a report with stats, a chart and a table", async ({ request }) => { - const res = await request.post(`${API}/api/reports/excel`, { + const res = await request.post(`${API}/api/v2/reports/excel`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` }, data: { title: "E2E Payments", @@ -36,7 +36,7 @@ test.describe("Excel exports", () => { }); test("the attendance register", async ({ request }) => { - const res = await request.get(`${API}/api/attendance/${seed().events.course}/export?format=xlsx`, { + const res = await request.get(`${API}/api/v2/events/${seed().events.course}/attendance/export?format=xlsx`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` }, }); expect(res.status()).toBe(200); diff --git a/apps/events/e2e/fixtures.ts b/apps/events/e2e/fixtures.ts index 80245ca..b26f686 100644 --- a/apps/events/e2e/fixtures.ts +++ b/apps/events/e2e/fixtures.ts @@ -52,6 +52,11 @@ export async function api(page: Page, role: Role, method: string, u return (text ? JSON.parse(text) : null) as T; } +/** Calls `/api/v2` as a seeded user and returns the answer's `data` (throws on an error, like `api`). */ +export async function v2(page: Page, role: Role, method: string, url: string, body?: unknown): Promise { + return (await api<{ data: T }>(page, role, method, url, body)).data; +} + /** Chooses an event in an EventPicker (the first on the page, or the one labelled `label`) by searching its title. */ export async function pickEvent(page: Page, title: string, label?: string) { const button = label ? page.getByRole("button", { name: new RegExp(`^${label}:`) }) : page.getByTestId("event-picker").first().getByRole("button").first(); diff --git a/apps/events/e2e/long-lists.spec.ts b/apps/events/e2e/long-lists.spec.ts index c5e8f2a..e2de3ea 100644 --- a/apps/events/e2e/long-lists.spec.ts +++ b/apps/events/e2e/long-lists.spec.ts @@ -1,10 +1,10 @@ -import { test, expect, seed, loginAs, api } from "./fixtures"; +import { test, expect, seed, loginAs, api, v2 } from "./fixtures"; // 1.50.1: long lists load a page (or just what's needed) at a time, with search and filters. test.describe("long lists", () => { test("Payments: today, recent and a person's payments for a refund", async ({ page }) => { // A donation recorded today for the seeded user (on an event no other test totals up). - await api(page, "supervisor", "POST", "/api/payments", { + await v2(page, "supervisor", "POST", "/api/v2/payments", { amount: 77, method: "cash", isDonation: true, eventId: seed().events.conference, userId: seed().users.user.id, }); @@ -21,11 +21,11 @@ test.describe("long lists", () => { test("Payments API: narrowing filters", async ({ page }) => { const userId = seed().users.user.id; - const mine = await api<{ data: { userId: string }[] }>(page, "supervisor", "GET", `/api/payments?userId=${userId}&limit=200`); + const mine = await v2<{ data: { userId: string }[] }>(page, "supervisor", "GET", `/api/v2/payments?userId=${userId}&limit=200`); expect(mine.data.length).toBeGreaterThan(0); expect(mine.data.every((p) => p.userId === userId)).toBe(true); - const unpaid = await api<{ status: string }[]>(page, "supervisor", "GET", "/api/registrations?unpaid=1"); + const unpaid = await v2<{ status: string }[]>(page, "supervisor", "GET", "/api/v2/registrations?unpaid=true"); expect(unpaid.every((r) => ["pending", "confirmed", "partial_paid"].includes(r.status))).toBe(true); }); @@ -44,7 +44,7 @@ test.describe("long lists", () => { }); test("Data requests: search", async ({ page }) => { - const res = await api<{ requests: unknown[]; total: number }>(page, "admin", "GET", "/api/privacy/requests?status=closed&search=nobody-matches-this-xyz"); + const res = await v2<{ requests: unknown[]; total: number }>(page, "admin", "GET", "/api/v2/privacy/requests?status=closed&search=nobody-matches-this-xyz"); expect(res.requests).toEqual([]); expect(res.total).toBe(0); }); diff --git a/apps/events/e2e/payfast.spec.ts b/apps/events/e2e/payfast.spec.ts index c870f6d..6e80f37 100644 --- a/apps/events/e2e/payfast.spec.ts +++ b/apps/events/e2e/payfast.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api } from "./fixtures"; +import { test, expect, seed, loginAs, api, v2 } from "./fixtures"; // Pays into a real PayFast sandbox account, so it needs one: // E2E_PAYFAST_MERCHANT_ID, E2E_PAYFAST_MERCHANT_KEY, E2E_PAYFAST_PASSPHRASE @@ -17,17 +17,17 @@ test.describe("PayFast", () => { test.skip(!PF.merchantId, "Set E2E_PAYFAST_* to test against a PayFast sandbox account"); test("choose PayFast on the pay page and land on PayFast's payment page", async ({ page }) => { - await api(page, "admin", "PUT", "/api/payfast/config", { ...PF, mode: "sandbox" }); + await v2(page, "admin", "PUT", "/api/v2/payments/payfast/config", { ...PF, mode: "sandbox" }); try { - await api(page, "admin", "PUT", "/api/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: true }] }); + await v2(page, "admin", "PUT", "/api/v2/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: true }] }); // A booking for the paid conference, then an online checkout for it - const event = await api(page, "staff", "GET", `/api/events/${seed().events.paid}`); + const event = await v2(page, "staff", "GET", `/api/v2/events/${seed().events.paid}/full`); const option = event.eventOptions.find((o) => o.isMainTicket)!; - const reg = await api(page, "staff", "POST", "/api/registrations", { eventId: seed().events.paid, options: [{ eventOptionId: option.id, quantity: 1 }] }); + const reg = await v2(page, "staff", "POST", "/api/v2/registrations", { eventId: seed().events.paid, options: [{ eventOptionId: option.id, quantity: 1 }] }); const origin = new URL(page.url() === "about:blank" ? "http://localhost:3100" : page.url()).origin; - const checkout = await api(page, "staff", "POST", "/api/payments/checkout", { - registrationId: reg.id, successUrl: `${origin}/payment/success`, cancelUrl: `${origin}/payment/cancel`, failureUrl: `${origin}/payment/failure`, + const checkout = await v2(page, "staff", "POST", `/api/v2/registrations/${reg.id}/checkout`, { + successUrl: `${origin}/payment/success`, cancelUrl: `${origin}/payment/cancel`, failureUrl: `${origin}/payment/failure`, }); // Yoco and PayFast are both on, so the payer chooses expect(checkout.provider).toBeNull(); @@ -53,8 +53,8 @@ test.describe("PayFast", () => { await expect(row.getByText("Not paid (yet)")).toBeVisible({ timeout: 30_000 }); await expect(page.getByText("No new payments found.")).toBeVisible(); } finally { - await api(page, "admin", "PUT", "/api/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: false }] }); - await api(page, "admin", "PUT", "/api/payfast/config", { merchantId: "", merchantKey: "", passphrase: "" }); + await v2(page, "admin", "PUT", "/api/v2/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: false }] }); + await v2(page, "admin", "PUT", "/api/v2/payments/payfast/config", { merchantId: "", merchantKey: "", passphrase: "" }); } }); }); diff --git a/apps/events/e2e/payments.spec.ts b/apps/events/e2e/payments.spec.ts index 042a67a..b89578a 100644 --- a/apps/events/e2e/payments.spec.ts +++ b/apps/events/e2e/payments.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api } from "./fixtures"; +import { test, expect, seed, loginAs, api, v2 } from "./fixtures"; type ProviderSetting = { id: string; label: string; enabled: boolean; configured: boolean }; @@ -20,28 +20,28 @@ test.describe("payment providers", () => { await expect(page.getByText(/Online payments are off/)).toBeVisible(); // A switched-off provider's settings are hidden await expect(page.getByRole("heading", { name: "Yoco payments" })).toBeHidden(); - const off = await api<{ providers: { id: string }[]; minimumAmount: number }>(page, "user", "GET", "/api/payments/providers"); + const off = await v2<{ providers: { id: string }[]; minimumAmount: number }>(page, "user", "GET", "/api/v2/payments/providers"); expect(off.providers).toEqual([]); expect(off.minimumAmount).toBe(15); await yoco.check(); await expect(yoco).toBeChecked(); await expect(page.getByRole("heading", { name: "Yoco payments" })).toBeVisible(); - const settings = await api<{ providers: ProviderSetting[] }>(page, "admin", "GET", "/api/payments/providers/settings"); + const settings = await v2<{ providers: ProviderSetting[] }>(page, "admin", "GET", "/api/v2/payments/providers/settings"); expect(settings.providers.find((p) => p.id === "yoco")?.enabled).toBe(true); } finally { // Leave Yoco on for the other tests. - await api(page, "admin", "PUT", "/api/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }] }); + await v2(page, "admin", "PUT", "/api/v2/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }] }); } }); test("with no provider on, nothing offers to pay online", async ({ page }) => { type EventWithOptions = { eventOptions: { id: string; isMainTicket: boolean }[] }; - const event = await api(page, "admin", "GET", `/api/events/${seed().events.paid}`); + const event = await v2(page, "admin", "GET", `/api/v2/events/${seed().events.paid}/full`); const option = event.eventOptions.find((o) => o.isMainTicket)!; - const reg = await api<{ id: string }>(page, "admin", "POST", "/api/registrations", { eventId: seed().events.paid, options: [{ eventOptionId: option.id, quantity: 1 }] }); + const reg = await v2<{ id: string }>(page, "admin", "POST", "/api/v2/registrations", { eventId: seed().events.paid, options: [{ eventOptionId: option.id, quantity: 1 }] }); - await api(page, "admin", "PUT", "/api/payments/providers/settings", { providers: [{ id: "yoco", enabled: false }, { id: "payfast", enabled: false }] }); + await v2(page, "admin", "PUT", "/api/v2/payments/providers/settings", { providers: [{ id: "yoco", enabled: false }, { id: "payfast", enabled: false }] }); try { await loginAs(page, "admin"); await page.goto(`/registration/success?registrationId=${reg.id}`); @@ -53,11 +53,11 @@ test.describe("payment providers", () => { await page.goto("/dashboard/user/donate"); await expect(page.getByText(/Online donations aren.t available/)).toBeVisible(); } finally { - await api(page, "admin", "PUT", "/api/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: false }] }); + await v2(page, "admin", "PUT", "/api/v2/payments/providers/settings", { providers: [{ id: "yoco", enabled: true }, { id: "payfast", enabled: false }] }); } // Back on (when Yoco is set up in this environment), the button returns - const on = await api<{ providers: unknown[] }>(page, "admin", "GET", "/api/payments/providers"); + const on = await v2<{ providers: unknown[] }>(page, "admin", "GET", "/api/v2/payments/providers"); if (on.providers.length > 0) { await page.goto(`/registration/success?registrationId=${reg.id}`); await expect(page.getByRole("button", { name: "Pay online" })).toBeVisible(); diff --git a/apps/events/e2e/pick-sessions.spec.ts b/apps/events/e2e/pick-sessions.spec.ts index 2627f58..2d5cb4f 100644 --- a/apps/events/e2e/pick-sessions.spec.ts +++ b/apps/events/e2e/pick-sessions.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api, pickEvent } from "./fixtures"; +import { test, expect, seed, loginAs, api, pickEvent, v2 } from "./fixtures"; type Registration = { id: string; eventId: string; user?: { name: string }; registrationOptions: { sessionId?: string | null; sessionIds?: string[]; priceSnapshot: number; quantity: number }[] }; type WaitlistEntry = { eventId: string; sessionId: string | null; quantity: number }; @@ -20,7 +20,7 @@ test.describe("pick sessions", () => { await page.getByRole("button", { name: "Register", exact: true }).click(); await page.waitForURL(/\/registration\/success/); - const regs = await api(page, "user", "GET", "/api/registrations/myregistrations"); + const regs = await v2(page, "user", "GET", "/api/v2/me/registrations/full"); const reg = regs.find((r) => r.eventId === seed().events.dropIn); expect(reg?.registrationOptions.filter((o) => o.sessionId)).toHaveLength(2); }); @@ -39,7 +39,7 @@ test.describe("pick sessions", () => { await page.getByRole("button", { name: "Register", exact: true }).click(); await page.waitForURL(/\/registration\/success/); - const regs = await api(page, "user", "GET", "/api/registrations/myregistrations"); + const regs = await v2(page, "user", "GET", "/api/v2/me/registrations/full"); const line = regs.find((r) => r.eventId === seed().events.conference)?.registrationOptions[0]; expect(line?.sessionId ?? null).toBeNull(); expect(line?.sessionIds).toHaveLength(2); @@ -58,7 +58,7 @@ test.describe("pick sessions", () => { await page.locator("form").filter({ hasText: "Join the waitlist" }).getByRole("button", { name: "Join waitlist" }).click(); await expect(page.getByText(/You're on the waitlist/)).toBeVisible(); - const mine = await api(page, "admin", "GET", "/api/waitlist/mine"); + const mine = await v2(page, "admin", "GET", "/api/v2/me/waitlist"); const entry = mine.find((e) => e.eventId === seed().events.dropIn); expect(entry?.sessionId).toBeTruthy(); expect(entry?.quantity).toBe(1); @@ -86,7 +86,7 @@ test.describe("pick sessions", () => { await page.getByRole("button", { name: "Confirm Registration" }).click(); await expect(page.getByText("Select Items")).toBeHidden(); - const regs = await api(page, "supervisor", "GET", `/api/registrations/event/${seed().events.dropIn}`); + const regs = await v2(page, "supervisor", "GET", `/api/v2/events/${seed().events.dropIn}/registrations`); const reg = regs.find((r) => r.user?.name === "Door Walk In"); expect(reg?.registrationOptions.filter((o) => o.sessionId)).toHaveLength(1); }); diff --git a/apps/events/e2e/privacy-notice.spec.ts b/apps/events/e2e/privacy-notice.spec.ts index effd3cf..cc03ff1 100644 --- a/apps/events/e2e/privacy-notice.spec.ts +++ b/apps/events/e2e/privacy-notice.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api, API, type Role } from "./fixtures"; +import { test, expect, seed, loginAs, api, API, type Role, v2 } from "./fixtures"; type Section = { id: string; title: string; body: string }; type Draft = { sections: Section[]; versions: { version: number; acceptances: number }[] }; @@ -13,12 +13,12 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { test.afterAll(async ({ request }) => { const tokens = [...(["admin", "supervisor", "staff", "user"] as Role[]).map(r => seed().users[r].token), seed().newsPromptUser.token, seed().noticeFirstUser.token]; for (const token of tokens) { - await request.post(`${API}/api/privacy/me/notice/accept`, { headers: { Authorization: `Bearer ${token}` } }); + await request.post(`${API}/api/v2/me/privacy/notice/accept`, { headers: { Authorization: `Bearer ${token}` } }); } }); test("the built-in notice is shown until a version is published, with the operator register filled in", async ({ page }) => { - const notice = await (await page.request.get(`${API}/api/privacy/notice`)).json() as Notice; + const notice = await (await (await page.request.get(`${API}/api/v2/privacy/notice`)).json()).data as Notice; expect(notice.version).toBe(0); expect(notice.sections.find(s => s.id === "sharing")?.body).toContain("• PayFast (South Africa)"); @@ -29,7 +29,7 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { test("an admin edits and publishes; operators feed the notice", async ({ page }) => { // A new operator appears in the notice's {operators} list. - const op = await api(page, "admin", "POST", "/api/privacy/operators", { name: "E2E Mailer", purpose: "Sending emails", dataShared: "Email address", location: "Ireland" }); + const op = await v2(page, "admin", "POST", "/api/v2/privacy/operators", { name: "E2E Mailer", purpose: "Sending emails", dataShared: "Email address", location: "Ireland" }); await loginAs(page, "admin"); await page.goto("/dashboard/admin/privacy?tab=notice"); @@ -40,7 +40,7 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { await expect(page.getByText("Draft saved.")).toBeVisible(); // Nothing public changes until it's published. - expect(((await (await page.request.get(`${API}/api/privacy/notice`)).json()) as Notice).version).toBe(0); + expect(((await (await page.request.get(`${API}/api/v2/privacy/notice`)).json()).data as Notice).version).toBe(0); await page.getByRole("button", { name: "Publish…" }).click(); await page.getByPlaceholder("e.g. We now use PayFast for online payments.").fill("Clearer introduction."); @@ -52,15 +52,15 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { await expect(page.getByText("• E2E Mailer (Ireland) — Sending emails.", { exact: false })).toBeVisible(); await expect(page.getByText(/Version 1/).first()).toBeVisible(); - await api(page, "admin", "DELETE", `/api/privacy/operators/${op.id}`); + await v2(page, "admin", "DELETE", `/api/v2/privacy/operators/${op.id}`); }); test("after publishing its own version, the editor points out new built-in text", async ({ page }) => { // The published version came from the built-in text; put an older wording back in one changed // section so it shows as having new text. - const draft = await api(page, "admin", "GET", "/api/privacy/notice/draft"); + const draft = await v2(page, "admin", "GET", "/api/v2/privacy/notice/draft"); const sections = draft.sections.map(s => (s.id === "changes" ? { ...s, body: "We may update this notice from time to time." } : s)); - await api(page, "admin", "PUT", "/api/privacy/notice/draft", { sections }); + await v2(page, "admin", "PUT", "/api/v2/privacy/notice/draft", { sections }); await loginAs(page, "admin"); await page.goto("/dashboard/admin/privacy?tab=notice"); @@ -80,7 +80,7 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { await page.reload(); await expect(page.getByLabel("1. Introduction text")).toBeVisible(); await expect(page.getByTestId("builtin-updates")).toHaveCount(0); - await api(page, "admin", "DELETE", "/api/privacy/notice/draft"); + await v2(page, "admin", "DELETE", "/api/v2/privacy/notice/draft"); }); test("someone who never accepted the notice is asked once, after login", async ({ page }) => { @@ -102,10 +102,10 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { }); test("a significant change is accepted once, after login", async ({ page }) => { - const draft = await api(page, "admin", "GET", "/api/privacy/notice/draft"); + const draft = await v2(page, "admin", "GET", "/api/v2/privacy/notice/draft"); // Re-acceptance needs a summary of what changed. - await expect(api(page, "admin", "POST", "/api/privacy/notice/publish", { sections: draft.sections, requiresAcceptance: true })).rejects.toThrow(/400/); - const published = await api<{ version: number }>(page, "admin", "POST", "/api/privacy/notice/publish", { sections: draft.sections, requiresAcceptance: true, changeSummary: "We added WhatsApp news." }); + await expect(v2(page, "admin", "POST", "/api/v2/privacy/notice/publish", { sections: draft.sections, requiresAcceptance: true })).rejects.toThrow(/400/); + const published = await v2<{ version: number }>(page, "admin", "POST", "/api/v2/privacy/notice/publish", { sections: draft.sections, requiresAcceptance: true, changeSummary: "We added WhatsApp news." }); await loginAs(page, "user"); await page.goto("/dashboard/user"); @@ -118,19 +118,19 @@ test.describe("privacy notice, operators and access log (POPIA)", () => { await expect(page.getByText("My Events").first()).toBeVisible(); await expect(page.getByRole("dialog", { name: "We've updated our privacy notice" })).toHaveCount(0); - const log = await api(page, "admin", "GET", `/api/privacy/consent-log?type=notice&q=${encodeURIComponent(seed().users.user.email)}`); + const log = await v2(page, "admin", "GET", `/api/v2/privacy/consent-log?type=notice&q=${encodeURIComponent(seed().users.user.email)}`); expect(log.rows[0]).toMatchObject({ version: published.version, source: "prompt" }); }); test("bulk exports are in the access log", async ({ page }) => { - const res = await page.request.post(`${API}/api/reports/pdf`, { + const res = await page.request.post(`${API}/api/v2/reports/pdf`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}`, "Content-Type": "application/json" }, data: JSON.stringify({ title: "E2E attendee list", kind: "table", table: { columns: ["Name"], rows: [["A"], ["B"], ["C"]] } }), }); expect(res.ok()).toBe(true); - await api(page, "supervisor", "GET", `/api/consent/events/${seed().events.free}`); + await v2(page, "supervisor", "GET", `/api/v2/events/${seed().events.free}/consent`); - const log = await api(page, "admin", "GET", "/api/privacy/access-log"); + const log = await v2(page, "admin", "GET", "/api/v2/privacy/access-log"); expect(log.rows.find(r => r.action === "report_pdf")).toMatchObject({ what: "E2E attendee list", records: 3, actor: "Sam Supervisor" }); expect(log.rows.some(r => r.action === "consent_list")).toBe(true); }); diff --git a/apps/events/e2e/privacy-retention.spec.ts b/apps/events/e2e/privacy-retention.spec.ts index 29cfcae..c389b8c 100644 --- a/apps/events/e2e/privacy-retention.spec.ts +++ b/apps/events/e2e/privacy-retention.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api } from "./fixtures"; +import { test, expect, seed, loginAs, api, v2 } from "./fixtures"; type RunResult = { result: Record> }; type UserRow = { name: string; email: string; isActive: boolean }; @@ -7,32 +7,32 @@ type Breach = { id: string; status: string; regulatorNotifiedAt: string | null } test.describe("retention, breaches and readiness (POPIA)", () => { test("the retention job warns inactive accounts first, and anonymises them 30 days after the warning", async ({ page }) => { - const { result } = await api(page, "admin", "POST", "/api/privacy/retention/run"); + const { result } = await v2(page, "admin", "POST", "/api/v2/privacy/retention/run"); expect(result.inactive_accounts.warned).toBeGreaterThanOrEqual(1); expect(result.inactive_accounts.anonymised).toBeGreaterThanOrEqual(1); expect(result.login_history.deleted).toBeGreaterThanOrEqual(1); - const warned = await api(page, "admin", "GET", `/api/users/${seed().retention.toWarn}`); + const warned = await v2(page, "admin", "GET", `/api/v2/users/${seed().retention.toWarn}`); expect(warned.email).toBe("dormant@e2e.test"); - const gone = await api(page, "admin", "GET", `/api/users/${seed().retention.toAnonymise}`); + const gone = await v2(page, "admin", "GET", `/api/v2/users/${seed().retention.toAnonymise}`); expect(gone.name).toBe("Deleted User"); expect(gone.email).toMatch(/@deleted\.invalid$/); // Seeded accounts (staff roles, and the recently active user) are untouched. - expect((await api(page, "admin", "GET", `/api/users/${seed().users.user.id}`)).email).toBe("user@e2e.test"); + expect((await v2(page, "admin", "GET", `/api/v2/users/${seed().users.user.id}`)).email).toBe("user@e2e.test"); }); test("retention periods are validated and saved; the notice follows them", async ({ page }) => { - const state = await api<{ policies: Record }>(page, "admin", "GET", "/api/privacy/retention"); - await expect(api(page, "admin", "PUT", "/api/privacy/retention", { policies: { ...state.policies, inactive_accounts: { enabled: true, months: 3 } } })).rejects.toThrow(/400/); - await api(page, "admin", "PUT", "/api/privacy/retention", { policies: { ...state.policies, form_answers: { enabled: true, months: 18 } } }); + const state = await v2<{ policies: Record }>(page, "admin", "GET", "/api/v2/privacy/retention"); + await expect(v2(page, "admin", "PUT", "/api/v2/privacy/retention", { policies: { ...state.policies, inactive_accounts: { enabled: true, months: 3 } } })).rejects.toThrow(/400/); + await v2(page, "admin", "PUT", "/api/v2/privacy/retention", { policies: { ...state.policies, form_answers: { enabled: true, months: 18 } } }); await page.goto("/legal/privacy"); await expect(page.getByText("Answers to event forms are deleted 18 months after the event.", { exact: false })).toBeVisible(); }); test("a breach is recorded, reported, and drafts are ready to copy", async ({ page }) => { - const breach = await api(page, "admin", "POST", "/api/privacy/breaches", { + const breach = await v2(page, "admin", "POST", "/api/v2/privacy/breaches", { title: "Phone with the attendee list lost", discoveredAt: new Date().toISOString(), description: "A leader's phone was stolen at the camp site.", dataAffected: "Names and phone numbers of 40 campers", }); @@ -46,12 +46,12 @@ test.describe("retention, breaches and readiness (POPIA)", () => { await page.getByRole("button", { name: "Regulator told today" }).click(); await expect(page.getByRole("button", { name: "Regulator told today" })).toHaveCount(0); - const list = await api(page, "admin", "GET", "/api/privacy/breaches"); + const list = await v2(page, "admin", "GET", "/api/v2/privacy/breaches"); expect(list.find(b => b.id === breach.id)?.regulatorNotifiedAt).toBeTruthy(); }); test("the readiness page scores the install", async ({ page }) => { - const r = await api(page, "admin", "GET", "/api/privacy/readiness"); + const r = await v2(page, "admin", "GET", "/api/v2/privacy/readiness"); expect(r.score).toBeGreaterThan(0); expect(r.checks.find(c => c.key === "retention_reviewed")?.ok).toBe(true); expect(r.checks.find(c => c.key === "retention_running")?.ok).toBe(false); // jobs are off in e2e diff --git a/apps/events/e2e/privacy.spec.ts b/apps/events/e2e/privacy.spec.ts index b08728f..19a15df 100644 --- a/apps/events/e2e/privacy.spec.ts +++ b/apps/events/e2e/privacy.spec.ts @@ -1,5 +1,5 @@ import type { Page } from "@playwright/test"; -import { test, expect, seed, loginAs, api, API } from "./fixtures"; +import { test, expect, seed, loginAs, api, API, v2 } from "./fixtures"; type Account = { id: string; token: string; email: string }; type PrivacyInfo = { news: { email: boolean; whatsapp: boolean }; history: { source: string }[]; requests: { type: string; status: string }[] }; @@ -9,12 +9,12 @@ type Requests = { requests: { id: string; type: string; userId: string; blockers /** A brand-new account made through sign-up, so tests can change it freely. */ async function signUp(page: Page, newsOptIn: boolean): Promise { const email = `privacy-${Date.now()}-${Math.floor(Math.random() * 1e6)}@e2e.test`; - const res = await page.request.post(`${API}/api/users`, { - data: { name: "Pat Privacy", email, password: "E2e-password-123", newsOptIn }, + const res = await page.request.post(`${API}/api/v2/auth/signup`, { + data: { name: "Pat Privacy", email, password: "E2e-password-123", newsOptIn, acceptTerms: true }, }); expect(res.ok()).toBe(true); - const body = await res.json(); - return { id: body.id, token: body.token, email }; + const { data } = await res.json(); + return { id: data.user.id, token: data.token, email }; } async function asAccount(page: Page, account: Account, method: string, url: string, body?: unknown) { @@ -23,13 +23,15 @@ async function asAccount(page: Page, account: Account, method: string, url: s headers: { Authorization: `Bearer ${account.token}`, "Content-Type": "application/json" }, data: body === undefined ? undefined : JSON.stringify(body), }); - return { status: res.status(), body: (await res.json().catch(() => null)) as T }; + // v2 answers { data }; a download (my data) is the file itself. + const json = await res.json().catch(() => null); + return { status: res.status(), body: (json && typeof json === "object" && "data" in json ? json.data : json) as T }; } test.describe("privacy (POPIA)", () => { test("sign-up records the news choice; the privacy page changes it and downloads my data", async ({ page }) => { const me = await signUp(page, false); - const before = await asAccount(page, me, "GET", "/api/privacy/me"); + const before = await asAccount(page, me, "GET", "/api/v2/me/privacy"); expect(before.body.news.email).toBe(false); expect(before.body.history.map((h) => h.source)).toContain("signup"); @@ -41,7 +43,7 @@ test.describe("privacy (POPIA)", () => { await expect(page.getByText("You're subscribed.")).toBeVisible(); await expect(byEmail).toBeChecked(); - const exported = await asAccount<{ account: { email: string }; communication: { news: { email: boolean } } }>(page, me, "GET", "/api/privacy/me/export"); + const exported = await asAccount<{ account: { email: string }; communication: { news: { email: boolean } } }>(page, me, "GET", "/api/v2/me/privacy/export"); expect(exported.status).toBe(200); expect(exported.body.account.email).toBe(me.email); expect(exported.body.communication.news.email).toBe(true); @@ -49,10 +51,10 @@ test.describe("privacy (POPIA)", () => { test("news broadcasts skip people who aren't opted in; event updates don't", async ({ page }) => { const out = await signUp(page, false); - const news = await api(page, "supervisor", "POST", "/api/broadcasts/preview", { userIds: [out.id, seed().users.admin.id], emails: "", kind: "news" }); + const news = await v2(page, "supervisor", "POST", "/api/v2/broadcasts/email/preview", { userIds: [out.id, seed().users.admin.id], emails: "", kind: "news" }); expect(news.matched).toBe(1); expect(news.skipped).toBe(1); - const update = await api(page, "supervisor", "POST", "/api/broadcasts/preview", { userIds: [out.id, seed().users.admin.id], emails: "", kind: "update" }); + const update = await v2(page, "supervisor", "POST", "/api/v2/broadcasts/email/preview", { userIds: [out.id, seed().users.admin.id], emails: "", kind: "update" }); expect(update.matched).toBe(2); expect(update.skipped).toBe(0); }); @@ -61,11 +63,11 @@ test.describe("privacy (POPIA)", () => { await page.goto(`/unsubscribe?t=${encodeURIComponent(seed().unsubscribeToken)}`); await page.getByRole("button", { name: "Unsubscribe from all news" }).click(); await expect(page.getByText(/You're unsubscribed from news and announcements/)).toBeVisible(); - const after = await api(page, "user", "GET", "/api/privacy/me"); + const after = await v2(page, "user", "GET", "/api/v2/me/privacy"); expect(after.news).toEqual({ email: false, whatsapp: false }); expect(after.history.some((h) => h.source === "unsubscribe_link")).toBe(true); - const bad = await page.request.get(`${API}/api/privacy/unsubscribe/not-a-real-token`); + const bad = await page.request.get(`${API}/api/v2/unsubscribe/not-a-real-token`); expect(bad.status()).toBe(404); }); @@ -84,17 +86,17 @@ test.describe("privacy (POPIA)", () => { test("delete my account: closed at once, anonymised when an admin completes the request", async ({ page }) => { const me = await signUp(page, true); - const wrong = await asAccount(page, me, "POST", "/api/privacy/me/requests", { type: "deletion", password: "nope" }); + const wrong = await asAccount(page, me, "POST", "/api/v2/me/privacy/requests", { type: "deletion", password: "nope" }); expect(wrong.status).toBe(400); - const made = await asAccount(page, me, "POST", "/api/privacy/me/requests", { type: "deletion", password: "E2e-password-123" }); + const made = await asAccount(page, me, "POST", "/api/v2/me/privacy/requests", { type: "deletion", password: "E2e-password-123" }); expect(made.status).toBe(201); // The account is closed: the old session no longer works, and logging in is refused. - expect((await asAccount(page, me, "GET", "/api/privacy/me")).status).toBe(401); - const login = await page.request.post(`${API}/api/users/login`, { data: { email: me.email, password: "E2e-password-123" } }); + expect((await asAccount(page, me, "GET", "/api/v2/me/privacy")).status).toBe(401); + const login = await page.request.post(`${API}/api/v2/auth/login`, { data: { identifier: me.email, password: "E2e-password-123" } }); expect(login.ok()).toBe(false); - const inbox = await api(page, "admin", "GET", "/api/privacy/requests?status=open"); + const inbox = await v2(page, "admin", "GET", "/api/v2/privacy/requests?status=open"); const request = inbox.requests.find((r) => r.userId === me.id); expect(request?.type).toBe("deletion"); expect(request?.blockers).toEqual([]); @@ -103,8 +105,8 @@ test.describe("privacy (POPIA)", () => { await loginAs(page, "admin"); await page.goto("/dashboard/admin/data-requests"); await expect(page.getByText(me.email)).toBeVisible(); - await api(page, "admin", "POST", `/api/privacy/requests/${request!.id}/complete`, {}); - const user = await api<{ name: string; email: string }>(page, "admin", "GET", `/api/users/${me.id}`); + await v2(page, "admin", "POST", `/api/v2/privacy/requests/${request!.id}/complete`, {}); + const user = await v2<{ name: string; email: string }>(page, "admin", "GET", `/api/v2/users/${me.id}`); expect(user.name).toBe("Deleted User"); expect(user.email).toMatch(/@deleted\.invalid$/); }); diff --git a/apps/events/e2e/registration.spec.ts b/apps/events/e2e/registration.spec.ts index 0d1b5fd..70f733e 100644 --- a/apps/events/e2e/registration.spec.ts +++ b/apps/events/e2e/registration.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api } from "./fixtures"; +import { test, expect, seed, loginAs, api, v2 } from "./fixtures"; type Registration = { id: string; status: string; eventId: string }; type Ticket = { id: string; qrCode: string; eventId: string }; @@ -14,7 +14,7 @@ test.describe("registration → payment → ticket → check-in → cashup", () await page.getByRole("button", { name: "Register", exact: true }).click(); await page.waitForURL(/\/registration\/success/); - const tickets = await api(page, "user", "GET", "/api/tickets/mytickets"); + const tickets = await v2(page, "user", "GET", "/api/v2/me/tickets"); expect(tickets.some((t) => t.eventId === seed().events.free)).toBe(true); }); @@ -26,14 +26,14 @@ test.describe("registration → payment → ticket → check-in → cashup", () await page.getByRole("button", { name: "Register", exact: true }).click(); await page.waitForURL(/\/registration\/success/); - const regs = await api(page, "user", "GET", "/api/registrations/myregistrations"); + const regs = await v2(page, "user", "GET", "/api/v2/me/registrations/full"); const reg = regs.find((r) => r.eventId === seed().events.paid); expect(reg?.status).not.toBe("paid"); - expect((await api(page, "user", "GET", "/api/tickets/mytickets")).some((t) => t.eventId === seed().events.paid)).toBe(false); + expect((await v2(page, "user", "GET", "/api/v2/me/tickets")).some((t) => t.eventId === seed().events.paid)).toBe(false); // A supervisor records the cash payment at the desk. - await api(page, "supervisor", "POST", "/api/payments", { amount: 150, method: "cash", registrationId: reg!.id, eventId: seed().events.paid, userId: seed().users.user.id }); - const ticket = (await api(page, "user", "GET", "/api/tickets/mytickets")).find((t) => t.eventId === seed().events.paid); + await v2(page, "supervisor", "POST", "/api/v2/payments", { amount: 150, method: "cash", registrationId: reg!.id, eventId: seed().events.paid, userId: seed().users.user.id }); + const ticket = (await v2(page, "user", "GET", "/api/v2/me/tickets")).find((t) => t.eventId === seed().events.paid); expect(ticket).toBeTruthy(); // My Events shows it. @@ -41,11 +41,11 @@ test.describe("registration → payment → ticket → check-in → cashup", () await expect(page.getByText("E2E Paid Conference").first()).toBeVisible(); // Staff check it in; a second scan is refused. - await api(page, "staff", "POST", `/api/tickets/scan/${ticket!.qrCode}`, { qty: 1 }); - await expect(api(page, "staff", "POST", `/api/tickets/scan/${ticket!.qrCode}`, { qty: 1 })).rejects.toThrow(/403.*fully used/); + expect((await v2<{ outcome: string }>(page, "staff", "POST", `/api/v2/checkin/${ticket!.qrCode}`, { people: 1 })).outcome).toBe("checked_in"); + expect(await v2(page, "staff", "POST", `/api/v2/checkin/${ticket!.qrCode}`, { people: 1 })).toMatchObject({ outcome: "already_used", message: expect.stringMatching(/fully used/) }); // Cashup: the R150 cash is on the supervisor who took it. - const cash = await api(page, "supervisor", "GET", `/api/cashups/event/${seed().events.paid}/cash-by-user`); + const cash = await v2(page, "supervisor", "GET", `/api/v2/events/${seed().events.paid}/cashup/cash-by-user`); const mine = cash.rows.find((r) => r.userId === seed().users.supervisor.id); expect(mine?.cash.total).toBe(150); expect(mine?.cash.count).toBe(1); diff --git a/apps/events/e2e/series.spec.ts b/apps/events/e2e/series.spec.ts index 97a4ea4..850d0ec 100644 --- a/apps/events/e2e/series.spec.ts +++ b/apps/events/e2e/series.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, loginAs, api, seed, API } from "./fixtures"; +import { test, expect, loginAs, api, seed, API, v2 } from "./fixtures"; // Event series (1.47.1): a supervisor makes a series, events join it, the public series page // lists them, an event page links to the next one, a user follows it, and the series job tells @@ -28,12 +28,12 @@ test.describe.serial("event series", () => { await expect(page.getByRole("status")).toContainText("E2E Breakfast"); await expect(page.getByTestId("series-row").filter({ hasText: "E2E Breakfast" })).toContainText("/series/e2e-breakfast"); - const all = await api(page, "supervisor", "GET", "/api/series"); + const all = await v2(page, "supervisor", "GET", "/api/v2/series"); series = all.find((s) => s.name === "E2E Breakfast")!; - past = await api(page, "supervisor", "POST", "/api/events", event("E2E Breakfast (last month)", -30, series.id)); - next = await api(page, "supervisor", "POST", "/api/events", event("E2E Breakfast (next month)", 30, series.id)); + past = await v2(page, "supervisor", "POST", "/api/v2/events", event("E2E Breakfast (last month)", -30, series.id)); + next = await v2(page, "supervisor", "POST", "/api/v2/events", event("E2E Breakfast (next month)", 30, series.id)); // Both are live already; announce them now so only the event made after following counts below. - await api(page, "admin", "POST", "/api/admin/jobs/series/run"); + await v2(page, "admin", "POST", "/api/v2/admin/jobs/series/run"); }); test("the series page lists what's coming up and what's past", async ({ page }) => { @@ -56,10 +56,10 @@ test.describe.serial("event series", () => { await page.getByRole("button", { name: "Follow this series" }).click(); await expect(page.getByRole("button", { name: "Unfollow" })).toBeVisible(); - await api(page, "supervisor", "POST", "/api/events", event("E2E Breakfast (in two months)", 60, series.id)); - const first = await api(page, "admin", "POST", "/api/admin/jobs/series/run"); + await v2(page, "supervisor", "POST", "/api/v2/events", event("E2E Breakfast (in two months)", 60, series.id)); + const first = await v2(page, "admin", "POST", "/api/v2/admin/jobs/series/run"); expect(first.output.announced).toBe(1); - const again = await api(page, "admin", "POST", "/api/admin/jobs/series/run"); + const again = await v2(page, "admin", "POST", "/api/v2/admin/jobs/series/run"); expect(again.output.announced).toBe(0); }); @@ -86,17 +86,17 @@ test.describe.serial("event series", () => { await expect(page.getByTestId("my-passes").getByRole("button", { name: "Pay now" })).toBeVisible(); type Mine = { id: string; total: number; registrations: { id: string; event: { title: string } }[] }[]; - const [purchase] = await api(page, "user", "GET", "/api/season-passes/mine"); + const [purchase] = await v2(page, "user", "GET", "/api/v2/me/season-passes"); expect(purchase.total).toBe(60); expect(purchase.registrations.map((r) => r.event.title).sort()).toEqual(["E2E Breakfast (in two months)", "E2E Breakfast (next month)"]); // Each event's registration owes its share: 2 × R15. type Reg = { id: string; totalDueComputed?: number; registrationOptions: { quantity: number; priceSnapshot: number }[] }; - const regs = await api(page, "supervisor", "GET", `/api/registrations/event/${next.id}`); + const regs = await v2(page, "supervisor", "GET", `/api/v2/events/${next.id}/registrations`); const fromPass = regs.find((r) => r.id === purchase.registrations.find((x) => x.event.title === "E2E Breakfast (next month)")!.id)!; expect(fromPass.registrationOptions[0]).toMatchObject({ quantity: 2, priceSnapshot: 15 }); // A pass registration keeps its tickets as bought: no codes. - const res = await page.request.post(`${API}/api/registrations/${fromPass.id}/coupon`, { + const res = await page.request.post(`${API}/api/v2/registrations/${fromPass.id}/coupon`, { headers: { Authorization: `Bearer ${seed().users.user.token}` }, data: { code: "ANY" }, }); expect(res.status()).toBe(409); diff --git a/apps/events/e2e/sessions.spec.ts b/apps/events/e2e/sessions.spec.ts index 54edd54..3f831c7 100644 --- a/apps/events/e2e/sessions.spec.ts +++ b/apps/events/e2e/sessions.spec.ts @@ -1,13 +1,13 @@ -import { test, expect, seed, loginAs, api, pickEvent } from "./fixtures"; +import { test, expect, seed, loginAs, api, pickEvent, v2 } from "./fixtures"; test.describe("multi-day events", () => { test("check-in is once per session, and the register and certificates follow", async ({ page }) => { const { course, events } = seed(); // Scanning today: Week 2. - const scan = await api<{ session: { label: string } }>(page, "staff", "POST", `/api/tickets/scan/${course.qrCode}`, { qty: 1 }); + const scan = await v2<{ session: { label: string } }>(page, "staff", "POST", `/api/v2/checkin/${course.qrCode}`, { people: 1 }); expect(scan.session.label).toBe("Week 2"); - await expect(api(page, "staff", "POST", `/api/tickets/scan/${course.qrCode}`, { qty: 1 })).rejects.toThrow(/Already checked in for Week 2/); + expect(await v2(page, "staff", "POST", `/api/v2/checkin/${course.qrCode}`, { people: 1 })).toMatchObject({ outcome: "already_used", message: expect.stringMatching(/Already checked in for Week 2/) }); // The register shows weeks 1 and 2 ticked. await loginAs(page, "supervisor"); diff --git a/apps/events/e2e/supervisor.spec.ts b/apps/events/e2e/supervisor.spec.ts index 2936afc..0d7d203 100644 --- a/apps/events/e2e/supervisor.spec.ts +++ b/apps/events/e2e/supervisor.spec.ts @@ -1,4 +1,4 @@ -import { test, expect, seed, loginAs, api, pickEvent } from "./fixtures"; +import { test, expect, seed, loginAs, api, pickEvent, v2 } from "./fixtures"; type EventRow = { id: string; title: string; scheduleType?: string; sessions?: { cancelled?: boolean }[] }; @@ -26,7 +26,7 @@ test.describe("supervisor tools", () => { const row = page.locator("li", { hasText: "E2E Wizard Course" }); await expect(row.getByText(/5 sessions · /)).toBeVisible(); - const all = await api(page, "supervisor", "GET", "/api/events/all"); + const all = await v2(page, "supervisor", "GET", "/api/v2/events/manage"); const created = all.find((e) => e.title === "E2E Wizard Course"); expect(created?.scheduleType).toBe("sessions"); expect(created?.sessions?.filter((s) => !s.cancelled)).toHaveLength(5); @@ -34,7 +34,7 @@ test.describe("supervisor tools", () => { test("copy an event: the popup is filled in and every date moves with the new start", async ({ page }) => { type Full = EventRow & { eventOptions: { name: string; price: number }[]; sessions: { startsAt: string; label?: string | null }[] }; - const source = await api(page, "supervisor", "GET", `/api/events/${seed().events.course}`); + const source = await v2(page, "supervisor", "GET", `/api/v2/events/${seed().events.course}/full`); await loginAs(page, "supervisor"); await page.goto("/dashboard/supervisor/events"); @@ -57,10 +57,10 @@ test.describe("supervisor tools", () => { await create.click(); await expect(page.getByRole("heading", { name: "Copy Event" })).toBeHidden(); - const all = await api(page, "supervisor", "GET", "/api/events/all?includePast=true"); + const all = await v2(page, "supervisor", "GET", "/api/v2/events/manage?past=true"); const row = all.find((e) => e.title === "E2E Alpha Course (next term)"); expect(row).toBeTruthy(); - const copy = await api(page, "supervisor", "GET", `/api/events/${row!.id}`); + const copy = await v2(page, "supervisor", "GET", `/api/v2/events/${row!.id}/full`); expect(copy.scheduleType).toBe("sessions"); const active = (s: Full) => s.sessions.filter((x) => !(x as { cancelled?: boolean }).cancelled); expect(active(copy)).toHaveLength(active(source).length); diff --git a/apps/events/e2e/volunteers.spec.ts b/apps/events/e2e/volunteers.spec.ts index 8ab9e73..64f9da4 100644 --- a/apps/events/e2e/volunteers.spec.ts +++ b/apps/events/e2e/volunteers.spec.ts @@ -20,9 +20,9 @@ test.describe.serial("volunteer rosters", () => { }); test("the volunteer ticket isn't offered publicly", async ({ request }) => { - const res = await request.get(`${API}/api/events/${seed().events.serving}`); - const ev = await res.json(); - expect(ev.eventOptions.map((o: { name: string }) => o.name)).toEqual(["Entry"]); + const res = await request.get(`${API}/api/v2/events/${seed().events.serving}`); + const ev = (await res.json()).data; + expect(ev.ticketOptions.map((o: { name: string }) => o.name)).toEqual(["Entry"]); }); test("a user signs up, then asks for cover", async ({ page }) => { @@ -48,8 +48,8 @@ test.describe.serial("volunteer rosters", () => { await expect(page.getByTestId("my-shift").filter({ hasText: "Welcome team" })).toBeVisible(); // The QR code on the wall holds this; a phone camera opens the check-in page. - const qr = await request.get(`${API}/api/volunteers/manage/events/${seed().events.serving}/qr`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } }); - const { qr: code } = await qr.json(); + const qr = await request.get(`${API}/api/v2/events/${seed().events.serving}/volunteers/qr`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } }); + const { qr: code } = (await qr.json()).data; await page.goto(`/serve/check-in?code=${encodeURIComponent(code)}`); await expect(page.getByTestId("volunteer-checked-in")).toContainText("Welcome team"); }); diff --git a/apps/events/e2e/webhooks.spec.ts b/apps/events/e2e/webhooks.spec.ts index 9b39e98..1286efc 100644 --- a/apps/events/e2e/webhooks.spec.ts +++ b/apps/events/e2e/webhooks.spec.ts @@ -51,7 +51,7 @@ test.describe.serial("outbound webhooks", () => { test("a new account is sent, signed, and shows in the delivery log", async ({ page, request }) => { const email = `webhook-${Date.now()}@test.local`; - const res = await request.post(`${API}/api/users`, { data: { name: "Webhook Person", email, password: "E2e-password-123", phoneNumber: "0820000123" } }); + const res = await request.post(`${API}/api/v2/auth/signup`, { data: { name: "Webhook Person", email, password: "E2e-password-123", phone: "0820000123", acceptTerms: true } }); expect(res.ok()).toBe(true); await expect.poll(() => received.filter(r => r.headers["x-crossevents-event"] === "user.created").length, { timeout: 15000 }).toBeGreaterThan(0); diff --git a/apps/events/frontend/eslint.config.mjs b/apps/events/frontend/eslint.config.mjs index d5eb35b..3fa5d64 100644 --- a/apps/events/frontend/eslint.config.mjs +++ b/apps/events/frontend/eslint.config.mjs @@ -8,16 +8,13 @@ const eslintConfig = defineConfig([ ...nextVitals, ...nextTs, { - // React Compiler-era rules that eslint-plugin-react-hooks 7 (with Next 16) turns on as - // errors. They flag patterns the app uses on purpose and that work (mostly loading data in - // useEffect), so they're warnings while the code is moved off them screen by screen — - // see HANDOVER, "Next.js 16". New code should follow them. + // The React Compiler rules (set-state-in-effect, purity, immutability, refs, + // static-components) are errors, as eslint-plugin-react-hooks 7 sets them (back on in 2.0). + // Loading data or reading the browser in an effect: useExternalEffect; state that follows + // other state: useStateSync (both in lib/hooks.ts) — see HANDOVER, "Next.js 16". rules: { - "react-hooks/set-state-in-effect": "warn", - "react-hooks/purity": "warn", - "react-hooks/immutability": "warn", - "react-hooks/static-components": "warn", - "react-hooks/refs": "warn", + // Those two take deps like useEffect; check them the same way. + "react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^(useExternalEffect|useStateSync)$" }], }, }, globalIgnores([".next/**", ".next-*/**", "out/**", "build/**", "next-env.d.ts", "src/lib/api-v2/schema.d.ts"]), diff --git a/apps/events/frontend/package-lock.json b/apps/events/frontend/package-lock.json index 41a18f7..bc77d9f 100644 --- a/apps/events/frontend/package-lock.json +++ b/apps/events/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events-frontend", - "version": "1.52.3", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events-frontend", - "version": "1.52.3", + "version": "2.0.0", "dependencies": { "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 1ae5dc1..af86a92 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "hope-events-frontend", - "version": "1.52.3", + "version": "2.0.0", "private": true, "scripts": { "dev": "next dev", diff --git a/apps/events/frontend/src/app/activate-account/page.tsx b/apps/events/frontend/src/app/activate-account/page.tsx index e9d5e9f..334e1bc 100644 --- a/apps/events/frontend/src/app/activate-account/page.tsx +++ b/apps/events/frontend/src/app/activate-account/page.tsx @@ -9,6 +9,7 @@ import { appName } from "@/lib/siteConfig"; import { ShieldCheck } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { apiV2Data } from "@/lib/apiV2"; +import { hardNavigate } from "@/lib/navigation"; function ActivateAccountContent() { const search = useSearchParams(); @@ -34,7 +35,7 @@ function ActivateAccountContent() { // dashboard fresh so the new session is picked up. if (data?.token) saveToken(data.token); setStatus("Your account is now active. Redirecting…"); - setTimeout(() => { window.location.href = "/dashboard"; }, 1500); + setTimeout(() => hardNavigate("/dashboard"), 1500); } catch (err) { setStatus(errorMessage(err) || "Activation failed. The link may have expired."); } finally { diff --git a/apps/events/frontend/src/app/campus/[slug]/page.tsx b/apps/events/frontend/src/app/campus/[slug]/page.tsx index b7db1b8..e4026e0 100644 --- a/apps/events/frontend/src/app/campus/[slug]/page.tsx +++ b/apps/events/frontend/src/app/campus/[slug]/page.tsx @@ -43,6 +43,8 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s if (!campus) notFound(); const events = await apiFetchListForPrerender(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }); + // A server component renders once per request (or revalidation): this is that render's time. + // eslint-disable-next-line react-hooks/purity const now = Date.now(); const upcoming = (events || []) .filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now) diff --git a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx index eff96bd..1f32230 100644 --- a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx @@ -9,6 +9,7 @@ import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@ import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const ACTION_LABELS: Record = { refund_created: "Refund created", @@ -231,7 +232,7 @@ export default function AdminAuditLogPage() { }, [token, buildQuery, setError]); // load changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes. - useEffect(() => { if (token) load(1); }, [token, load]); + useExternalEffect(() => { if (token) load(1); }, [token, load]); return (
diff --git a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx index 12feb0e..de7776b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useCallback, useEffect, useMemo, useState } from "react"; +import React, { useCallback, useMemo, useState } from "react"; import { useParams } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { fetchEvent } from "@/lib/api"; @@ -11,6 +11,7 @@ import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { createCost, updateCost, deleteCost } from "@/lib/eventSetup"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const METHOD_LABELS: Record = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"]; @@ -55,7 +56,7 @@ export default function EventCashupPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); return (
@@ -317,7 +318,7 @@ function CashByUserSection({ eventId, token, onCashSummaryChange }: { }, [eventId, token, onCashSummaryChange]); // onCashSummaryChange is a state setter in the parent, so this only reruns when the event/token change. - useEffect(load, [load]); + useExternalEffect(() => load(), [load]); const rows = data?.rows || []; const sumOf = (m: "cash" | "card" | "eft" | "other", key: "total" | "count") => @@ -947,7 +948,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh // CashByUserSection below; when there is one, cash on hand is whatever wasn't deposited. const [cashSummary, setCashSummary] = useState<{ actualTotal: number | null; denominations: PersonDenom[] }>({ actualTotal: null, denominations: [] }); - useEffect(() => { setLines(initialLines); }, [initialLines]); + useExternalEffect(() => { setLines(initialLines); }, [initialLines]); const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next })); diff --git a/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx b/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx index 816706a..fe17edd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx @@ -12,6 +12,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { AttendeeFormModal, type AttendeeFormDef } from "@/components/shared/AttendeeFormModal"; import type { Event } from "@/types"; +import { useExternalEffect } from "@/lib/hooks"; // GET /api/v2/corrections/events/{id} (services/corrections.ts) type CorrectionTicket = { @@ -265,7 +266,7 @@ function CorrectionsContent() { } }, [token, eventId, setMessage]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); useEffect(() => { if (!eventId) return; fetchEvent(eventId, { authToken: token || undefined }) diff --git a/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx b/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx index 49d1f5a..159803e 100644 --- a/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx @@ -9,6 +9,7 @@ import { Inbox, AlertTriangle } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type RequestType = "access" | "correction" | "deletion"; type RequestStatus = "open" | "completed" | "rejected" | "cancelled"; @@ -144,10 +145,9 @@ export default function DataRequestsPage() { // Search once typing pauses; a new search or tab starts at page 1. useEffect(() => { - const t = setTimeout(() => setSearch(searchInput.trim()), 350); + const t = setTimeout(() => { setSearch(searchInput.trim()); setPage(1); }, 350); return () => clearTimeout(t); }, [searchInput]); - useEffect(() => { setPage(1); }, [view, search]); const [msg, setMsg] = useDismissingState(null); const load = useCallback(async () => { @@ -163,7 +163,7 @@ export default function DataRequestsPage() { setMsg({ type: "err", text: errorMessage(e) || "Could not load requests." }); } }, [token, view, page, search, setMsg]); - useEffect(() => { setRequests(null); load(); }, [load]); + useExternalEffect(() => { setRequests(null); load(); }, [load]); return (
@@ -181,7 +181,7 @@ export default function DataRequestsPage() {
{(["open", "closed"] as const).map(v => ( - ))} diff --git a/apps/events/frontend/src/app/dashboard/admin/page.tsx b/apps/events/frontend/src/app/dashboard/admin/page.tsx index f2f9e11..6a5ab55 100644 --- a/apps/events/frontend/src/app/dashboard/admin/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/page.tsx @@ -19,6 +19,7 @@ import { CampusFilter } from "@/components/shared/CampusFilter"; import { TodayPanel } from "@/components/dashboard/TodayPanel"; import { CommandPaletteButton } from "@/components/shared/CommandPalette"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`; const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`; @@ -108,7 +109,7 @@ export default function AdminDashboardPage() { } }, [token, campus, setPaymentStats, setOverview]); - useEffect(() => { + useExternalEffect(() => { if (!token) return; loadStats(); }, [token, loadStats]); diff --git a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx index becd3b9..047081b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx @@ -13,6 +13,7 @@ import { RegistrationBulkBar } from "@/components/admin/RegistrationBulkBar"; import { SavedFilters } from "@/components/shared/SavedFilters"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const; @@ -60,7 +61,8 @@ export default function AdminRegistrationsPage() { // Deep links (the dashboard's "Waiting for you" list and the Ctrl+K palette): ?q=, ?status=, ?event=. // A search by reference may be for a past event's registration, so past events are included then. - useEffect(() => { + // Deep links (the command palette, other pages): read the URL once. + useExternalEffect(() => { const params = new URLSearchParams(window.location.search); const q = params.get("q"); if (q) { setQuery(q); setIncludePastEvents(true); } @@ -103,11 +105,11 @@ export default function AdminRegistrationsPage() { } catch {} }, [token, includePastEvents, includeInactiveEvents]); - useEffect(() => { + useExternalEffect(() => { loadRegistrations(); }, [loadRegistrations]); - useEffect(() => { + useExternalEffect(() => { loadEvents(); }, [loadEvents]); diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index b46d220..bd7aac9 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api"; import { apiV2Raw, apiV2Data } from "@/lib/apiV2"; import { useSiteSettings } from "@/contexts/SiteSettingsContext"; import { useDismissingState } from "@/hooks/useDismissingState"; -import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook } from "lucide-react"; +import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react"; import { ColorPickerField } from "@/components/admin/ColorPickerField"; import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel"; import { BackupsTab } from "@/components/admin/BackupsTab"; @@ -16,14 +16,16 @@ import { JobsTab } from "@/components/admin/JobsTab"; import { PaymentsTab } from "@/components/admin/PaymentsTab"; import { LicenceTab } from "@/components/admin/LicenceTab"; import { WebhooksTab } from "@/components/admin/WebhooksTab"; +import { AiTab } from "@/components/admin/AiTab"; import { CampusesTab } from "@/components/admin/CampusesTab"; import { extractDominantColors } from "@/lib/extractColors"; import { mapsSearchUrl } from "@/lib/maps"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { uploadImage } from "@/lib/eventSetup"; +import { useExternalEffect } from "@/lib/hooks"; -type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence"; +type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai"; const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [ { id: "organisation", label: "Organisation", icon: Building2 }, @@ -38,6 +40,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [ { id: "backups", label: "Backups", icon: DatabaseBackup }, { id: "jobs", label: "Background jobs", icon: Timer }, { id: "licence", label: "Licence", icon: KeyRound }, + { id: "ai", label: "AI", icon: Sparkles }, ]; const inputCls = @@ -717,6 +720,7 @@ function SiteSettingsPageInner() { {activeTab === "webhooks" && } {activeTab === "jobs" && } {activeTab === "licence" && } + {activeTab === "ai" && } {activeTab === "campuses" && }
@@ -893,7 +897,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token]); - useEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]); + useExternalEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]); const fetchStatus = useCallback(async () => { if (!token || step !== 3) return; @@ -908,7 +912,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token, step, fetchConfig]); - useEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]); + useExternalEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]); // Auto-poll status when not stable — only while this tab is active. useEffect(() => { @@ -928,7 +932,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token]); - useEffect(() => { + useExternalEffect(() => { if (active && status === "SCAN_QR_CODE") { fetchQr(); } else { setQrSrc(null); } }, [status, fetchQr, active]); diff --git a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx index ad8adf3..9c4e57b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx @@ -13,6 +13,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { useCampuses } from "@/hooks/useCampuses"; import { SavedFilters } from "@/components/shared/SavedFilters"; import { apiV2Data, apiV2 } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; interface UserItem { id: string; @@ -60,7 +61,7 @@ export default function AdminUsersPage() { const [activeFilter, setActiveFilter] = useState<"" | "true" | "false">(""); // ?q= (the Ctrl+K palette links here with a person's email). - useEffect(() => { + useExternalEffect(() => { const q = new URLSearchParams(window.location.search).get("q"); if (q) { setQuery(q); setDebouncedQuery(q); } }, []); @@ -113,7 +114,7 @@ export default function AdminUsersPage() { // Initial load, and back to page 1 whenever a filter or the page size changes // (loadUsers is recreated when any of them do). - useEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]); + useExternalEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]); const goToPage = (p: number) => loadUsers(p); diff --git a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx index b849e0b..16e9591 100644 --- a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx @@ -14,6 +14,7 @@ import type { Event, Ticket as TicketRecord } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; function EventTicketsContent() { const { token, user } = useAuth(); @@ -60,7 +61,8 @@ function EventTicketsContent() { }, [token, setError]); // No event in the URL: default to the first upcoming one once the list arrives. - useEffect(() => { + // No event in the URL: pick the first and put it there. + useExternalEffect(() => { if (paramEventId || events.length === 0) return; setEventId(events[0].id); router.replace( @@ -71,7 +73,7 @@ function EventTicketsContent() { }, [events, paramEventId, router, selectedUserId]); // Sync params → state (setting the value it already has is a no-op) - useEffect(() => { + useStateSync(() => { if (paramEventId) setEventId(paramEventId); if (paramUserId) setSelectedUserId(paramUserId); }, [paramEventId, paramUserId]); diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx index 22c43b6..639e2d2 100644 --- a/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx @@ -19,6 +19,7 @@ import { FAMILY_QR_PREFIX, QR_PREFIX, deviceId, loadOffline, offlineCheckIn, saveOffline, stickerAlert, suggestRoom, type CheckInResult, type KidsBoard, type KidsFamily, type OfflineState, } from "@/lib/kids"; +import { useExternalEffect } from "@/lib/hooks"; type Tab = "in" | "out" | "rooms"; type Msg = { type: "ok" | "err"; text: string } | null; @@ -78,7 +79,7 @@ export default function KidsDeskPage() { } }, [token, eventId, sessionId, working]); - useEffect(() => { + useExternalEffect(() => { setBoard(null); setFamily(null); setResult(null); diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx index 4c9996b..5bbb720 100644 --- a/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useCallback, useEffect, useState } from "react"; +import React, { useCallback, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { errorMessage } from "@/lib/utils"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; @@ -11,6 +11,7 @@ import { KidsEventPicker } from "@/components/kids/KidsEventPicker"; import { RoomBoard, RoomStatusBadges } from "@/components/kids/RoomBoard"; import type { KidsBoard } from "@/lib/kids"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const ROOM_KEY = "hope_events_kids_room"; @@ -24,7 +25,7 @@ export default function KidsRoomsPage() { const [error, setError] = useState(null); const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); - useEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []); + useExternalEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []); const load = useCallback(async (log = false) => { if (!token || !eventId) return; @@ -37,7 +38,7 @@ export default function KidsRoomsPage() { } }, [token, eventId, sessionId]); - useEffect(() => { load(true); }, [load]); + useExternalEffect(() => { load(true); }, [load]); useVisiblePolling(() => { load(); }, 5000, !!token && !!eventId); const pickRoom = (id: string) => { diff --git a/apps/events/frontend/src/app/dashboard/staff/page.tsx b/apps/events/frontend/src/app/dashboard/staff/page.tsx index d987b01..6530c2d 100644 --- a/apps/events/frontend/src/app/dashboard/staff/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/page.tsx @@ -13,6 +13,7 @@ import { CampusScopeNote } from "@/components/shared/CampusFilter"; import { TodayPanel } from "@/components/dashboard/TodayPanel"; import { CommandPaletteButton } from "@/components/shared/CommandPalette"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const QUICK_ACTIONS = [ { href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode }, @@ -63,7 +64,7 @@ export default function StaffDashboardPage() { } }, [token, setStats, setRecentScans]); - useEffect(() => { + useExternalEffect(() => { if (!token) return; loadStats(); }, [token, loadStats]); diff --git a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx index 2f7a5f2..996567e 100644 --- a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx @@ -16,6 +16,7 @@ import { activeSessions, currentSessionLabel, formatSessionWhen, sessionLabel } import { BackLink } from "@/components/shared/BackLink"; import { apiV2, apiV2Data } from "@/lib/apiV2"; import { listSections } from "@/lib/eventSetup"; +import { useStateSync } from "@/lib/hooks"; // What the confirm step needs, from GET /api/v2/checkin/{qrCode}. Offline scans build the // same shape from the downloaded ticket list. @@ -109,7 +110,6 @@ export default function TicketScanningPage() { const selectedEvent = useMemo(() => allEvents.find(ev => ev.id === selectedEventId) || null, [allEvents, selectedEventId]); const eventSessions = useMemo(() => selectedEvent?.scheduleType === "sessions" ? activeSessions(selectedEvent.sessions) : [], [selectedEvent]); - useEffect(() => { setSelectedSessionId("auto"); }, [selectedEventId]); const sessionParam = selectedEventId !== "all" && selectedSessionId !== "auto" ? selectedSessionId : null; useEffect(() => { @@ -133,13 +133,16 @@ export default function TicketScanningPage() { }, [selectedEventId, token]); // In offline mode the event and section are fixed to the locked scope. - useEffect(() => { + // An offline lock fixes the event and section this device scans for. + useStateSync(() => { if (!offline.lock) return; setSelectedEventId(offline.lock.eventId); + setSelectedSessionId("auto"); }, [offline.lock]); - useEffect(() => { - if (!offline.lock) return; - setSelectedSectionId(offline.lock.sectionId || "all"); + // Again when the sections load (the picker needs the locked one in its list). + useStateSync(() => { + void sections; + if (offline.lock) setSelectedSectionId(offline.lock.sectionId || "all"); }, [offline.lock, sections]); // Bug fix: stop the scanner when the event or section filter changes so stale scan @@ -377,7 +380,7 @@ export default function TicketScanningPage() { className="w-full sm:w-72" events={pickerEvents} value={selectedEventId === "all" ? "" : selectedEventId} - onChange={id => setSelectedEventId(id || "all")} + onChange={id => { setSelectedEventId(id || "all"); setSelectedSessionId("auto"); }} emptyLabel="All events" graceHours={12} disabled={!!offline.lock} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx index 8eebc2d..3cb4f0a 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx @@ -12,6 +12,7 @@ import type { Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null }; type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] }; @@ -115,7 +116,7 @@ export default function AllocationsPage() { setError(errorMessage(e) || "Failed to load allocations"); } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const current = board?.sets.find(s => s.id === setId) || null; const groupOf = useMemo(() => new Map((current?.assignments || []).map(a => [a.attendeeId, a.groupId])), [current]); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx index 5e4b3ba..1dea102 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -21,6 +21,7 @@ import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRe import { EventPicker } from "@/components/shared/EventPicker"; import { AttendeeFormModal, formsStillNeeded } from "@/components/shared/AttendeeFormModal"; import { apiV2, apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" }; @@ -1103,7 +1104,7 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo, onF }, [token, eventId]); // Again when the registration changes: its tickets may have just been issued. - useEffect(() => { load(); }, [load, registration]); + useExternalEffect(() => { void registration; load(); }, [load, registration]); if (!registration) { return ( @@ -1572,7 +1573,8 @@ function SendTicketsModal({ open, onClose, token, registration }: { const [localError, setLocalError] = useDismissingState(""); const [localInfo, setLocalInfo] = useState(""); - useEffect(() => { + // Each time it opens: start from the registration's details. + useStateSync(() => { if (open && registration) { setPhone(registration.user?.phoneNumber || ""); setEmail(registration.user?.email?.endsWith("@guest.local") ? "" : registration.user?.email || ""); @@ -1706,7 +1708,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded const [saving, setSaving] = useState(false); const [localError, setLocalError] = useDismissingState(""); - useEffect(() => { + useStateSync(() => { if (open) { setAmount(""); setReason(""); setLocalError(""); } }, [open, setLocalError]); @@ -1842,7 +1844,7 @@ function DoorRefundPanel({ token, eventId, setInfo }: { } }, [token, eventId]); - useEffect(() => { + useExternalEffect(() => { load(); }, [load]); @@ -2004,7 +2006,7 @@ function NewAttendeeModal({ open, onClose, seed, onConfirm }: { const [err, setErr] = useState(""); // Pre-fill name from whatever was typed in search - useEffect(() => { + useStateSync(() => { if (open) { setName(seed || ""); setEmail(""); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx index 03c4450..efa2bef 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx @@ -12,6 +12,7 @@ import type { AttendanceRegister, AttendanceRow, Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; +import { useExternalEffect, useNow } from "@/lib/hooks"; type Filter = "all" | "completed" | "not_completed" | "missed_recent"; @@ -65,12 +66,13 @@ function AttendancePageInner() { setBusy(false); } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const columns = useMemo(() => (reg?.columns || []).filter(c => showCancelled || !c.cancelled), [reg, showCancelled]); const multi = reg?.event.scheduleType === "sessions"; // Sessions already held (for "missed the last two"). - const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < Date.now()).map(c => c.id), [reg]); + const now = useNow(); + const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < now).map(c => c.id), [reg, now]); const rows = useMemo(() => { const q = query.trim().toLowerCase(); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx index ff74667..79ca028 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx @@ -11,6 +11,7 @@ import { BackLink } from "@/components/shared/BackLink"; import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] }; type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] }; @@ -108,7 +109,7 @@ export default function BundlesPage() { }, [token, canView, setError]); // Start on the next upcoming event (or the latest one). - useEffect(() => { + useStateSync(() => { if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents)); }, [allEvents, eventId]); @@ -127,7 +128,7 @@ export default function BundlesPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const toggleActive = async (b: EventBundle) => { try { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx index 426bfe2..57d17dd 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx @@ -13,6 +13,7 @@ import type { Event, ConsentRow, MedicalRow } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const STATUS_STYLE: Record = { @@ -70,7 +71,7 @@ export default function ConsentTrackerPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const rows = useMemo(() => { const all = data?.rows || []; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx index 84babee..721dbc7 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx @@ -9,6 +9,7 @@ import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, Li import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; @@ -176,7 +177,7 @@ export default function CouponsPage() { } }, [token, setError]); - useEffect(() => { if (token && canView) load(); }, [token, canView, load]); + useExternalEffect(() => { if (token && canView) load(); }, [token, canView, load]); // Codes that can still be used first; off, expired and used-up ones only when asked for. const visible = useMemo(() => { @@ -422,7 +423,10 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [userQuery, setUserQuery] = useState(""); - const [userResults, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); + const [foundUsers, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); + const searchingUsers = d.restrictTo === "users" && userQuery.trim().length >= 2; + // Only while there's a search (a shorter query clears the list without another render). + const userResults = searchingUsers ? foundUsers : []; const [eventQuery, setEventQuery] = useState(""); const [showPast, setShowPast] = useState(false); const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); @@ -443,7 +447,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { const scopedEvents = useMemo(() => events.filter(e => d.eventIds.includes(e.id)), [events, d.eventIds]); useEffect(() => { - if (d.restrictTo !== "users" || userQuery.trim().length < 2) { setUserResults([]); return; } + if (!searchingUsers) return; const t = setTimeout(async () => { try { const res = await (apiV2Data("get", "/users", { query: { search: userQuery.trim(), limit: "8" }, authToken: token }) as Promise<{ data: { id: string; name: string; email: string }[] }>); @@ -451,7 +455,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { } catch { setUserResults([]); } }, 300); return () => clearTimeout(t); - }, [userQuery, d.restrictTo, token]); + }, [userQuery, searchingUsers, token]); const toggleEvent = (id: string) => { const eventIds = d.eventIds.includes(id) ? d.eventIds.filter(x => x !== id) : [...d.eventIds, id]; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx index 75a62bf..3499e21 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -14,6 +14,9 @@ import { MessageKindPicker, matchedText, type MessageKind } from "@/components/s import { CampusAudiencePicker } from "@/components/shared/CampusAudiencePicker"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { AiDraftMessage } from "@/components/shared/AiDraftMessage"; +import { AiImprove } from "@/components/shared/AiImprove"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; type Attendee = { id: string; name: string; email: string; pref: string }; type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets'; @@ -209,10 +212,12 @@ function EmailAttendeesPageInner() { }, [token, setError]); // Reload when the signed-in user changes too (e.g. after an impersonation switch). - useEffect(() => { loadEvents(); }, [user, loadEvents]); + useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]); + const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]); + const [loadingUsers, setLoadingUsers] = useState(false); // Load users for broadcasts - useEffect(() => { + useExternalEffect(() => { const run = async () => { try { if (!token) return; @@ -234,7 +239,7 @@ function EmailAttendeesPageInner() { // Form state const [eventId, setEventId] = useState(preselectEventId); - useEffect(() => { + useStateSync(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]); @@ -243,8 +248,6 @@ function EmailAttendeesPageInner() { const [showInfo, setShowInfo] = useState(false); // Broadcasts state - const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]); - const [loadingUsers, setLoadingUsers] = useState(false); const [selectedUserIds, setSelectedUserIds] = useState([]); const [broadcastEventId, setBroadcastEventId] = useState(""); const [broadcastSubject, setBroadcastSubject] = useState(""); @@ -289,7 +292,7 @@ function EmailAttendeesPageInner() { } }, [token]); - useEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]); + useExternalEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]); const openEdit = (job: ScheduledJob) => { setEditing(job); @@ -351,7 +354,8 @@ function EmailAttendeesPageInner() { // Event helper to prefill templates const currentEvent = useMemo(() => (events || []).find(e => e.id === eventId), [events, eventId]); - useEffect(() => { + // A template fills in the subject and message, unless they were typed over. + useStateSync(() => { const title = currentEvent?.title || 'the event'; if (templateKey === 'payment_reminder') { if (!subjectDirty) setSubject(`Payment reminder: ${title}`); @@ -614,9 +618,13 @@ function EmailAttendeesPageInner() { {templateKey !== 'tickets' ? (
+
+ { setSubject(d.subject); setSubjectDirty(true); setBody(d.body); setBodyDirty(true); }} /> +