diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 18d1b94..cc04ffb 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -49,6 +49,34 @@ and this project follows [Semantic Versioning](https://semver.org/). 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). ## [1.52.3] - 2026-11-02 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/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..0c7b47e 100644 --- a/apps/events/backend/package-lock.json +++ b/apps/events/backend/package-lock.json @@ -10,6 +10,7 @@ "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 be2f6ba..5d376e8 100644 --- a/apps/events/backend/package.json +++ b/apps/events/backend/package.json @@ -22,6 +22,7 @@ }, "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", @@ -35,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/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/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/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/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/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/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/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/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 84a1dc6..dd1fdb8 100644 --- a/apps/events/backend/tests/v2.test.ts +++ b/apps/events/backend/tests/v2.test.ts @@ -392,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 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/ROADMAP-v2.md b/apps/events/docs/ROADMAP-v2.md index 8c9b511..56133b3 100644 --- a/apps/events/docs/ROADMAP-v2.md +++ b/apps/events/docs/ROADMAP-v2.md @@ -11,18 +11,18 @@ 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). **2.0.0 is in progress** on the `release/2.0` branch, tagged only +**Status (2026-11-02):** all features in this document are approved, and everything before 2.0.0 +has shipped (1.32.0 – 1.52.3). **2.0.0 is in progress** on the `release/2.0` branch, tagged only when all of it is in (decided 2026-10-30): | # | 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 | `release/2.0` | ✅ committed (WIP) | -| 3 | The five helpers (§15) with their buttons, an eval set, privacy notice text | `release/2.0` | next | -| 4 | v1 removed (webhook paths and old message links keep working) | `release/2.0` | to do | -| 5 | Migration guide, docs | `release/2.0` | to do | -| 6 | Marketing site: Cross Code with a Cross Events page (§17) | its own repo | to do | +| 3 | The five helpers (§15) with their buttons, an eval set, privacy notice text | `release/2.0` | ✅ committed (WIP); 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 | `release/2.0` | ✅ v1, passwords, `node-fetch` (2026-11-02); lint rules in progress | +| 5 | Migration guide (`MIGRATING-TO-2.md`), docs | `release/2.0` | guide ✅ (2026-11-02); docs in progress | +| 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. @@ -845,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 | --- @@ -1103,6 +1103,7 @@ feature. | — | 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) | @@ -1126,4 +1127,3 @@ feature. - **Marketing site (§17):** repository, domain(s), hosting, whether prices are shown, and the contact route. -- **Password hashing upgrade** (§14): in 2.0 or later. 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/src/lib/api-v2/openapi.json b/apps/events/frontend/src/lib/api-v2/openapi.json index cbcc0ee..c5e50fc 100644 --- a/apps/events/frontend/src/lib/api-v2/openapi.json +++ b/apps/events/frontend/src/lib/api-v2/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Cross Events API", "version": "v2", - "description": "Version 2 of the Cross Events API. Every response is JSON:\n- a single item is `{ \"data\": { … } }`;\n- a list is `{ \"data\": [ … ], \"meta\": { \"page\", \"limit\", \"total\", \"pages\" } }`, paged with `?page=` and `?limit=` (at most 100);\n- an error is `{ \"error\": { \"code\", \"message\", \"fields\"? } }` with a stable `code`.\n\nDates are ISO 8601 in UTC; amounts are in rand. Sign in through the app and send the token as `Authorization: Bearer `.\nVersion 1 (`/api/…`) keeps working while the app moves over; it will be removed in 2.0." + "description": "Version 2 of the Cross Events API. Every response is JSON:\n- a single item is `{ \"data\": { … } }`;\n- a list is `{ \"data\": [ … ], \"meta\": { \"page\", \"limit\", \"total\", \"pages\" } }`, paged with `?page=` and `?limit=` (at most 100);\n- an error is `{ \"error\": { \"code\", \"message\", \"fields\"? } }` with a stable `code`.\n\nDates are ISO 8601 in UTC; amounts are in rand. Sign in through the app and send the token as `Authorization: Bearer `.\nVersion 1 (`/api/…`) was removed in 2.0: its addresses answer `410 Gone`. See the migration guide (MIGRATING-TO-2.md)." }, "servers": [ { @@ -21285,20 +21285,30 @@ ] }, "cashDenominations": { - "anyOf": [ - { - "type": "object", - "properties": {}, - "additionalProperties": {} + "type": "array", + "items": { + "type": "object", + "properties": { + "value": { + "type": "number", + "description": "The note or coin, in rand" + }, + "count": { + "type": "number" + } }, - { - "type": "null" - } - ] + "required": [ + "value", + "count" + ], + "additionalProperties": {} + }, + "description": "Counted cash by note and coin" } }, "required": [ - "rows" + "rows", + "cashDenominations" ], "additionalProperties": {} } @@ -59217,10 +59227,14 @@ } }, "actions": { - "type": "array", - "items": { + "type": "object", + "propertyNames": { "type": "string" - } + }, + "additionalProperties": { + "type": "string" + }, + "description": "Every action, with its label" }, "actors": { "type": "array", diff --git a/apps/events/frontend/src/lib/api-v2/schema.d.ts b/apps/events/frontend/src/lib/api-v2/schema.d.ts index 1961b77..d3f2bbb 100644 --- a/apps/events/frontend/src/lib/api-v2/schema.d.ts +++ b/apps/events/frontend/src/lib/api-v2/schema.d.ts @@ -16134,9 +16134,14 @@ export interface operations { [key: string]: unknown; }[]; cashActualTotal?: number | null; - cashDenominations?: { + /** @description Counted cash by note and coin */ + cashDenominations: ({ + /** @description The note or coin, in rand */ + value: number; + count: number; + } & { [key: string]: unknown; - } | null; + })[]; } & { [key: string]: unknown; }; @@ -33791,7 +33796,10 @@ export interface operations { } & { [key: string]: unknown; })[]; - actions: string[]; + /** @description Every action, with its label */ + actions: { + [key: string]: string; + }; actors: ({ id: string; name: string; diff --git a/apps/events/playwright.config.ts b/apps/events/playwright.config.ts index d1e1759..c23a423 100644 --- a/apps/events/playwright.config.ts +++ b/apps/events/playwright.config.ts @@ -35,7 +35,7 @@ export default defineConfig({ // tsx runs the TypeScript straight from src/ (never a stale dist/ build). command: "node ../e2e/support/prepare-db.js && npx tsx src/index.js", cwd: "backend", - url: `http://localhost:${API_PORT}/api/settings/needs-setup`, + url: `http://localhost:${API_PORT}/api/v2/setup/needed`, timeout: 180_000, reuseExistingServer: !ci, stdout: "ignore",