diff --git a/apps/events/.gitignore b/apps/events/.gitignore new file mode 100644 index 0000000..49441fa --- /dev/null +++ b/apps/events/.gitignore @@ -0,0 +1,50 @@ +# dependencies +node_modules/ + +# env files (never commit real secrets — .env.example files are fine) +.env +.env.* +!.env.example + +# IDE +.idea/ +.vscode/ + +# next.js +.next/ +out/ + +# build output +dist/ +build/ + +# logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* +*.log + +# typescript +*.tsbuildinfo + +# OS +.DS_Store +Thumbs.db + +# this install's PM2 config (made from ecosystem.config.example.js; deploys never touch it) +/ecosystem.config.js + +# misc scratch / generated files +temp/ +backend/public/uploads/ +backend/backups/ +hope-events-deployment-setup.txt + +# runtime data stores (mutated by the running app, not source) +backend/data/scheduled-emails.json +backend/data/banner.json +# end-to-end tests +e2e/.data/ +e2e/report/ +e2e/test-results/ +frontend/.next-e2e/ diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md new file mode 100644 index 0000000..7ff8f07 --- /dev/null +++ b/apps/events/CHANGELOG.md @@ -0,0 +1,2263 @@ +# Changelog + +All notable changes to this project are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project follows [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [2.1.1] - 2026-11-03 + +### Fixed + +- **Feedback "Send now" and "Remind" no longer make the page wait** for every email: they work out + who they're going to, answer straight away ("Sending the feedback form to 40 people in the + background", "Reminding 12 people. It carries on in the background.") and the emails go out in a + background task. The Feedback page refreshes itself a few times to show them land. + +### Added + +- **One-off background tasks** (`enqueueTask` in `src/jobs/index.js`, first one `feedback-send` → + `runFeedbackTask` in `utils/feedback.js`): queued in pg-boss (retried twice, kept across a + restart), or run in-process straight after the response when the queue isn't running. Tasks must + be safe to run twice: sending skips people already invited, and a reminder is claimed with the + 24-hour rule, so two tasks at once never remind the same person twice. +- `POST /api/v2/events/{id}/feedback/remind` answers with `queued`; its counts are what's being + sent. `send-now`'s `invited` is how many it's sending to. + +## [2.1.0] - 2026-11-03 + +### Added + +- **Feedback page** (Supervisor → Feedback, `/dashboard/supervisor/feedback`; supervisors and + admins, campus-scoped supervisors see their campuses). Every event with a feedback form, newest + first: sent / scheduled / no send time, answered of asked with the response rate, the average + star rating and the last reminder. One event's page has the per-question **Results** (with the + AI "Summarise feedback" button), each **Response**, and on a named form **People** — who was + asked, who has answered and the reminders each has had. "Send now" before it goes out; "Edit + form" opens the event editor. +- **Remind those who haven't answered** (`POST /api/v2/events/{id}/feedback/remind`): a fresh link + to each, and the form to anyone eligible who hasn't had it yet (e.g. checked in after it went + out). On a named form one person can be reminded (`userIds`). Nobody gets the form or a reminder + twice within 24 hours (`REMIND_GAP_MS`). The automatic 3-day reminder is unchanged. +- `GET /api/v2/feedback` (every form) and `GET /api/v2/events/{id}/feedback/results` (one + event's results, responses and people) — `src/services/feedback.ts`, `src/v2/resources/feedback.ts`. +- `FeedbackInvite.reminderCount`, counting automatic and manual reminders (migration + `20261103120000_feedback_reminders`; existing reminded invites start at 1). +- Access log action **`feedback_responses`**: opening a named form's answers. +- Help page for the Feedback page; Feedback on the supervisor and admin dashboards and in Ctrl+K. + +### Changed + +- **Anonymous forms stay anonymous on the page:** no names on answers, and no list of who has or + hasn't answered (it would give answers away on a small event) — counts only, and no reminding + one person. +- A reminder now only goes to someone who still hasn't answered at the moment it's sent. + +### Removed + +- The planned 2.1.0 AI helpers on the privacy pages (Consent log, Access log) are dropped from + the roadmap. + +## [2.0.2] - 2026-11-03 + +### Changed + +- **Wider income bands in the Hub heartbeat**, from `R0–R1 000` up to `over R10 000 000` (was + `over R100 000`): 14 bands, edges at R1 000, R5 000, R20 000, R50 000, R100 000, R150 000, + R250 000, R400 000, R700 000, R1m, R2.5m, R5m and R10m (`BAND_TOPS` in `src/hub/report.js`). + Every Cross Code licence-tier edge is a band edge; a test checks it. + +### Added + +- **`income.eventIncome12m`** in the heartbeat: the band of the last 12 months' event income + (payments less refunds, without donations, sponsorships or donation legs), which the licence + tier is billed on. Shown on the Hub from Hub 1.6.2. + +### Fixed + +- The heartbeat's income bands counted a donation twice once it was applied to a registration + (the leg payment); they now leave legs out, like every report. + +## [2.0.1] - 2026-11-02 + +### Changed + +- **Summarise this report on every report.** The eight reports that list people (Payments between + dates, Attendees per event, Revenue detailed, Master orders, Cashup audit trail, Parental consent + status, Feedback summary, Medical & emergency list) now have the button too. They're sent as + **anonymised totals**, worked out on the screen (`components/reports/aiReportData.ts`): per event + and method, status or option, with names, emails, who recorded or did what, notes and comments + left out; consent and medical details only as counts (given / pending / declined, with + allergies, on medication, …); feedback as the per-question results without the comments. + `POST /api/v2/ai/summarise-report` accepts every report key; for a people report it refuses + (403 `AI_REPORT_HAS_PEOPLE`) any column that would carry a person (name, email, attendee, + parent, emergency contact, notes, …), so a new column fails safe. Each people-report summary is + recorded in the access log (`ai_report`; sensitive for consent and medical). The prompt tells + the AI the totals are anonymised on purpose. + +## [2.0.0] - 2026-11-02 + +### Added + +- **AI helpers — the plumbing** (2.0, roadmap §15). The site calls AI through the Cross Events Hub + (protocol §3b, Hub 1.6.0), which holds the Claude API key and a monthly allowance in rand per + licence; no key is ever stored on the site. `GET /api/v2/ai/status` says whether to show the AI + buttons: hidden when the licence has no AI (worked out from the licence token, without asking the + Hub), disabled with the reason once the month's allowance is used up or the Hub can't be reached. + The answer is cached for a minute and refreshed by every AI call. `` and + `useAiStatus()` on the frontend; only supervisors and admins see AI. +- **Site settings → AI** (admins): this month's use against the allowance, use per person, per + helper and per day, a switch per helper, and an optional most-uses-per-person-per-day. Admins are + emailed once a month when 80% is used. Changes are audited (`ai_settings_changed`). +- Each AI call is logged in `AiCall` (person, helper, outcome, cost — never the prompt or answer); + anonymising an account unlinks its calls, and calls go after 13 months. Anthropic is added to the + operator register, switched off until a site uses AI. Migration `20261030120000_ai_helpers`. +- v2 errors have a new code, `UNAVAILABLE` (503), for when the Hub or the AI service can't be + reached. +- **The five AI helpers' API** (supervisors and admins): `POST /api/v2/ai/draft-event` (the event + form from a description, with ticket options, early bird, schedule and a budget from the notes), + `/ai/summarise-report` (reports without people in them only), `/ai/draft-message` (email or + WhatsApp, with `{{name}}` and the event placeholders), `/ai/summarise-feedback` (an event's + feedback, sent without who answered; recorded in the access log) and `/ai/improve-text` + (improve, shorter, or only fix mistakes). Every helper is told today's date. Email addresses, + phone numbers and ID numbers in what's sent are swapped for placeholders and put back in the + answer, so they never leave the site. Two checks are worked out in code as well as by the AI: a + weekday that doesn't match its date, and costs a full event can't cover. +- **AI buttons in the app** (only where the licence has AI; supervisors and admins): + - New event → **Describe your event**: a few sentences fill in the form (details, dates, tickets, + early bird; course dates as sessions), with the checks and a budget from the notes to look at + first. Nothing changes until "Fill in the form". + - **Improve / Shorter / Fix mistakes** under the event description, the site banner, and the + email and WhatsApp message boxes; the suggestion replaces the text only with "Use this". + - **Draft with AI** in Email attendees and WhatsApp attendees: a short note becomes the email's + subject and body, or the WhatsApp message, with `{{name}}` and the event's details. + - **Summarise this report** on reports without people in them, and **Summarise feedback** per + event on the Feedback summary report. + - Every suggestion says "AI suggestion — check it before saving". +- **Privacy notice:** the built-in text says how the AI helpers use information and where requests + go (sections 4 and 9). Sites with their own published notice see the change in the notice + editor. +- `npm run ai:eval` (backend): the helpers' eval set — fixed examples run through the site's Hub + connection, with automatic checks on the facts and every answer printed to read. +- **MIGRATING-TO-2.md:** what changes for integrations and for whoever runs the server, with every + v1 address and its v2 replacement. + +### Removed + +- **API v1** (`/api/…`). Every screen has used `/api/v2` since 1.51.16. Any v1 address now answers + `410 Gone` with `code: "API_V1_REMOVED"`, except what outside senders still use: the provider + webhooks (`/api/webhooks/yoco|payfast|whatsapp` and WAWP's oldest `/api/whatsapp/webhook`) and + the links in messages already sent (calendar files and one-click unsubscribe answer `308` with + their v2 address; a mail app's one-click POST to the old address is still handled) — + `legacyV1Router` and `v1Removed` in `src/v2/links.ts`. The 43 v1 route files are gone (the + controllers stay: `v1Route` runs them behind v2 routes); so are the `Deprecation` headers + (`src/v2/deprecation.ts`), the v1 reference at `/docs` (it redirects to `/docs/v2`) and the + hand-written `backend/API_DOCUMENTATION.md` (now a pointer to `/docs/v2`). +- `node-fetch` from the backend's dependencies (nothing used it since the move to native `fetch`). + +### Changed + +- **Passwords are hashed with Argon2id** (`@node-rs/argon2`, 19 MiB, 2 passes) instead of bcrypt. + bcrypt hashes still sign in, and are re-hashed with Argon2id the first time each person signs in + (`needsRehash` in `src/config/auth.js`, used by `logIn`). `bcryptjs` stays only to check those. +- The campus-scope route test runs over the v2 routes (`tests/v2CampusScope.test.ts`): each staff + or supervisor route needs a campus-scope middleware or must be on the list of routes whose + service checks campuses itself. The read-only and impersonation lists name v2 paths only. +- e2e tests call `/api/v2` only (`v2()` in `e2e/fixtures.ts` returns the answer's `data`); + Playwright waits for `/api/v2/setup/needed`. +- Documented shapes corrected: the access log's `actions` (action → label) and a cash-up's + `cashDenominations` (notes and coins). +- **The React Compiler lint rules are errors again** (`set-state-in-effect`, `purity`, + `immutability`, `refs`, `static-components`); the 192 places they flagged are fixed, and + `npx eslint src` reports nothing. New hooks in `frontend/src/lib/hooks.ts`: `useStateSync` (state + that follows other state, set while rendering), `useExternalEffect` (loading from the API or + reading the browser), `useNow` (the time, refreshed each minute); `hardNavigate` in + `lib/navigation.ts` for the full reloads after signing out or switching who is signed in. Other + pages navigate with the router. Several resets moved into the handlers that cause them. +- Small behaviour fixes from that work: the site banner now appears and goes at its set times + without a reload; lists of past/upcoming events stay right on a page left open; registering + goes to the next page without a full reload; popups keep the latest close handler without + writing it during render. + +## [1.52.3] - 2026-11-02 + +### Fixed + +- **Licence read-only mode works again.** The read-only guard (`src/hub/readOnly.js`) only listed + v1 paths, and every screen has used `/api/v2` since 1.51.15 — so a suspended, revoked or + unlicensed site could still create and change events, take registrations and start payments. + The v2 successors of every blocked v1 route are now blocked too (answered as `READ_ONLY` with + reason `LICENCE_READ_ONLY`). A test checks each blocked v2 path is a real route in the OpenAPI + document, so a renamed route can't slip out of the list. + +## [1.52.2] - 2026-11-02 + +### Changed + +- **`scripts/deploy.sh` stops before touching anything when files in the install folder were + changed or added by hand**, and lists them. A setup wizard run on one server had added files to + `backend/src` that the backend build picked up, so the deploy failed halfway and rolled back. + Ignored files (`.env`, uploads, backups, `ecosystem.config.js`) never count. + `ALLOW_LOCAL_CHANGES=1` deploys anyway. +- `bash scripts/deploy.sh --check` runs only that check (no backup, fetch, build or reload). The + script can also be run from a copy outside the install (e.g. `/tmp/deploy.sh`, from the folder + you're in), so an older install can check before updating — see DEPLOYMENT.md, "Updating". + +## [1.52.1] - 2026-11-02 + +### Changed + +- **The API documentation (`/docs/v2`, `GET /api/v2/openapi.json`) now describes every route in + full.** Before, most routes answered by a v1 handler showed an empty body and `data: unknown`. + Each one now documents the body it reads and what it answers, from the handler's actual code, and + every path and query parameter has a description. Actions that take no input say "No body + needed". +- How: `documented: { body?, response? }` on `v1Route` (and `defineRoute`), with shared shapes in + `src/v2/docs.ts`. These are documentation only — requests and answers aren't checked against + them, so nothing an app already does can start failing — but outside production a body or + answer that doesn't fit is logged (`[api/v2] … doesn't match its documented schema`). + `tests/v2Docs.test.ts` keeps the document complete. +- The funnel report's `eventIds` and the webhook deliveries' `status`/`before` filters are now + declared (they worked, but weren't in the document or the typed frontend calls). +- The frontend's generated API types are richer; a few calls had their types tightened to match + (ticket transfer, breach register, kids check-out). Nothing changes in what they send. + +## [1.52.0] - 2026-11-02 — urgent + +### Fixed + +- **Paid door and manual registrations no longer end up without tickets.** On an event with a + required attendee form, tickets wait until a form is in for each person — but At the door and + Manual registration never asked for the form, so payment was recorded and nobody could be checked + in. The form now pops up when someone is registered, selected or pays at the door (and after + registering or paying in Manual registration): fill it in, or **Fill in later**, which issues the + tickets once it's paid and sends the payer a link to the form (`POST + /api/v2/registrations/{id}/form-later`, staff; `Registration.formWaivedAt`). Closing the popup + counts as Fill in later. The door's check-in panel says when a form is holding tickets back. +- **Picked-session bookings needed a form per session.** A person booked on three sessions needed + three forms before their tickets were issued; each person now needs one (`formPlaces` in + `utils/ticketUtils.js`). +- **A required form with only statements and headings held tickets back for ever** (nothing to + answer). Only a required form with a question counts now (`formNeedsAnswers`). Every place that + decided this on its own (coupon making it free, manual and online registration) now asks the + ticket generator (`formsOutstanding`). +- **Self-service kiosk:** it asked for one form per main ticket picked, so a visitor adding to an + existing registration (or booking picked sessions) could finish with the forms still short and + no tickets. It now asks for the forms the server says are missing (`formsNeeded` on `POST + /api/v2/registrations/manual`). Headings on the form showed as an empty text box; they're shown + as text now, with the statements. +- Recording a payment answers `formsNeeded` when a form still holds the tickets back. + +### Added + +- **Corrections** (admins, `/dashboard/admin/corrections`): every registration at an event — + past and closed ones too — with what needs putting right. Issue all missing tickets at once + (forms left for later); fill in a form; issue tickets before payment ("pay later", the balance + is still owed — `Registration.ticketsReleasedAt`); make it free (the balance is written off as a + complimentary discount, `Registration.complimentaryDiscount`, part of `discountTotal`, shown as + "Complimentary" on invoices and receipts; not on closed events); and check a ticket in or undo it + after the event, for any session (a manual check-in, no message sent). Sending the tickets is a + choice. `/api/v2/corrections/…` (admin): `GET events/{id}`, `POST events/{id}/issue-missing`, + `POST registrations/{id}/tickets`, `POST registrations/{id}/complimentary`, + `POST tickets/{id}/check-in`. Code in `src/services/corrections.ts`. +- Audit actions `attendee_form_waived`, `tickets_issued_override`, `registration_complimentary` + and `checkin_corrected`. Migration `20261102120000_corrections`. + +### Upgrading + +- Update before your next event with a required attendee form. After updating, open Admin → + Corrections for a past event to issue any tickets that went missing (leave "Send them" off if + the event is over). + +## [1.51.17] - 2026-10-30 — security release + +### Security + +- **Forgot password no longer reveals whether an account exists.** It answered "Email not found" + (404) for an unknown address, so anyone could check which emails have accounts. It now gives + the same answer and status for every address, sent before any work that only happens for a + real account (so the response time doesn't tell either); the reset link is made and sent + afterwards. Applies to `POST /api/users/forgot` and `POST /api/v2/auth/password/forgot`. +- **Sign-in no longer reveals it either.** An unknown email answered "User does not exist" (with a + different status on v1); it now gets exactly the answer a wrong password gets, after a password + check against a stand-in hash so it takes as long. +- Forgot password is rate-limited like sign-in, so it can't be used to flood someone's inbox with + reset emails. + +### Upgrading + +- Update as soon as you can. Nothing else changes; the forgot-password page shows the new message. + +## [1.51.16] - 2026-10-30 + +### Added + +- **Incoming webhooks on v2:** `/api/v2/webhooks/yoco`, `/payfast` and `/whatsapp`. New provider + set-ups use them — the PayFast notify URL (every new checkout), the Yoco webhook URL offered in + Site settings → Payments, and the WhatsApp webhook URL. The v1 addresses (`/api/webhooks/…`, + `/api/whatsapp/webhook`) keep working with the same handlers, because a provider may not follow + a redirect on a POST; they now name their v2 address in a `Link` header. +- **Links in sent messages on v2:** "Add to calendar" links point at + `/api/v2/events/{id}/calendar.ics`, and the one-click unsubscribe header at + `/api/v2/unsubscribe/{token}/one-click`. The same links in messages already sent answer `308` + with their v2 address; a mail app's one-click POST to the old address is still handled there. + +### Fixed + +- `/api/webhooks/whatsapp` was an empty stub that answered 500; it now runs the WhatsApp webhook + handler like `/api/whatsapp/webhook`. + +### Upgrading + +- Nothing has to change: existing Yoco and WhatsApp webhook registrations keep working. To move a + registration to its v2 address, generate the Yoco webhook again (Site settings → Payments → Yoco) + and paste the webhook URL shown in Site settings → WhatsApp into WAWP. PayFast moves by itself. + +## [1.51.15] - 2026-10-30 + +### Added + +- **API v2 — privacy and admin:** my privacy (`/me/privacy`, news, my data as JSON or PDF, requests, + accepting the notice), `/privacy/notice`, unsubscribe links (`/unsubscribe/{token}`), the privacy + admin (requests, notice drafts and publishing, operators, consent and access logs, readiness, + retention, breaches); `/admin/audit-log`, jobs, impersonation (`/admin/impersonate/{userId}`, + `/me/impersonation` and its end and log); site settings and first-run set-up (`/settings`, + `/setup`); the Hub; outbound webhooks; backups (including the download); Yoco and PayFast settings + (`/payments/yoco/…`, `/payments/payfast/…`). +- `v1Route` handles `res.download` and `res.sendFile`. + +### Changed + +- **Every API call the app makes now goes to `/api/v2`.** Only the incoming webhooks (Yoco, + PayFast, WhatsApp) and the links in sent messages are still v1 — those are 1.51.16. +- Ending a viewing-as session works on v2 while the session is read-only. + +## [1.51.14] - 2026-10-29 + +### Added + +- **API v2 — people and messaging:** the rest of accounts (`/auth/login/code/resend`, + `/auth/password/forgot` and `/reset`, `/auth/activate`, `/me/sessions/revoke`, `/me/close`, + `/me/activity`, `/me/verify-password`, `/me/two-factor/…`; admin `/users`, `/users/{id}`, + `/users/exists`, sessions and anonymising); `/event-listing` (the full public list the site's event + pages show) and `/admin/events`; messaging an event's people, email and WhatsApp broadcasts, + `/scheduled-messages`, `/automations/schedule`; the WhatsApp connection (`/whatsapp/…`); `/banner`; + `/saved-filters`; `/dashboard/today` and `/search`; `/stats/…`; `/analytics/…`; report files + (`/reports/pdf`, `/excel`, `/email`, `/whatsapp`). +- `defineRoute` refuses a method and path defined twice (the first would silently win). +- `GET /me` also answers `newsPromptPending`, `noticePromptPending`, `twoFactorRequired` and + `campusScope`, so the app's session (and its after-sign-in prompts) comes from v2. + +### Changed + +- Sign-in (including the self-service kiosk's), password reset, two-step sign-in, account + settings, admin users, messaging, broadcasts, WhatsApp set-up, dashboards, saved filters, + reports and the public event lists use v2. + +## [1.51.13] - 2026-10-29 + +### Added + +- **API v2 — kids check-in and volunteers:** my family (`/me/family`, its children and adults); kids + set-up and the check-in desk (`/events/{id}/kids/…`: settings, board, families, check-in and out, + collection codes, duty, offline snapshot and sync; `/kids/check-ins/{id}/…`, `/kids/alerts/{id}/resolve`); + serving (`/me/volunteering`, `/events/{id}/volunteer-roles`, sign-up, swaps, self check-in) and rosters + (`/events/{id}/volunteers` and its QR and settings, roles, assigning, manual check-in, hours). + +### Changed + +- The kids desk, rooms view, family page, serving page and volunteer rosters use v2. + +## [1.51.12] - 2026-10-29 + +### Added + +- **API v2 — tickets and attendance:** `/me/tickets` (+ `/email`), `/tickets` (the staff list, one + ticket, sending, issuing, scan stats and recent scans, the ticket for a QR code), transfers + (`/tickets/{id}/transfer`, `/ticket-transfers/{token}` to accept or decline), `/events/{id}/tickets`; + offline scanning (`/scan-locks`: take tickets offline, snapshot, sync, release, reports); the + attendance register (`/events/{id}/attendance`, its PDF/Excel export) and certificates (issue, + send, revoke, download, preview, verify, `/me/certificates`); allocations (`/events/{id}/allocations`, + `/allocation-sets`, `/allocation-groups`, `/me/allocation-groups`). +- Frontend: `apiV2Raw()` for screens whose helpers pass the path as a string; file downloads + read v2's error shape. +- `v1Route` can run a v1 router (with `map: () => ({ url })`); a chain that answers nothing is a + 404 instead of waiting. + +### Changed + +- Tickets, transfers, offline scanning, attendance, certificates, allocations and the kids room + set-up use v2. + +## [1.51.11] - 2026-10-29 + +### Added + +- **API v2 — money:** payments (`/payments`, `/payments/{id}`, receipts, refunds, donations + assigned to registrations, stats, providers and their settings, open checkouts), payment links + (`/registrations/{id}/payment-link` (+ `/send`), `/payment-links/{id}` — the pay page), + `/donations/checkout`, `/me/payments`; cash-ups (`/events/{id}/cashup` and its counts, draft, close + and reopen, `/cashup-lines/{id}/pending`, `/cashups/audit`); provider transactions; the waitlist + (join, mine, offers by link, the event's list, offer/move/remove); sponsorship; parental consent + (the event's list, medical notes, reminders, the consent form by link); `/form-responses`; and + feedback (set-up, send now, the summary, the form by link). +- **`src/v2/viaV1.ts`:** `v1Route()` — a v2 route answered by the v1 handler, in-process, behind + v2's access checks, validation and docs. v1 JSON becomes `data`; v1 errors become v2 errors with + v1's `code` as `reason`; piped files become downloads. +- The v2 reference (`/docs/v2`) opens with its sections collapsed and has a filter box — with + more than about 130 endpoints Swagger UI stopped drawing the expanded list. + +### Changed + +- Every money screen (payments, at the door, cash-up, consent, waitlist, feedback, forms, the pay + and donate pages, the user dashboard) uses v2. + +## [1.51.10] - 2026-10-29 + +### Added + +- **API v2 — managing registrations:** the staff list (`GET /registrations`, paged, `unpaid`, + `userId`), an event's registrations (`/events/{id}/registrations`), a registration in full + (`/registrations/{id}/full`, `/me/registrations/full`), `PATCH /registrations/{id}/status`, + registering someone (`POST /registrations/manual`), bulk actions (`/registrations/bulk`), changing + items (`PUT /registrations/{id}/items`), the invoice, coupon codes on a registration, named + attendees and their form links, attendee form drafts and responses + (`/registrations/{id}/form-draft`, `/registrations/{id}/form-responses`). +- **`src/services/registrationAdmin.ts`:** everything after a registration is made, moved from + `registrationController.js` (now about 60 lines of v1 wrappers). +- v2 manual registration accepts the same `notificationPreference` and `couponCode` values v1 did. +- Frontend: `fetchAllRegistrations()` reads every page of the staff list. Registrations, at the + door, manual registration, self-service, payments, forms, the attendee composers, reports and + the user dashboard all use v2. + +### Changed + +- The roadmap gives money (payments, cashup, provider transactions, waitlist, sponsorship, + consent, feedback) its own release, 1.51.11; the later areas move up one, and incoming webhooks + and links are now 1.51.16. + +## [1.51.9] - 2026-10-29 + +### Added + +- **API v2 — series, season passes, deals and campuses:** `/series` (list, create, `PATCH`, delete, + `/series/by-slug/{slug}`, `/series/{id}/compare`, `PUT`/`DELETE /series/{id}/follow`); + `/season-passes` (list, create, `PATCH`, delete, `/season-passes/{id}/buy`), + `/season-pass-purchases/{id}/checkout`, `/me/season-passes`; bundle deals + (`/events/{id}/bundles`, `PATCH`/`DELETE /bundles/{id}`, `/bundles/quote`); coupon codes (`/coupons`, + `/coupons/{id}`, `/coupons/redemptions`, `/coupons/check` — always a 200 with `valid`); campuses + (`/campuses`, `/campuses/admin`, `/campuses/by-slug/{slug}`, `PUT /campuses/enabled`, + `PUT /campuses/order`, create, `PATCH`, delete, `/campuses/{id}/audience`). +- **Services:** `src/services/series.ts`, `deals.ts` and `campuses.ts` — the series, season pass, + bundle, coupon and campus controllers are now thin v1 wrappers. +- **v2 errors carry a service's own code as `reason`** (e.g. `CAMPUS_HAS_EVENTS`), like the shared + middleware's codes. +- Frontend: `apiV2Data()` — `apiV2` for screens with their own record types (path, parameters and + body still checked; cast the answer). Series, season passes, bundles, coupons, campuses, the + coupon field and bundle quotes on the register page all use v2. + +### Changed + +- Checking a coupon code on v2 answers `valid: false` with the reason instead of an error; the + coupon field shows that reason as before. + +## [1.51.8] - 2026-10-29 + +### Added + +- **API v2 — the rest of setting events up:** `GET /events/{id}/full` (the event in full — what's + left per ticket, variant and session, form, attachments, bundles, next in series; staff also see + inactive events, creator and email recipients), `GET /events/{id}/calendar.ics`, + `GET /events/by-alias/{alias}`; ticket options (`POST /events/{id}/ticket-options`, + `PATCH`/`DELETE /ticket-options/{id}`) and variants (`POST /ticket-options/{id}/variants`, + `PATCH`/`DELETE /variants/{id}`); attachments (`GET`/`POST /events/{id}/attachments` — multipart — + and `DELETE …/{attachmentId}`, admin `/attachments/status` and `/attachments/sync`); scanning + sections (`/sections`); planned costs (`/events/{id}/costs`, `/costs/{id}`); image uploads + (`/uploads/event-image`, `/uploads/logo`, `/uploads/favicon` — returning `path` and `url`). +- **Services:** `src/services/eventDetails.ts` (from eventController.js, now 1,080 lines, from 2,217 + at the start of 1.51.7) and `src/services/setup.ts` (sections and costs). v1 uses them too. +- **v2 route features:** `file` routes answer with a download (`fileResponse`), and `upload` routes + are described as multipart in the OpenAPI document. +- Frontend: `fetchEvent()` for every event page (the public event and registration pages too), + and `lib/eventSetup.ts` for ticket options, sections, attachments, costs and image uploads. + +### Changed + +- The pre-migration fallbacks for attachments (JSON manifests on disk) are gone from the normal + path; old manifests can still be imported with `/attachments/sync`. +- v1's `GET /api/events/:id` now points at `/api/v2/events/{id}/full` as its successor. +- Roadmap: series, season passes, bundles, coupons and campuses are 1.51.9; later areas move up one + (to 1.51.15). + +## [1.51.7] - 2026-10-29 + +### Added + +- **API v2 — setting events up:** `GET /events/manage` (every event staff may see, hidden ones too; + `past`, `inactive`, `closed`; campus-scoped), `POST /events`, `PATCH /events/{id}` (only what's sent + changes; `sessionChanges` when sessions were sent), `DELETE /events/{id}` (admins; deactivates), + `POST /events/{id}/copy-from`, and `GET`/`PUT /events/{id}/notify-recipients`. Event records are + typed for their core fields and pass the rest through as stored (`z.looseObject`). +- **`src/services/events.ts`:** create, update, deactivate, the staff list, notify recipients and + copy-from moved out of `eventController.js` (2,217 → 1,717 lines), with the schedule helpers + (`withSchedule`, `scheduleData`, `saveSchedule`). v1 uses it too. The pre-migration fallbacks + (retrying without `registrationDeadline`, `goLiveAt`…) are gone — every install has those columns. + Creating an event now also returns its ticket options. +- Frontend: `fetchManagedEvents()` (`lib/api.ts`) — every event picker, the kiosk, reports and the + set-up screens load events through v2; the event wizard creates, saves, copies and sets + notification recipients through v2. v1 deprecation links for these endpoints. + +### Changed + +- **pg-boss 11** (servers are on Node 24). It can't upgrade pg-boss 10's tables, so the job queue + uses a new schema, `pgboss_v11`; schedules are recreated at start, and the admin page's + "recent runs" start again from this release. The old `pgboss` schema is left as it was (it can + be dropped: `DROP SCHEMA pgboss CASCADE;`). pg-boss 11 brings cron-parser 5, so the last + cron-parser 4 deprecation is gone. +- Roadmap: the rest of the events area (event details for staff, ticket options and variants, + attachments, sections, costs, series, season passes, bundles, coupons, campuses, calendar file, + alias) is 1.51.8; the later areas move up one (to 1.51.14). + +## [1.51.6] - 2026-10-29 + +### Fixed + +- **Command palette (Ctrl+K) was missing things.** It listed 9 of the 19 reports — now every + report (built from the report catalogue, so new ones appear by themselves), plus Dashboard, + Reports, Ticket options and My groups, and your own pages (My events & tickets, My payments, + My privacy, My kids, My serving, My attendee forms, Make a donation). Attendee forms now opens + for staff and supervisors too (the page allows them; the palette had it as admin-only). An e2e + test fails when a dashboard page is neither in the palette nor deliberately left out. + +### Changed + +- **Excel exports use ExcelTS** (`@cj-tech-master/excelts` 10) instead of exceljs, which is + unmaintained: same API, no dependencies — the backend has 87 fewer packages and none of + exceljs's deprecated ones (fstream, glob 7, inflight, lodash.isequal, rimraf 2). New + `e2e/excel.spec.ts` opens a real report and attendance export. ExcelTS itself now says it's no + longer developed (its successor, documonster, is pre-1.0); existing versions keep working. +- The backend needs **Node 22 or newer** (`engines`); the servers run Node 24 LTS. +- Roadmap: incoming webhooks and links in sent messages get v2 URLs too (1.51.13), with the v1 paths + still answering; the area releases are now 1.51.7 – 1.51.13. + +## [1.51.5] - 2026-10-29 + +### Changed + +- **Next.js 16** (from 15.5) and **React 19.3**. Builds and dev use Turbopack (Next 16's default); + `tsconfig.json` `jsx` is `react-jsx` (required by Next 16); `images.domains` → `remotePatterns`. +- **ESLint 10** (ESLint 9 is out of support) with Next 16's own flat configs + (`eslint-config-next/core-web-vitals` and `/typescript`, no more FlatCompat). `npm run lint` is + `eslint src` (`next lint` was removed). Next 16's React Compiler-era rules + (`react-hooks/set-state-in-effect`, `purity`, `immutability`, `static-components`, `refs`) are + warnings for now — 181 places, mostly loading data in `useEffect`. +- Removed the empty `middleware.ts` (a pass-through that did nothing; Next 16 renames middleware to + "proxy"), which also drops its 117 kB bundle. + +## [1.51.4] - 2026-10-29 + +### Security + +- **Next.js 15.5.28** (critical: remote code execution through the image optimiser with SVGs, and a + Server Actions denial of service), **@sentry/nextjs 10.78** (critical: middleware bypass), + **zod 4.6.7** (high: memory exhaustion on oversized collections; backend and frontend), + **multer 2.5.0** (high: denial of service from a pending file filter), **nodemailer 10.3.0** + (moderate: three address-parsing flaws that could add recipients), fast-uri 3.1.9 and + ip-address 10.7.5 (moderate). Minimum versions raised in package.json so a fresh install can't + resolve an older one. `npm audit`: frontend and root clean; the backend's 6 remaining reports are + low and dev-only (jest → deepmerge), with no real fix (npm suggests downgrading Jest to 25). + +### Changed + +- **cron-parser 5** (v4 is unmaintained): `CronExpressionParser.parse` in `src/jobs/index.js`. +- **Node 24 LTS** for new installs (`scripts/install.sh`); Node 20 reached end of life in April 2026. + `deploy.sh` warns on servers older than Node 22; DEPLOYMENT.md has "Upgrading Node". +- Roadmap: every endpoint moves to v2 before 2.0 (1.51.5 – 1.51.11). + +### Known + +- Still deprecated, with reasons: exceljs (unmaintained; brings fstream, glob 7, inflight, + lodash.isequal, rimraf 2) — replacing it with ExcelTS waits for approval; ESLint 9 (out of + support) — ESLint 10 needs Next.js 16 (1.51.5); @opentelemetry/sdk-trace-base — pulled in by the + latest @sentry/nextjs, for Sentry to update; glob 10 — inside Jest (dev only). + +## [1.51.3] - 2026-10-29 + +### Changed + +- **Express 5** (from 4). Kept Express 4 behaviour where it changed: the `qs` ("extended") query + parser, and `req.body` as `{}` when a request has no JSON body. `@types/express` 5. +- **The ticket scanner and at-the-door check-in use API v2** (`/api/v2/checkin/{qrCode}`). The v2 + look-up now gives `attendee`, `bookedBy` and `ticketOptionId` (for section checks). +- **Shared middleware answers in the v2 shape on /api/v2:** rate limits, the impersonation and + licence read-only guards, the auth checks and campus refusals write v1's `{ message, code }`; + on v2 that becomes `{ error: { code, message, reason } }` (`reason` = the specific old code, e.g. + `TWO_FACTOR_REQUIRED`, `LICENCE_READ_ONLY`). Read-only answers have the v2 code `READ_ONLY` (403). + The frontend's `apiFetch` treats `reason` like v1's `code`, so the 2FA and impersonation + handling works on v2 calls too. + +### Added + +- **v1 deprecation headers:** v1 endpoints that have a v2 replacement answer with + `Deprecation: @` (RFC 9745) and `Link: <…>; rel="successor-version"` (`src/v2/deprecation.ts`). + The rest of v1 has no replacement yet, so no header. + +## [1.51.2] - 2026-10-29 + +### Added + +- **API v2 accounts:** `POST /auth/signup` (needs `acceptTerms`), `POST /auth/login` (answers + `signed_in` with a token, or `code_required` for two-factor) and `POST /auth/login/code`, both + behind the login rate limit; `PATCH /me` (only what is sent changes; a new password needs the + current one) and `GET /me` now with `notificationPreference` and `homeCampusId`. +- **API v2 check-in:** `GET /checkin/{qrCode}` (look up: holder, what's left, session, consent) + and `POST /checkin/{qrCode}` (check in everyone left or `people`). Every normal result is a 200 + with an `outcome` — `checked_in`, `already_used`, `consent_required`, `wrong_event`, + `wrong_section`, `section_not_found`, `no_session`, `locked`, `transferred`. Staff only, with the + same campus rule as v1. +- **Services:** sign up, log in, the 2FA step and profile changes moved from `userController.js` + (~430 lines shorter) to `src/services/auth.ts`; scan preview and scanning from + `ticketController.js` to `src/services/checkin.ts`. v1 answers exactly as before (`ServiceError` + can carry the old `v1Status`, e.g. 400 for a wrong password, which is 401 in v2). +- v2 routes can take extra middleware (`middleware: [loginLimiter]`). + +### Changed + +- Logging in (and the 2FA code step), signing up, and changing your details or password use API v2. + The scanner stays on v1 until 1.51.3. + +## [1.51.1] - 2026-10-29 + +### Added + +- **API v2 registrations and payments:** `POST /registrations` (signed in, guest for free + events, or a waitlist link), `GET /registrations/{id}`, `POST /registrations/{id}/cancel` and + `POST /registrations/{id}/checkout` (online payment, with an optional donation; answers + `priceUpdated` with the new balance when an early-bird price ran out). Owners only (admins too); + someone else's registration is `NOT_FOUND`. +- **Services in TypeScript:** making and cancelling registrations moved from + `registrationController.js` to `src/services/registrations.ts`, and paying a registration + online from `paymentController.js` to `src/services/payments.ts`. v1 and v2 run the same code; + `ServiceError` carries the HTTP status. `registrationController.js` is ~560 lines shorter. +- **Typed frontend calls:** `npm run api:types` (repo root) writes the OpenAPI document to + `frontend/src/lib/api-v2/openapi.json` and generates `schema.d.ts` from it (openapi-typescript); + `apiV2(method, path, { params, query, body, authToken })` in `frontend/src/lib/apiV2.ts` checks + the path, parameters, body and answer. A backend test fails while the saved document is stale. + +### Changed + +- The register page, "Pay now" (registration success page and My Events) and cancelling on My + Events use API v2. `apiFetch` reads v2 errors (`error.message`, with `code`/`fields` in `data`). + +## [1.51.0] - 2026-10-29 + +### Added + +- **API v2** (`/api/v2`), the groundwork for 2.0: every endpoint is declared once with zod + schemas (`src/v2/route.ts`). The declaration validates the request, strips the response to what + the schema lists, and generates the **OpenAPI 3.1** document (`GET /api/v2/openapi.json`, admin) + shown at **`/docs/v2`** (Swagger UI, served locally). One error shape + `{ error: { code, message, fields? } }` with stable codes, and one list shape + `{ data, meta: { page, limit, total, pages } }`. First endpoints (read-only): `GET /events`, + `GET /events/:id`, `GET /me`, `GET /me/registrations`. v1 (`/api/…`) is unchanged. +- **TypeScript in the backend:** `tsconfig.json` (`allowJs`; `.ts` strict), `npm run build` → + `dist/`, `npm run typecheck`, `npm run dev` through tsx, Jest runs `.ts` via ts-jest. Typed + doors into JS modules in `src/v2/legacy.ts`. +- Tests: `tests/v2.test.ts`, e2e `e2e/api-v2.spec.ts`. + +### Changed + +- The server moved from `backend/src/index.js` to `backend/src/app.js`. `src/index.js` is now a + launcher that runs the matching build in `dist/` (or compiles on the fly with tsx when there is + none), so existing PM2 configs keep working unchanged. +- `scripts/deploy.sh` and `scripts/install.sh` build the backend (`npm ci --include=dev`, then + `npm run build`); a rollback to a release before 1.51.0 skips the build. The first update to + 1.51.0 by an older deploy script still starts (it compiles at start-up); the next update builds. +- e2e starts the backend with tsx. + +## [1.50.2] - 2026-10-29 + +### Added + +- **Searchable event picker** (`components/shared/EventPicker.tsx`) instead of the plain event + dropdowns on staff and supervisor pages (scanner, event tickets, at the door, payments, manual, + email and WhatsApp attendees, forms, attendance, consent, waitlist, allocations, bundles, offline + scans, kids and volunteer set-up, manage registrations, the kiosk). It opens on upcoming events + (soonest first); past ones are behind **Show past events** (latest first), and typing searches + every event by name, campus or date. Keyboard: arrows, Page Up/Down, Enter, Escape. +- **Reports:** the events list can be searched; "Select these N" / "Clear these" act on the matches. +- **Site settings → Webhooks → How webhooks work:** what is sent and when, the envelope and + headers, retries and duplicates, checking the signature (Node.js and PHP), Zapier/Make set-up, + and a copyable example of every event type. `GET /api/outbound-webhooks` event types now carry + an `example`; `tests/webhooks.test.js` checks each one has the same shape as the real payload. + +### Changed + +- Pages that listed every event ever made in their dropdown (email and WhatsApp attendees, forms, + bundles, scanner, payments) now open on upcoming ones; their separate "Include past events" + checkboxes are gone (the picker has its own). Event tickets and Payments can now reach past + events too. +- e2e: `pickEvent()` in `e2e/fixtures.ts`; `e2e/event-picker.spec.ts`. + +## [1.50.1] - 2026-10-29 + +### Added + +- **Audit log:** search by person (name or email), target (type or `#id`) or IP, a Role filter, + **Clear filters**, and "21–40 of 312" under the list. The Action filter now lists every action + that can be logged (it was missing 35 — campuses, kids check-in, volunteers, series, season + passes, webhooks, bulk actions, Hub updates, certificates and more), sorted by name. +- **Data requests:** search by name or email, and closed requests a page (50) at a time — the list + used to stop silently at 200. +- **Webhook delivery log:** filter by status (failed, retrying, succeeded) and **Load older** — + it used to show only the latest 50. +- API filters: `/api/registrations?unpaid=1&userId=`, `/api/payments?userId=&from=&donations=1`, + `/api/privacy/requests?search=&page=&limit=`, `/api/outbound-webhooks/:id/deliveries?before=`, + `/api/admin/audit-log?search=&role=`. Shared `components/shared/Pager.tsx`. + +### Fixed + +- Audit log: the **To** date left out that day's entries (it meant midnight at the start of the + day). Both dates are now whole days in the site's time zone. + +### Changed + +- **Payments** (supervisor) no longer downloads every payment and registration ever made when it + opens: it loads the latest payments, today's (for the totals), donations with what they were + applied to, and only registrations still owing. Refunds load the chosen person's own payments and + registrations when they're picked. Faster as the years add up; the page works the same. + +## [1.50.0] - 2026-10-28 + +### Added + +- **Accessibility pass (WCAG 2.2 AA)** on the public pages, sign-in/sign-up, registration, + payment, My Events and the self-service kiosk: + - **Keyboard:** a "Skip to main content" link as the first Tab stop on every page; a clear focus + ring (in the brand colour) on everything you can tab to; popups (Contact us, Join the waitlist, + Sponsor a spot, Transfer ticket, the registration popup and send dialogs on My Events, the kiosk's + Change Event and Confirm account changes) are announced as dialogs, take focus when they open, + keep Tab inside, close with Escape and hand focus back. The kiosk's "Create an account" switch + and its password eye can now be used with the keyboard. + - **Screen readers:** every form field on those pages has a label tied to it (sign-in, sign-up, + forgot/reset password, activation, profile, privacy centre, payments filters, donate, forms, + feedback, consent, waitlist, sponsorship, transfer, kiosk and its custom questions); ticket + quantity buttons say what they do ("Add one Adult", "Remove one Adult") and the number is + announced; option buttons say which one is chosen; error messages are announced when they + appear. + - **Colour:** light grey text darkened to meet 4.5:1, and links inside sentences are underlined + so they don't rely on colour alone. The page honours "reduce motion" on the device. + - **Branding:** Site settings → Branding (and the setup wizard) warn when the primary colour is + too light for white text and links (under 4.5:1) and offer a darker shade of it in one click. +- Automated accessibility checks: `e2e/accessibility.spec.ts` runs axe-core (WCAG 2.0–2.2 A/AA + rules) on those pages, plus keyboard tests (skip link, popup focus and Escape, ticket quantities, + the kiosk switch). New dev dependency `@axe-core/playwright`. +- `components/shared/ModalOverlay.tsx` for the app's own popups, and `components/layout/SkipLink.tsx`. + +### Changed + +- e2e tests click ticket quantities by name (`/^Add one /`) instead of "+". + +## [1.49.2] - 2026-10-28 + +### Added + +- **Saved filters** on Manage registrations, Users, Events and Reports: set the filters, then + **Saved filters → Save** under a name; click one to apply it; **★** makes it the default, applied + when the page opens (but not over a link that already says what to show, such as the + dashboard's "Waiting for you"). Reports remember the report, events, dates, campus and the + past/inactive/closed options. Per person, stored on the server (up to 30 per page), removed when + an account is anonymised. +- `/api/saved-filters` (list, save, rename/default, delete — your own only). Migration + `20261028180000_saved_filters`. + +## [1.49.1] - 2026-10-28 + +### Added + +- **Bulk actions on registrations** (Admin → Manage registrations): tick registrations, or "Select + all shown" after filtering, and act on them at once — + - **Send a message** by email or WhatsApp, as an event update to the person who registered + (placeholders as on Email attendees); + - **Mark paid** — records what each still owes, by cash, EFT, card or other; paid registrations get + their tickets by email, as with a single payment; + - **Move to another ticket** (one event) — the same lines, issued tickets and QR codes move with + them, repriced at the new ticket's current price, so the difference shows as owing or overpaid; + places on the new ticket are checked first; + - **Put in a room or group** (one event) — their named people, with the group's capacity and + gender rules; + - **Export to Excel** (recorded in the access log, like other exports); + - **Cancel** — coupon uses released and the waitlist offered the places; no refund (record refunds + on the Payments page). + Each runs the same code as doing it one at a time (closed events, payment caps, coupons, + waitlist, privacy rules on messages), with a result per registration. Up to 500 at a time. +- `POST /api/registrations/bulk` (campus-checked for every registration; payments and ticket moves + refused in licence read-only mode); `registrationIds` filter on the email and WhatsApp attendee + endpoints. Audit action `registrations_bulk` (migration `20261028170000_registrations_bulk`). + +## [1.49.0] - 2026-10-28 + +### Added + +- **Today on the dashboard** (staff, supervisors, admins): what's on today — each event, or its + session today — with people checked in so far against places, children in now at kids church, + and volunteers here against rostered (and how many short). Supervisors and admins also see money + in today and over the last 7 days. Refreshes every 30 seconds; follows campus scoping. +- **Waiting for you** (supervisors, admins): what needs someone, each linking to where it's dealt + with — unpaid registrations for events in the next two weeks, young people waiting for parental + consent, waitlists, cover requests, serving roles in the next week short of people, and for + admins past events to cash up, provider payments to reconcile, open privacy requests and failed + webhook deliveries. +- **Command palette — Ctrl K (⌘K)** anywhere in the dashboard, or "Search or jump to…" on the + dashboards: pages, settings tabs and reports for the person's role, actions ("New event", "Scan + tickets", "Record a payment"…), and search — events for everyone; payments by amount ("R450") for + supervisors; people and registrations (by reference) for admins. Keyboard: ↑/↓, Enter, Esc. +- Deep links: `/dashboard/supervisor/events?edit=` and `?new=1`; `/dashboard/admin/registrations?q=&status=&event=`; + `/dashboard/admin/users?q=`. +- `GET /api/dashboard/today`, `GET /api/dashboard/search?q=`. + +## [1.48.2] - 2026-10-28 + +### Added + +- **Four demo seeds**, to match the church a demo is for — `npm run demo:small`, `demo:events` + (the original demo), `demo:ministry` and `demo:multicampus` from the repo root (`demo:list` + describes them; in `backend/` it's `npm run set-demo -- --profile=`). New in the seeds: + multi-session courses with attendance and certificates, a "pick your days" conference, kids church + with families, children, rooms and check-ins (including some checked in right now), volunteer + rosters with QR check-ins and a cover request, an event series with followers and a season pass, + and three campuses with campus-limited staff. Campuses are switched on only for `multicampus`. + Series announcements and volunteer reminders are marked as sent, so the jobs don't email demo + people. See `backend/DEMO_DATA.md`. + +### Fixed + +- **`npm run set-demo` failed since 1.43.0** ("Event_createdById_fkey"): clearing the `Campus` table + with TRUNCATE … CASCADE also emptied `User` (it points at Campus for the home campus), deleting the + admin it keeps. Tables that `User` points at are now emptied with DELETE after the admin's links + to them are cleared. + +## [1.48.1] - 2026-10-28 + +### Changed + +- **Built-in privacy notice brought up to date** with volunteer rosters (what is kept, reminders, + who sees the roster and cover requests), following an event series, season passes, webhooks + (connected systems, what they receive, 30-day copies), how people agree to the notice, and the + `cross_events_dismissed_notices` browser-storage item. Sites that haven't published their own + version show the new text straight away. +- **Sites that published their own version** are now told: Admin → Privacy → Privacy notice lists + what changed in the built-in text since they last reviewed it, marks each section with new text + (**show it** / **Use the new text**), offers **Use all the new text**, and **Add** for built-in + sections the notice doesn't have. **Done — hide this** records the review + (`privacy_notice_builtin_reviewed`). Their own text is never changed without them; publish (with + "Significant change" if people should accept again) to make it live. + +### Fixed + +- **Agreeing to the notice when an account was made for you** — activating an account (made by + staff, at the door or by whoever registered you) now asks you to agree to the Terms of Use and + Privacy Policy, as sign-up does (consent log source "Account activation"). +- **Never accepted?** Anyone who has never accepted any version (accounts made for them, or from + before acceptances were recorded) is asked once after login ("Our privacy notice"), even while + the built-in notice is in use. Before, they were only asked after a version marked as a + significant change was published. +- The "Change my cookie choice" button on the privacy page also shows above a cookie section an + admin wrote themselves (any section whose id mentions cookies), not only the built-in one. + +## [1.48.0] - 2026-10-28 + +### Added + +- **Outbound webhooks** — Site settings → **Webhooks**: send what happens here to other systems + (ChurchSuite, Planning Center, Google Sheets through Zapier or Make…). Add an https address and + choose what to send: `registration.created`, `registration.paid`, `registration.cancelled`, + `payment.received`, `payment.refunded`, `ticket.checked_in`, `user.created`, `event.published`. +- Each message is JSON `{ id, type, createdAt, data }` signed with the webhook's own secret + (`X-CrossEvents-Signature: t=…,v1=…`, HMAC-SHA256 of `.`; shown once, "New secret" to + rotate). **Send test**, a **delivery log** (30 days, with the full message and what came back) and + **Resend**. Failures are retried after 1 min, 5 min, 30 min, 2 h and 12 h, then marked failed. +- Events are noticed in one place (a Prisma client extension in `config/db.js`), so every way of + registering, paying, cancelling, refunding or checking in is covered; each is checked again a + moment later, so a change that was rolled back sends nothing. +- Safety and privacy: https addresses on public networks only (checked again at each send; + redirects aren't followed); each webhook is added to the POPIA operator register (marked inactive + when deleted); kids check-in and volunteer tickets are never sent; deliveries are deleted after 30 + days and with an anonymised account. +- New `webhooks` job (every minute, `WEBHOOKS_JOBS_ENABLED`); `WEBHOOKS_ENABLED=false` stops + noticing events. Audit action `webhook_endpoint_changed` (migration `20261028160000_webhooks`). + +## [1.47.4] - 2026-10-28 + +### Fixed + +- **Update requested, then a newer version came out** — the Licence page said the newer version + was requested ("Version 1.47.3 is available. Update requested …") when the request was for an + older one, and there was no way to ask for the newer version; the update banner stayed hidden. + Now it shows the request ("You asked for version 1.47.0 on …") and, below it, that a newer + version has come out with **Ask for 1.47.3 instead** (Withdraw request stays). The banner shows + again and says to change the request. Changing it is audited as `hub_update_requested` with + `changedFrom`. +- With Cross Events Hub 1.5.0 the Hub moves the open request on to the new version and emails the + provider once; with an older Hub the site withdraws the request and makes it again. + +## [1.47.3] - 2026-10-28 + +### Added + +- **Season passes** — one price for a ticket at each of several events in a series. On the Event + series page supervisors make a pass (name, price, optional sale end) and tick which events and + which ticket (and variant) at each it includes; the form shows what they'd cost separately. Youth + (parental consent) events, staff-only tickets and per-session tickets can't be on a pass. Events + and price are fixed once someone has bought it (switch it off instead); campus-scoped supervisors + can only use their campuses' events. +- **Buying** — on the series page signed-in people choose how many and buy: they're registered at + every event on the pass at once and pay once (a free pass gives the tickets straight away). If + online payment isn't possible the places stay booked and "Your passes" offers **Pay now**. A pass + stops selling when its first event starts. +- **Money per event** — the price is split over the events in proportion to their normal ticket + prices (whole cents). Each registration's line is priced at its event's share, and the payment is + recorded as one payment per event (all linked to the purchase), so each event's cashup and reports + count only its part. Pass registrations aren't repriced by early-bird changes, take no coupon + codes, and their tickets can't be edited. +- `/api/season-passes` (list, create, change, delete; `:id/buy`; `purchases/:id/checkout`; `mine`), + `passes` on `GET /api/series/by-slug/:slug`. Making, changing and buying passes is blocked in + licence read-only mode. Purchases are in "Download my data". Audit action `season_pass_changed` + (migration `20261028150000_season_pass`). + +## [1.47.2] - 2026-10-28 + +### Added + +- **Series: year on year** report (Reports → Other) — pick a series and see each of its events side + by side, oldest first: registrations (not cancelled), tickets, income (as on the dashboard: refunds + counted, donations applied to orders left out) and people checked in (a multi-session event shows + the average per session), with the attendance rate and the change from the event before. Bar charts + of registrations and income; exports to PDF, Excel, email and WhatsApp like the other reports. + Campus-scoped staff see only their campuses' events. **Compare** on each series on the Event series + page opens it (`?report=seriesComparison&series=`). +- `GET /api/series/:id/compare`. + +## [1.47.1] - 2026-10-28 + +### Added + +- **Event series** — group separate events (Camp 2025, Camp 2026; the monthly men's breakfast) on + one page. Supervisors make series on the new **Event series** page (name, web address, + description, picture) and put an event in one with the **Series** box in the event editor; a + copied event keeps its series. A series can have events at several campuses. +- **Series page** `/series/`: what's coming up (event cards) and past events. Each event in a + series shows "Part of …" and **Next in this series** on its page. +- **Follow a series** — signed-in people follow on the series page. When a new event in the series + goes live (and hasn't started) followers get one email, sent as News & announcements: only to + people opted in to news, with the unsubscribe link and one-click headers. New `series` job every + 15 minutes (`SERIES_JOBS_ENABLED`); an event moved into another series is announced to that + series' followers. +- Followed series are in "Download my data" and removed when an account is anonymised. +- API: `/api/series` (list, create, change; delete for admins; `by-slug`; follow/unfollow), + `seriesId` on event create/update, `?series=` on `GET /api/events`, `series` and + `nextInSeries` on `GET /api/events/:id`. Creating and changing series is blocked in licence + read-only mode. Audit actions `series_created`, `series_updated`, `series_deleted` (migration + `20261028140000_event_series`). + +## [1.47.0] - 2026-10-28 + +### Added + +- **Copy an event** — "Copy" on each card on the Events page opens the event editor filled in from + that event: details, campus, sessions, ticket options, variants and early-bird tiers, sections, + the registration form, notification recipients, the feedback questions, certificates and session + reminders. Everything can be changed before saving. A **New start** box at the top moves every + date by the same amount — the end, the sessions, the registration deadline, early-bird deadlines + and the feedback date. On save the event's allocation groups (rooms, buses, teams) are copied + too, and for admins its planned costs (a cost on a ticket option goes to the option with the + same name). Not copied: registrations, coupons, attachments, bundles, the short link, the go-live + time, cancelled sessions, kids check-in (kids ticket and rooms) and volunteer roles. +- `POST /api/events/:id/copy-from` (blocked in licence read-only mode, campus-checked for both + events); `POST /api/events` takes `clonedFromId`, recorded in the `event_created` audit entry. + +## [1.46.2] - 2026-10-28 + +### Added + +- **What's new before you update** — Site settings → Licence shows the release notes for every + version newer than the site, so you can decide whether to ask for the update. Updates that fix a + security problem or a serious bug are marked, and show as a red banner. +- **Withdraw request** — changed your mind after pressing Request update? Withdraw it on the Licence + page and your provider is told not to update the site. +- **Not now** — on the update banner or the Licence page: hides the "update available" reminder until + the next version comes out ("Remind me again" turns it back on). Urgent updates can't be put off. +- **Notices from your provider** — planned maintenance and other messages from your provider show as + a banner at the top of the dashboard for site admins and supervisors, at the times given. Close + one with ×; current notices are also listed on the Licence page. + +- **`WHATS-NEW.md`** — the release notes churches see, in plain language. The Hub reads it from git + with the version tags, so a release needs its section there before tagging. + +Needs Cross Events Hub 1.4.0 for the notes, withdrawing and notices; with an older Hub the site +works as before. + +## [1.46.1] - 2026-10-28 + +### Removed + +- The Gitea CI workflow (`.gitea/workflows/ci.yml`). There's no Actions runner, so every push + left a run stuck on "Waiting". Tests and lint are run by hand before a release, and releases + are deployed with `scripts/deploy.sh` on the server. + +## [1.46.0] - 2026-10-28 + +### Added + +- **Volunteer rosters** — plan who serves where (Supervisor → **Volunteer rosters**). + - **Serving roles** (Welcome, Parking, Kids, Sound…) per event, or per session on a multi-session + event, with the number of people needed, optional shift times and a short description. Each + event or session has its own roster; nothing repeats by itself. + - **Anyone with an account can volunteer:** My account → **Serving** lists events looking for + people and lets you sign up for a role that isn't full. Supervisors can also put someone on a + role (even beyond the number needed). Nobody can be in two roles at the same time. Supervisors + get a sign-up link to share (it works for hidden events too). + - **Reminders** by WhatsApp or email the day before a shift. + - **"Can't make it" swaps:** the volunteer asks for cover, the event's other volunteers are told, + and the first to accept takes the place straight away — no approval. The event's notification + recipients get an email about every swap and every withdrawal. + - **Check-in on the day:** volunteers scan the event's check-in QR code (show it on a screen or + print it) with their phone camera and are checked in for that day's shifts; staff can tick + people in on Staff → **Volunteers**, and undo it. + - **Kids rooms:** a role can be linked to a kids room. Its volunteers count as leaders on duty + in that room once they check in (for the room's ratio), and the room screen lists who is + rostered but not in yet. + - **Free volunteer ticket**, off by default: choose a ticket per event (or add a free + "Volunteer" ticket) and everyone on the roster gets a free place on it unless they already have + a ticket. It's given back when they leave the roster. + - **Roster sheet** with phone numbers, check-in times and a printable view; fill rate per + event; **hours served** per person across events. + - Audit log entries for the volunteer ticket, role changes, people put on or taken off a roster + and check-ins by hand; opening a roster is in the access log. "Download my data" includes + your shifts; anonymising an account gives up its future shifts. + - Background job `volunteers` (every 15 minutes, `VOLUNTEER_JOBS_ENABLED`) sends the reminders. + +### Fixed + +- **The kids check-in ticket was offered publicly:** the free "Kids check-in" ticket from 1.45.0 + showed on the event page and could be booked by anyone. It (and the new volunteer ticket) is now + left out of public event pages and lists and refused on public registration; staff still see it. + +## [1.45.1] - 2026-10-28 + +### Fixed + +- **Privacy notice (built-in text)** brought up to date: kids check-in (what's kept about + children and authorised adults, who sees allergies, medical and custody notes, pickup codes, + offline desk lists, the 6-month deletion), multi-session attendance, session reminders, + certificates and their public check, home campus, WhatsApp sign-in codes, and campus-limited + staff. "Stored on South African servers" is replaced by where the data really is: the site's + own database at the hosting provider in the operator list. It now also says what the site sends + Cross Code's licence server (health and totals, income as a range — no personal information), + and lists the kids check-in browser storage. + Sites that have already published their own notice keep it: review the changes and publish a + new version from Admin → Privacy → Privacy notice. +- **Terms of use:** a new "Kids Check-in" section (pickup codes, parents' responsibility for + their children's details), sessions and certificates, kids messages among the required + messages, and account deletion from the Privacy page. Later sections are renumbered. + +## [1.45.0] - 2026-10-28 + +### Added + +- **Kids check-in** — a secure, fully digital check-in and pickup for children's ministry, run + from a staff desk. No label printers needed. + - **Families are kept between events** (weekly kids church): parents add their children under + My account → **Kids** (date of birth, allergies, medical and custody notes) and list + **authorised adults** who may collect them (no account needed). Staff can find a family by + name or phone, scan the parent's family QR code, or add a new family on the spot. + - **Pickup codes:** checking in gives the family a 4-character code for the day (or session), + shared by the children checked in together. It shows on the parent's phone with a QR code and + is sent by WhatsApp or email (and, if chosen, to an authorised adult). Anyone with the code can + collect. + - **"Write on the sticker" panel:** first name, room, code and a short ALLERGY/MEDICAL alert in + large print, for volunteers to copy onto a blank sticker. + - **Rooms** with an age range, capacity and ratio (children per leader). The desk suggests the + room from the child's age; the room screen shows live cards with allergies, medical and custody + notes, "I'm on duty", and warns when a room is full or over the ratio. + - **Check-out** by typing or scanning the code. A wrong code is refused, shown as an alert on the + room screens and recorded in the audit log; checking out without the code needs a reason. + "Call parent" asks the parents to come to the room. + - **Offline desk:** download the families and 20 pickup codes for the device beforehand, keep + checking in without a connection, and sync afterwards. + - Children show on the **attendance register** and reports: each gets a free place on the event's + kids ticket the first time, and every check-in counts as attendance. + - Set up per event under Supervisor → **Kids check-in setup**; works per campus. + - **Privacy:** allergies, medical and custody notes are encrypted and never put in messages; + opening the desk or room screens is written to the access log; families are in "Download my + data" and anonymising; a new retention rule deletes a child's profile after **6 months** + without a check-in (on by default); a readiness check for it. +- Rooms in Rooms & groups take an age range and a ratio (`minAge`, `maxAge`, `ratio`). + +### Changed + +- Apple and Google Wallet tickets are removed from the 2.0 plan. + +## [1.44.0] - 2026-10-27 + +### Added + +- **Staff for some campuses** (Admin → Users → "Limit to campuses", while campuses are on). A + supervisor or staff member limited to some campuses sees only those campuses' events plus + events for all campuses — in every list, report, dashboard, the scanner and offline scanning. + - **Events for all campuses:** they can scan, register people and take payments at the door, but + not change them, cash them up or refund them (the event editor opens read-only). + - **New events** go at one of their campuses; they can't move events to another campus. + - **Admins and supervisors for every campus only:** the site banner, payment reconciliation and + open online checkouts, and donations not linked to an event. + - **Messages:** broadcasts only to people at their campuses or attendees of their events (no + typed-in addresses). **Coupons:** only for their campuses' events. + - Another campus's records answer "not found"; the **scanner says which campus** a ticket is + for. Staff still see their own registrations for any campus's event. + - Their dashboard says which campuses they work with. Admins are never limited, and limits are + ignored while campuses are off (the Campuses tab warns first). Changing someone's limits is in + the audit log; a campus with staff limited to it can't be deleted. + - Every staff and supervisor route declares how it handles campus limits, and a test fails on + any that doesn't (`tests/campusScopeRoutes.test.js`). + +## [1.43.0] - 2026-10-27 + +### Added + +- **Campuses** (Site settings → Campuses, off by default) for a church with more than one campus + in one install. Churches with one campus see no campus fields anywhere. + - Admins turn campuses on, then add, order, archive and delete campuses: name, web address, + address, contact, colour, logo, default event location, and staff who get that campus's daily + summary. A campus with events can't be deleted, only archived. Turning campuses off hides + everything campus-related and deletes nothing. + - **Events** belong to one campus or to **All campuses** (church-wide). Choosing a campus fills + in its default location; moving an event to another campus is in the audit log. The Events + list in the dashboard shows each event's campus and has a campus filter. + - **Public site:** a campus filter on the events page, remembered in the visitor's browser and + starting on their home campus; a campus shows its own events plus church-wide ones. The campus + shows on event cards, the event page and ticket PDFs. **Campus pages** at `/campus/` + (also in the sitemap). + - **Home campus** on the profile page. + - **Reports and dashboards:** a campus filter on Reports (all reports and the funnel) and on the + admin and supervisor dashboards' past-month tiles, with a church-wide total. + - **Broadcasts:** "Everyone at a campus" in Email and WhatsApp broadcasts — people whose home + campus it is, plus (ticked) people who registered for its events in the last 12 months. News + consent still applies. + - **Daily summary:** campus recipients also get the summary of their campus's events. + - The Hub heartbeat reports whether campuses are on and how many there are (`campusCount`). + - Campus-scoped staff (supervisors and staff limited to some campuses) follow in 1.44.0. +- The privacy notice lists the new `hope_events_campus` browser-storage item. + +### Fixed + +- "Request update" (1.42.0) wasn't written to the audit log: the `hub_update_requested` action was + missing from the database. The request itself always worked. + +## [1.42.1] - 2026-10-27 + +### Changed + +- **The production Hub's public key is built in** (`backend/src/hub/publicKey.js`), so sites can + check licences without `HUB_PUBLIC_KEY` in their `.env`. `HUB_PUBLIC_KEY` still overrides it (for + a local Hub while developing). + +## [1.42.0] - 2026-10-27 + +### Changed + +- **"Request update" instead of the deploy command.** When a new version is out, Site settings → + Licence shows a **Request update** button instead of `bash scripts/deploy.sh …`. It sends a + signed request to the Hub (`docs/hub-protocol.md` §3a), which tells the provider; the site never + updates itself. Afterwards it shows "Update requested on …" until the site runs that version, and + the "update available" banner for admins goes away. Logged in the audit log + (`hub_update_requested`). Needs Cross Events Hub 1.1.0; an older Hub answers "The Hub doesn't take + update requests yet". + +## [1.41.3] - 2026-10-27 + +### Changed + +- **The platform is now called Cross Events** (and the Hub, Cross Events Hub): Site settings → + Licence, the "update available" banner, the setup wizard, the audit log, help and the docs. + Technical names stay as they are (`hope-events` repo, PM2 and nginx names, install folder, browser + storage keys), so existing installs and sign-ins keep working. + +## [1.41.2] - 2026-10-27 + +### Fixed + +- **Background jobs page showed last-run times two hours ahead** (e.g. 12:55 at 10:55). Prisma's + Postgres adapter dropped the time-zone offset of pg-boss's timestamps; the query now reads them + as UTC. Job history itself was never wrong. `APP_TIMEZONE` is now in `backend/.env.example` and + SETTINGS.md. + +## [1.41.1] - 2026-10-27 + +### Changed + +- **No licence now means read-only**, the same as a suspended licence: a site that isn't connected + to the Hub can't create events, registrations or payments until a licence key is connected + (admins see a red banner). `LICENCE_CHECK_DISABLED=true` switches this off outside production, + for the end-to-end tests. +- **Read-only mode also blocks editing events**, their options and their variants (suspended, + revoked and unlicensed sites). +- The site **checks in with the Hub 30 seconds after starting**, and 30 seconds after a licence + key is connected, instead of waiting up to 15 minutes. + +### Fixed + +- A site the Hub no longer knows (`INSTALL_NOT_FOUND`, e.g. the licence was released) kept showing + "Active" on its old licence. It now drops the connection and licence, and shows "No licence". + +## [1.41.0] - 2026-10-26 + +### Added + +- **Hope Events Hub connection** (`docs/hub-protocol.md`). Each install connects to the Hub + (`events-hub.crosscode.co.za`) with a licence key: + - **Licence step in `/setup`** (on the last screen), and **Site settings → Licence** for existing + installs: connect, see the licence (licensed to, plan, end date, grace period), the last check-in, + and "Check now". + - A **heartbeat every 15 minutes** (`hub-heartbeat` job; `HUB_HEARTBEAT_ENABLED=false` to switch off): + version, health (database, background jobs, last backup, free disk, server errors, pending + migrations) and totals (users, events, registrations, tickets, check-ins, payment providers, income + as a range only). Never anyone's personal information. + - **Licences are checked on the site** with the Hub's public key, so a Hub outage never switches a + site off and a licence can't be faked by editing the database: + - **Grace period** (licence past its end date, default 14 days): everything works; **only site + admins** see "Licence needs renewing — X days left". + - **Suspended or revoked**: read-only — no new events, registrations, tickets, payments, waitlist + places, coupons or bundles. Tickets still scan; all data can still be viewed and exported; + refunds, cancellations and privacy requests still work. + - Not connected yet: works as before; admins see "Connect to the Hub". + - **Update available**: admins see when a newer version is out, with the command to run. +- **`/health`** — status, version, database, background jobs and last backup, for monitoring. +- **Install script** (`scripts/install.sh`): a fresh Ubuntu server to a running site in one command — + Node 20, PostgreSQL, PM2, nginx, HTTPS, configuration, migrations, build; then `/setup`. + +### Changed + +- The generic settings endpoints never read or write the Hub connection (install id, secret, licence). + +## [1.40.0] - 2026-10-23 + +### Added + +- **POPIA toolkit, part 3.** Three new tabs on Admin → Privacy (POPIA): + - **Readiness** (now the first tab): a checklist with a score — Information Officer and legal details set, privacy notice published, operators described (no generic names, a location for each), retention reviewed and the job running, no overdue requests, breaches reported to the Regulator, unsubscribe links working (`BACKEND_URL` on https), email set up, WhatsApp STOP replies arriving, two-factor login required, backups running. Each open item links to where you fix it. + - **Retention**: how long personal information is kept, with what each setting would affect right now. A nightly job (`retention`, 03:30; `RETENTION_JOBS_ENABLED=false` to switch off) applies it: + - **Inactive accounts** — no login, registration, payment or being named as an attendee for **5 years**: a warning by email (or WhatsApp) 30 days before, then the account is anonymised. Logging in keeps it. Never staff, supervisors or admins, and never while they have a registration for an upcoming event. **On by default.** + - **Attendee form answers** — deleted 12 months after the event. + - **Login history** — kept 24 months. + - **Payer names and emails in Yoco/PayFast notifications** — removed after 24 months (payments themselves are kept). + - **Audit log, access log and "view as" sessions** — kept 5 years. + - Medical details, visit statistics and backups keep their existing settings, shown alongside. "Run now" applies them straight away. + - **Breaches**: a register of security compromises (what happened, what information, who, consequences, what was done, advice to the people affected), with status and the dates the Information Regulator and the people affected were told. Each entry has a draft message for the people affected and a summary for the Regulator's form, ready to copy. +- **Children's and medical information** is flagged in the access log (medical lists, and anything about an event that asks for parental consent), with a filter. +- The privacy notice gets a `{retention}` placeholder — one line per retention period, following the settings. The built-in notice uses it; if you already published your own version, add a line with `{retention}` to your retention section. + +## [1.39.0] - 2026-10-23 + +### Added + +- **POPIA toolkit, part 2: the admin side.** A new **Admin → Privacy (POPIA)** page with four tabs: + - **Privacy notice editor.** The privacy notice is now editable. It starts from the built-in text (updated for 1.38.0's privacy page, news opt-in, unsubscribe and STOP), one box per section; add, remove and reorder sections, save drafts, preview, and **publish numbered versions**. Placeholders such as `{org}`, `{ioName}`, `{ioEmail}`, `{medicalRetentionDays}` and `{operators}` are filled in when the notice is shown, so it follows Site settings and the operator register. Earlier versions stay readable on the privacy page (`/legal/privacy?version=N`). + - **Re-accepting the notice.** When publishing, tick "Significant change" (and say what changed) to ask everyone to accept the new version: they're asked once, after their next login, with a link to delete their account instead. Sign-up records which version was accepted. Acceptances are counted per version. + - **Operators** — the register of outside services that handle personal information (Yoco, PayFast, WAWP, WhatsApp, email and hosting providers, Google Maps, Sentry), with what each receives and where. Those in use are listed in the notice. + - **Consent log** — every news opt-in/opt-out (and how), every privacy notice acceptance, and every parental consent answer, searchable by person. + - **Access log** — who downloaded, emailed or opened personal information in bulk: report PDFs/Excel files (and reports emailed or WhatsApped), attendance registers, certificate downloads, room/group lists, attendee form answers, the parental consent and medical lists, database backups, and every "view as" session. With how many records each time. +- The contact page shows the Information Officer (when set in Site settings → Legal), with a link to the privacy notice. +- "Download my data" includes the privacy notice versions you accepted. + +### Changed + +- Deleting someone's personal data also removes the IP addresses kept with their consent and notice records (the records stay as proof). + +## [1.38.0] - 2026-10-23 + +### Added + +- **POPIA toolkit, part 1: privacy for the people in the system.** + - **Privacy page** (My account → Privacy): choose News & announcements by email and/or WhatsApp, see the history of those choices, **download my data** (a readable PDF, or the complete copy as JSON: account, registrations and the people registered, form answers, parental consent, payments, tickets and check-ins, certificates, feedback, communication choices), **ask for a correction**, and **delete my account**. + - **Two kinds of bulk message.** When emailing or WhatsApping attendees, or sending a broadcast, choose **Event update** (about an event the recipients registered for — goes to everyone selected) or **News & announcements** (only to people who opted in, with an unsubscribe link). Attendee messages default to event updates, broadcasts to news, and the next-event promo automation is always news. Previews say how many people were skipped. + - **Unsubscribe**: every news email ends with an unsubscribe link and carries one-click unsubscribe headers (Gmail, Apple Mail); every event update says why it was sent and links to the preferences. News WhatsApps end with "Reply STOP" and a link. Unsubscribed addresses without an account are remembered too. + - **WhatsApp STOP**: replying STOP (or "unsubscribe") to the church's number stops WhatsApp news and sends a confirmation. Needs WAWP's webhook pointed at the URL shown in Site settings → WhatsApp (it carries a secret, since WAWP doesn't sign webhooks). + - **News opt-in**: an unticked "news and announcements" box on sign-up. Existing accounts stay opted in (logged as "existing account") and are asked once, after their next login, to confirm or opt out. Every change is logged with when and how. + - **Data requests** (Admin → Data requests): correction and deletion requests with a 30-day due date, emailed to the Information Officer and admins, with a daily reminder for ones due within a week or overdue (`privacy` job, 08:00; `PRIVACY_JOBS_ENABLED=false` to switch off). Completing or rejecting a request emails the person and is in the audit log. + +### Changed + +- **Deleting an account is now a request.** "Delete my account" (and "Also delete my personal data" when closing an account) closes the account straight away; the personal information is deleted when an admin completes the request — after any registration for an upcoming event has been cancelled or the event is over. +- **Deleting personal data now goes much further.** Before, it only cleared the account's name, email and phone. Now it also removes the names and details of the people they registered (and their own details on other people's bookings), form answers, parental-consent details, sponsor names, feedback authorship, pending transfer requests, certificate names, login history, and payer names/emails kept from Yoco and PayFast notifications. Payments, registrations, tickets and check-ins are kept, as "Deleted User", for the books and reports. Admin → Users → Anonymise uses the same deletion, and is refused while the person has a registration for an upcoming event. +- "Download my data" is blocked while an admin is viewing as someone else. + +## [1.37.4] - 2026-10-23 + +### Fixed + +- **Deploy script** (`scripts/deploy.sh`): without a tag it now deploys the latest `main`. The PM2 config is per install: `ecosystem.config.js` is no longer in git (the repo has `ecosystem.config.example.js`), so deploys stop overwriting the install's app names and port; the script keeps the install's copy across checkouts and rollbacks, and creates it from the example on a fresh install. The script also runs from a temporary copy (so checking out a new version of it mid-deploy is safe), and a failure rolls back once. + +## [1.37.3] - 2026-10-23 + +### Fixed + +- The production build (and so the deploy) failed on unescaped quotes in the Payments help text. + +## [1.37.2] - 2026-10-23 + +### Added + +- **Payment status checks** for when a provider's notification never arrives. Payments → Reconcile has a new "Waiting for payment" list: online checkouts from the last 14 days with no payment yet, each with "Check status" (and "Check all"). For PayFast it looks the payment up in PayFast's transaction history and, if PayFast received it, records it exactly as the notification would have (same amount check, tickets and emails). A background job does this every 15 minutes for checkouts between 10 minutes and 3 days old (`payment-status`, switch off with `PAYMENT_STATUS_JOB_ENABLED=false`). Yoco's API has no way to look a payment up, so Yoco checkouts show "can't check" — find them in the Yoco portal and record them with Reconcile, as before. +- **Test connection** on the PayFast settings card: checks the saved merchant ID and passphrase with PayFast. + +## [1.37.1] - 2026-10-23 + +### Changed + +- **No "Pay online" when it can't be used.** When no payment provider is switched on, or the amount is under the R15 minimum, the registration success page, My Events ("Make payment" and "Make donation"), the donate page, "Sponsor a spot", the donation box on the register form and the supervisor Payment Link tab no longer offer online payment. Where it helps, they say why and to pay at the event instead. +- Roadmap: SnapScan and Zapper are dropped (Yoco and PayFast are enough); later releases move up two versions — POPIA toolkit is next as 1.38.0. + +## [1.37.0] - 2026-10-23 + +### Added + +- **PayFast.** A second online payment provider (card, instant EFT and more). Switch it on in Site settings → Payments, then enter the merchant ID, merchant key and salt passphrase from your PayFast (or Sandbox) dashboard and choose Sandbox or Live. Payments are confirmed by PayFast's notification (ITN) at `/api/webhooks/payfast`, which is checked the way PayFast requires: the signature, that it came from PayFast, that PayFast confirms it, and that the amount matches the checkout. PayFast starts switched off. +- **Choosing how to pay.** When more than one provider is on, payers choose on a new "Pay online" page (`/pay/…`). Payment links in emails, WhatsApp and invoices go there too, so they work for every provider. +- Payer-facing wording no longer says Yoco: "Pay online" after registering, a neutral redirect message, and the Terms and Privacy pages name both providers (Yoco or PayFast), including that PayFast may receive your name and email to fill in its payment page. +- A payment of a different amount from the checkout (e.g. changed along the way) isn't recorded automatically: it waits in "Unreconciled Online Payments" with a note explaining why. + +## [1.36.0] - 2026-10-23 + +### Added + +- **Site settings → Payments** (replaces the Yoco tab): turn each online payment provider on or off and set their order. The first one enabled and set up is used by default. Yoco's keys and webhook settings are on the same tab. Yoco is the only provider for now; PayFast, SnapScan and Zapper follow in the next releases. If no provider is on and set up, online payments are off and people pay at the door. + +### Changed + +- Online payments go through one payment provider layer (`backend/src/payments`). Yoco works exactly as before: the same checkout, the same webhook URL (`/api/webhooks/yoco`) and the same reconciliation. +- **Online payments must be at least R15**, for every kind of online payment (balance, part-payment, donation, sponsorship). A smaller balance is paid at the door. +- Payments record which provider took them (`provider`, e.g. "yoco"); existing online payments are marked as Yoco. The payment method (card, Apple Pay…) is unchanged, so cashups and reports add up as before. Provider fees are still never deducted or added — they're handled at cashup. +- Yoco transactions are now "provider transactions" (`/api/provider-transactions`, with `/api/yoco-transactions` still working). The Payments page's reconcile list is called "Unreconciled Online Payments" and shows the provider. The database table is renamed in place, so stored transactions are kept. +- The checkout endpoint is now `POST /api/payments/checkout` (with an optional `provider`); `/api/payments/yoco-checkout` still works. + +## [1.35.1] - 2026-10-23 + +### Added + +- **Waitlist per session.** On pick-sessions events, a full session shows "Join waitlist" in the session list, and the waitlist works per session: when a place in that session frees up, the next person waiting for it gets the offer. Offers never run past the session's start, and nobody is offered a session that has started or was cancelled. The claim link ticks the session for them. My Events, the claim page and the supervisor Waitlist page show which session an entry is for. +- **"All sessions" tickets on pick-sessions events let people choose their sessions.** When an event's "How people book" is "Pick sessions", every ticket now shows the session list. A ticket set to "All sessions" is still one ticket at one price, whatever is ticked. The ticket then only scans on the ticked sessions (online and offline), and the attendance register, certificates, session reminders and session capacity follow them. Tickets and the ticket email list the ticked dates. A ticket set to "Pick sessions" is still charged per session. Events booked as "The whole course" show no session list. Bookings made before this cover every session, as before. +- **Session picker at the door.** The At the door "Select items" pop-up now has the session picker for per-session tickets, so walk-ins can be booked straight in. For a new attendee, a place in today's session is selected by default when there's room. + +### Changed + +- Per-session tickets show their list of sessions straight away (on the registration page, Manual registration, At the door and the self-service kiosk). Before, the list only appeared after pressing "+", so it wasn't obvious you could choose sessions. Ticking a session sets the quantity to 1. + +### Fixed + +- Per-session stock limits on pick-sessions tickets weren't being enforced, and the public event page lost all stock information on events with such a ticket. +- The offline-scanning service worker served the app's script files from its cache first, for good. On a development server, where those files keep their names when they change, a browser that had opened the scanner kept running old code on every page, even after a hard reload. It now fetches them from the network and uses the cache only when offline. Its cache is renamed, so old copies are cleared. +- At the door, editing a registration that has per-session tickets could no longer be saved ("below the quantity already issued"). +- Whole-course tickets: the waitlist now also counts room in sessions that have a capacity, so it no longer says "places available" when a session is full. Places held for waitlist offers now count towards session capacity. + +## [1.35.0] - 2026-10-23 + +### Added + +- **Pick sessions.** A multi-day event can let people choose which sessions to come to — day passes for a conference, or a weekly drop-in class. In the event wizard choose "How people book: Pick sessions", then in Items & Pricing set a ticket to "Pick sessions (price per session)". People tick the sessions they want when they register; each session is its own line and its own ticket, at the per-session price (early-bird and staff prices apply per session; late-joiner pricing doesn't). A session can be booked until it starts (staff can book until it ends). Whole-course tickets can still be sold alongside, and stop selling when the course starts. +- **Session capacity**: in pick-sessions events each session can have a capacity, covering picked places plus whole-course tickets. Full sessions can't be ticked. A per-session ticket's stock limit is places per session. +- Picked-session tickets only scan on their own session ("This ticket is for Class 2 (2026-11-11)…"), on and offline. The attendance register shows one row per person with a dash for sessions they didn't book, and completion and certificates count the sessions they booked. Session reminders go only to the people booked on that session. Tickets, printouts and the ticket email show the session's date. +- The session picker is on the public registration page, Manual registration and the self-service kiosk. +- The roadmap to 2.0 and a handover note are now in the repo: `docs/ROADMAP-v2.md`, `docs/HANDOVER.md` (plus the previous round's spec, `docs/FEATURES-ROUND-1.md`). + +### Changed + +- Per-session tickets can't be changed from My Events' "edit booking" (book more sessions by registering again); they still count towards the total. At the door, per-session tickets are booked from Manual registration (the page says so). + +## [1.34.0] - 2026-10-22 + +### Added + +- **Background jobs page** (Admin → Site Settings → Background jobs): every scheduled job with its schedule, next run and last 10 runs (start, finish, result or error), and a "Run now" button (recorded in the audit log). +- **End-to-end tests** with Playwright (`npm run test:e2e`): they start their own backend and frontend against a separate, freshly seeded database and cover the public pages, free and paid registration through payment, ticket, check-in and cashup, multi-day check-in with the attendance register and certificates, creating a multi-session event in the wizard, the self-service kiosk, and the jobs page. +- **CI workflow** (`.gitea/workflows/ci.yml`): backend tests, frontend lint, typecheck and build, and the end-to-end tests on every push and pull request. It runs once a Gitea Actions runner is registered. +- **Deploy script** (`scripts/deploy.sh `): backs up the database, checks out the tag, installs, migrates, builds and reloads PM2, going back to the previous version if a step fails before the reload. CI runs it over SSH for `v*` tags once the `DEPLOY_*` secrets are set. + +### Changed + +- Timed background jobs (daily summary, waitlist, feedback, session reminders and certificates, consent, analytics rollup, backup, temp cleanup) now run on a job queue in Postgres (pg-boss) instead of in-process timers. Each runs once per schedule even with more than one server process, failed runs are retried, and a slow run never overlaps the next. Schedules are cron, in `APP_TIMEZONE` (Africa/Johannesburg by default) rather than the server's clock; change one with `JOB_SCHEDULE_`, or turn all jobs off with `JOBS_ENABLED=false`. The existing `*_ENABLED` flags still work; the old `*_JOB_INTERVAL_MS` settings are replaced by the schedules. If the queue can't start, the jobs run on timers as before. +- The server lets a running job finish before it stops or restarts. + +### Fixed + +- At the door, the Check-In tab counted every past session's check-in on a multi-day ticket, so from the second session the ticket showed as fully used. It now counts only today's session. + +## [1.33.0] - 2026-10-22 + +### Added + +- **Multi-day events.** An event can run over several sessions, e.g. every Wednesday 18:30–20:30 for 5 weeks. In the event wizard choose "Multiple sessions", create the dates from a repeat pattern (daily or weekly, every N, on chosen weekdays, for a number of sessions or until a date), then edit any session's label, times or location, add one-off dates, or cancel a session (kept for history). People register and pay once and get one ticket for every session. +- The event page shows the schedule (past sessions greyed out, the next one highlighted, cancelled ones struck through). Event cards show "5 sessions · Wed 4 Nov – Wed 2 Dec", and multi-day events stay listed until their last session, sorted by their next one. Calendar files have one entry per session. Ticket PDFs, printed tickets and the ticket email give the session range. +- **Late joining**: a multi-day event closes registration when its first session starts, unless late joining is on (until session N, set per event). Late joiners pay full price, a pro-rata price for the sessions still to come (rounded to the nearest R10, at least R10), or a fixed late price — main tickets only, and never more than the normal price. The event and registration pages say when the late price applies. +- **Per-session check-in**: a multi-day ticket is checked in once per session. The scanner uses today's session (staff can pick another), shows the session on the confirm screen, and says "Already checked in for Week 3 at 18:42" on a second scan. Each event chooses whether check-in is open the whole day of a session (the default) or only from 2 hours before it until it ends. Offline mode downloads the list for today's session, and synced scans count for the session at their scan time. +- **Session reminders**: optional per event — 1 hour, 3 hours and/or 1 day before each session, by email and/or WhatsApp (each person's notification preference still applies). Off by default. +- **Attendance register** (Dashboard → Attendance): attendees × sessions with ticks, totals per session, completion, search and filters (completed, not completed, missed the last two sessions), and Excel/PDF export. Supervisors can tick someone present or absent, recorded in the audit log. Also works for single-date events (one "Checked in" column). +- **Completion certificates**: optional per event, in the wizard's new Attendance step. Four designs (Classic, Modern, Church, Kids) with the site logo and colour, your title and wording ({name}, {event}, {sessionsAttended}, {totalSessions}, {endDate}), an optional signature name, role and image, and who qualifies (every session, at least N sessions, or at least N%). "Preview certificate" shows a sample. Certificates are issued automatically when the event ends (and can be sent automatically), or from the attendance register: issue now, issue to one person anyway, send, download all as one PDF, or revoke. People download theirs under My Certificates on My Events. Each has a code and QR code that anyone can check on the public page `/certificates/verify/`, which shows only the name, event and dates. +- Saving an event where sessions moved or were cancelled offers a "Message attendees" link, since registrants aren't told automatically. +- A background job every 5 minutes sends due session reminders and issues certificates (`SESSION_JOBS_ENABLED=false` to turn it off). The church's timezone for "today" defaults to Africa/Johannesburg (`APP_TIMEZONE` to change). + +### Changed + +- The event wizard has a ninth step, Attendance, for late joining, check-in window, session reminders and certificates. + +## [1.32.0] - 2026-10-22 + +### Added + +- Event cards on the home page and events list show a diagonal "Early bird" ribbon in the top-right corner while the event has an early-bird tier running (deadline not passed and places left on that tier). It isn't shown when the event is sold out, registration is closed or not open yet, or the event is contact-only. + +## [1.31.1] - 2026-10-22 + +### Added + +- Settings → Organisation has a "Google Search Console verification" field. Paste the HTML tag from Search Console and the site outputs it on every page, so each deployment can verify its own domain without uploading a file. + +## [1.31.0] - 2026-10-22 + +### Added + +- The registration funnel's traffic source works without tagged links: visits from Facebook, Instagram, Google, X, LinkedIn and other sites are recognised from where the visitor came from (and Facebook's/Google's click ids). Links without a tag used to count as "direct". WhatsApp still only shows from tagged links (`?utm_source=whatsapp`), since it doesn't pass that on. +- The event page's Share button shares the link tagged `?utm_source=share`, and Save QR encodes it tagged `?utm_source=qr`, so those visits show separately. +- Event pages tell search engines about the event in Google's event format (schema.org `Event`): name, dates, venue, picture, organiser, ticket prices in Rand and whether it's sold out. Google can then show events with their date, venue and ticket link in search results and in its event listings. Contact-only events are listed without tickets. + +### Changed + +- Event pages, the events list and the home page tell search engines their one official address, so `?utm_source=…`, `?src=…` and alias links all count towards the same page in search rankings. Shared event links also carry the event's address. + +## [1.30.1] - 2026-10-22 + +### Changed + +- All tickets now share the design of the tickets printed from the user dashboard: rounded white cards with a light border and soft shadow, the date beside the event name, and the QR code in the middle. This covers the PDF sent by email and WhatsApp (now 6 per page, so the QR codes are bigger) and printing from Event Tickets (staff) and At the door (supervisor). Printed names are now escaped, so a name with `<` or `&` prints correctly. + +## [1.30.0] - 2026-10-22 + +### Added + +- The register form asks for an optional **Donation amount** under the ticket options. Pick a suggested amount (worked out from the ticket total), enter a custom amount (min R15), or choose None. The donation shows in the total and is paid in the same Yoco checkout as the tickets. It's recorded as a separate donation to the event, so it never counts towards the registration's balance. + +### Fixed + +- Event pages with a waitlist crashed with "Attempted to call soldOutLines() from the server". The sold-out helper now lives in `lib/waitlist.ts` so the server page can call it. + +## [1.29.1] - 2026-10-21 + +### Changed + +- The Coupon codes page matches the Bundle deals page and works on phones. Codes show as cards with the discount, events, uses, restrictions, dates and limits. On phones, the edit form and the list of uses open full-width from the bottom, and the discount type is picked from three buttons. +- The coupons list hides codes that are off, expired or used up unless you tick "Show codes that are off, expired or used up". Search also matches event names. +- When creating or editing a code, the Events list shows upcoming events only, soonest first, with a search box and a "Show past events" option. Past events already on the code stay listed so they can be unticked. + +## [1.29.0] - 2026-10-21 + +Run `npm run prisma:deploy` in the backend when deploying. This release adds a migration. + +### Added + +- Bundle deals now come in four types, chosen when you create one: + - **Exact set**: these tickets in these numbers for one price, e.g. 2 adults + 3 kids for R220. This is how bundles worked before. + - **Pick any**: any mix of the qualifying tickets for a set price, e.g. any 4 of Adult or Child for R250, so 2 + 2 and 4 + 0 both count. + - **Buy X get Y free**: in every set of qualifying tickets the cheapest are free, e.g. buy 3, get 1 free. + - **Group discount**: from a group size up, every qualifying ticket costs less (a price per ticket or a percentage off), e.g. 10+ tickets: R70 each. It applies once, to the whole group, and never makes a ticket dearer. +- The deals list and the "Complete bundle" cards on the register form, at the door, manual registration and the kiosk describe each type in one line, e.g. "Any 4 of Adult, Child for R250". For a group discount the button reads "Complete group" and adds the tickets still needed. +- `npm run set-demo`: Family Fun Day also has a pick-any deal, "Lunch for four" (any 4 lunch packs for R220). + +## [1.28.3] - 2026-10-21 + +### Fixed + +- Bundle deals edit form: each ticket row's quantity box filled the whole row, which pushed the ticket picker off the side and added a sideways scrollbar. The quantity box is narrow again, with the ticket picker beside it. + +## [1.28.2] - 2026-10-21 + +### Changed + +- The Bundle deals page has a new layout that works on phones. It shows upcoming events only, soonest first, with a "Show past events" option. Bundles show as cards with their tickets, price, saving, uses and dates. On a phone, the edit form opens full-width from the bottom, and its price section shows the standard price, the bundle price and the saving side by side. + +## [1.28.1] - 2026-10-21 + +### Added + +- At the door, manual registration and the self-service kiosk now list the event's bundle deals and show the same bundle cards as the register form: once a ticket from a bundle is picked, **Complete bundle** tops up the ticket numbers, and **+** adds another full set. + +### Fixed + +- At the door now has the same "← Back to dashboard" link as the other dashboard pages. +- At the door's "less than already paid" warning shows the total after bundle deals. + +## [1.28.0] - 2026-10-21 + +Run `npm run prisma:deploy` in the backend when deploying. This release adds a migration. + +### Added + +- **Bundle deals**: sell a set of tickets together for one price, e.g. 5 Adult + 3 Child for R500 instead of R550. Supervisors set them up per event under Dashboard → **Bundle deals**: the tickets and quantities (one variant or any variant), the price, optional dates, and on/off. +- Bundles apply automatically, with no code, as many times as a registration's tickets allow; leftover tickets are charged as usual. A bundle only applies when it's cheaper than the tickets at the prices actually charged, early-bird and staff prices included. When several compete, the one that saves the most is used first. This works for online registration, manual registration, at the door and on the kiosk. +- The event page and the register form list the event's deals, and every basket shows the saving live. On the register form, once a ticket from a bundle is picked, the bundle appears with what's missing and a **Complete bundle** button that tops up the ticket numbers. Once it's complete, **+** adds another full set. Invoices, receipts, emails, WhatsApp messages and the Yoco payment page show it as its own line, e.g. "Bundle: Family deal ×2". +- The Discounts report lists bundle deals next to coupon codes. Each bundle shows how often it's been used and the total saving given. +- `npm run set-demo`: Family Fun Day sells a **Family deal** bundle (2 adults + 3 kids for R220) in place of the old Family pass ticket. + +### Changed + +- Coupon codes now work out after bundle deals, on what's left. Registration.discountTotal now holds bundle and coupon discounts together, with the bundle part in the new `bundleDiscount`. +- Removing a code from a registration keeps its bundle deal. When an early-bird tier expires before payment and prices change, bundle deals are worked out again and coupon amounts are kept. +- Registrations keep a bundle they already have, even after it's turned off or its dates pass. Deleting a bundle that has been used turns it off instead. + +## [1.27.1] - 2026-10-21 + +### Added + +- `npm run set-demo` also stages ten completed events from the past year, with door sales recorded by staff, staff cash counts, check-ins, refunds, donations and post-event feedback. Their cashups go through every path: a quick close; full closes with card fees, a cash deposit fee, a written-off shortfall, cash kept on hand and an unaccounted amount; a close, reopen and re-close; pending EFT money that was later received and some still outstanding; and one event left open with the cash counted, ready for a live cashup. Funnel stats older than 90 days are stored as daily totals, the way the app rolls them up. See `backend/DEMO_DATA.md`. + +## [1.27.0] - 2026-10-21 + +Run `npm run prisma:deploy` in the backend when deploying. This release adds a migration. + +### Added + +- Cashups now record where each payment method's money ended up. For cash, card, EFT and other, the expected takings are split into what's **in the bank**, **cash on hand**, and **pending** (on the card machine or Yoco report, or with a proof of payment), with a reference for the pending amount. Card fees, bank charges, cash shortfalls and other losses are **written off** with a reason. Each method shows what's still **unaccounted**. Closing with an unaccounted amount is allowed after a warning, and the amount comes off profit, as variance did before. +- When staff have counted the cash, cash on hand is worked out for you: the count, less what reached the bank and any deposit fee written off as a bank charge. +- Pending money on a closed event can be marked **received** or **written off** later from the cashup screen, without reopening the event. Each one is logged with who did it and when. +- Reopening an event starts the next cashup from the last one, with any pending money settled since folded in. +- Write-offs show as **Bank & card charges** on the cashup screen and in the Cashup, Finance and Profit reports. The Cashup report has new In bank, On hand, Pending, Written off and Unaccounted columns. + +### Changed + +- Net profit now subtracts write-offs as their own line instead of showing card fees and bank charges as missing income. The net figure is the same. +- Every dashboard page uses the same back link: the small "← Back to dashboard" link above the page title, as on the Waitlist page. The grey Back buttons are gone. Site settings, profile, donate and manual registration, which had no way back, now have one too. + +## [1.26.1] - 2026-10-21 + +### Added + +- `npm run set-demo` in the backend replaces the database contents with demo data for showing the platform to other churches. It keeps the site settings and the admin account, and stages six upcoming events with registrations, payments, tickets, a waitlist, camp cabins, coupons, costs and funnel stats. See `backend/DEMO_DATA.md`. + +## [1.26.0] - 2026-10-21 + +### Changed + +- Upgraded Prisma from 5.22 to 7.10. Prisma 7 connects through the `@prisma/adapter-pg` driver adapter (node-postgres) instead of the Rust query engine. The database URL moved from `schema.prisma` to the new `backend/prisma.config.js`, which loads `backend/.env` itself. All Prisma clients are now created in `src/config/db.js`, and the server shares one client instead of opening two connection pools. No schema or migration changes. +- Prisma 7 checks TLS certificates on database connections. A `DATABASE_URL` that uses SSL with a self-signed or otherwise invalid certificate now fails to connect where Prisma 5 accepted it. +- `npm run dev` in the backend now uses Node's built-in `node --watch` instead of `nodemon`. +- The frontend now passes ESLint with no errors or warnings, down from 1,137, and `next build` runs ESLint again. It was skipped before (`eslint.ignoreDuringBuilds`), which is how the issues built up. + - API data is now typed. `src/types` describes the records the backend returns, modelled on the Prisma schema, and `apiFetch` returns `unknown` unless the caller names a type, so untyped responses no longer pass silently. + - Effects list everything they depend on. Data loaders are wrapped in `useCallback`, so a page reloads when its inputs change instead of showing stale data. + - The pricing helpers that were copied into several pages now live in `src/lib/pricing.ts`. + +### Fixed + +- Internal links on the home page, the 404 page and "Forgot your password?" now navigate client-side instead of reloading the whole page. +- Changing the page size on Admin → Users fetched the list twice; it now fetches once. +- At the door, the refund history now shows a refund's reason. The page was reading a field that doesn't exist, so the reason never appeared. +- In the Master Orders report, a ticket option named like one of the fixed columns (e.g. "name") could overwrite that column's value. +- Removed code that could never run: an unreachable "Pay with Yoco" button on the registration form, an unused attendee-forms block on the registration success page, unused export helpers in Reports, and fonts that were downloaded but never applied. + +### Security + +- Backend `npm audit` now reports 0 vulnerabilities: + - Patched `follow-redirects` (pulled in by `axios`) to 1.16.1, which fixes leaking credential headers on cross-origin redirects. + - Removed `nodemon`, the only backend package that pulled in `braces`. + - Jest's coverage loader now uses `js-yaml` 4, which drops the `sprintf-js` advisory. +- Frontend: overrode `postcss-selector-parser` to 7.1.7, used by the Tailwind 3 build. The generated CSS is byte-identical. The remaining frontend findings (7 high) are all the same `braces` advisory (GHSA-vfj7-8cjw-p6xm). It has no patched release, comes in only through build and lint tools (Tailwind 3 and `eslint-config-next`), and only ever handles glob patterns from our own config, never user input. + +## [1.25.1] - 2026-10-20 + +### Fixed + +- On mobile, the cookie consent banner now sits above the bottom navigation bar instead of being hidden behind it. +- The floating help button moves up above the cookie consent banner while it is showing, so the banner no longer covers it. + +## [1.25.0] - 2026-10-20 + +### Added + +- A **Yoco** tab in Site Settings for online payments: + - **Secret key:** shown masked like a card number (`sk_test_***…aba`) with a Test/Live badge. Yoco checks a new key before it is saved. + - **Webhook secret:** **Generate** registers this server's webhook URL (`BACKEND_URL/api/webhooks/yoco`, editable) with Yoco and saves the secret Yoco returns. **Enter manually** takes the secret of a webhook you registered yourself. + - **Registered webhooks:** every webhook on the Yoco account, with its URL and mode. It shows which one is active and warns when a URL isn't this server. Each can be deleted; deleting the active one also removes its stored secret. +- New admin endpoints under `/api/yoco` (config and webhooks). Changes are written to the admin audit log, without the secret values. + +### Changed + +- The Yoco secret key and webhook secret are now stored in the database, AES-256-GCM encrypted, instead of only in `backend/.env`. `YOCO_SECRET_KEY` and `YOCO_WEBHOOK_SECRET` still work as fallbacks when the database has no value. `npm run migrate:env-to-db` moves them across. +- Yoco secrets are never returned by `/api/settings/all` and can't be changed through `PUT /api/settings`. +- Starting a checkout or sponsorship without a Yoco key now gives a clear "online payments are not configured" message instead of failing at Yoco. + +## [1.24.0] - 2026-10-19 + +### Changed + +- Ticket transfers now need the new holder to accept. + - "Transfer" (in My Events, or At the door → Tickets) sends the person a link by email and/or WhatsApp, to the details typed. + - Nothing changes on the ticket until they accept on the new `/transfer/` page. They can also decline. + - On accepting, the transfer completes as before: new QR code, ticket delivery, account activation link, parental consent on youth events. + - My Events shows "Waiting for … to accept" with a Cancel button. + - Offers expire after 7 days or when the event starts, and a new offer replaces an open one. +- Privacy for group tickets and transfers: there is no user search, and nothing reveals whether an email or phone number belongs to an account. + - Registration responses no longer include named attendees' account links. + - If an email and phone point at two different accounts, this is no longer reported to the person typing them. The email's account is used. +- Terms of Use and Privacy Policy updated for everything added since 1.12: + - booking for other people, ticket transfers, and youth-event consent with health information and how long it is kept; + - who can see what (door staff, group leaders, supervisors), and read-only admin support access; + - sponsorships, waitlists, discount codes and feedback; + - two-factor authentication and offline scanning. +- The Privacy Policy has a full **cookie policy**: every item the site stores in the browser (necessary, staff-only and optional), the optional visit statistics, and the third-party cookies from the Google Maps embed and Yoco checkout. +- A new "Cookie settings" link in the footer (and a button in the policy) lets visitors change their choice. +- The API docs page (`/docs`) now lists every mounted route. 45 were missing, including dashboard stats, backups, attachments, the audit log, ticket transfer links and WhatsApp admin. + +### Fixed + +- After activating an account, the visitor is now really signed in. The token was saved under a key the app never read, so the "auto-login" didn't work. + +### Notes + +- `npm install` succeeds in the root, `backend` and `frontend` with no missing packages. +- The remaining `npm audit` findings are all in development/build tools (Jest, nodemon, ESLint, Tailwind's build), and none affect the running site. + - `braces` and `sprintf-js` have no patched release. + - `postcss-selector-parser` 7 would break Tailwind 3. +- Requires the `add_transfer_requests` database migration. + +## [1.23.0] - 2026-10-19 + +### Added + +- Impersonate user (Admin → Manage users → Impersonate): an admin can see the site exactly as a user does, to help with problems such as "my ticket isn't showing". + - A reason is required, and the session lasts at most 30 minutes. + - A bright "Viewing as [name]" banner with a countdown and "End impersonation" shows on every page. +- Impersonation is strictly read-only. + - A server-side guard, mounted before every route, refuses any change (registrations, payments, refunds, cancellations, profile, consent, messages and everything else) made with an impersonation token. + - Viewing pages doesn't trigger the price refresh it normally does. + - Admins can't be impersonated, and the admin must have two-factor authentication on. +- Impersonation is recorded in the audit log: start, end, reason, and every page and API call, including blocked attempts. + - The audit log page lists recent sessions with their full trail. +- New setting: email users when an admin views their account (Site Settings → Legal → Support access; off by default). +- New `/api/admin/impersonate` endpoints. + - Requires the `add_impersonation` database migration. + +## [1.22.0] - 2026-10-19 + +### Added + +- Registration funnel stats (first-party, no third-party analytics), showing where people drop off between seeing an event and paying. + - A new cookie notice asks visitors once. Only those who choose "Allow" are counted, using a random anonymous visit id. + - We record the event page view and the start of registration. The submit and paid stages come from the registration itself. + - Only the stage, the traffic source and the device type are stored. No name, IP address or User-Agent is kept. +- New report, **Registration funnel**: counts and conversion % per stage over a date range, a daily trend, and breakdowns by traffic source, device and ticket option. + - Selecting several events compares them. + - Sources come from `utm_source` links and from short links, which now add `?src=` when redirecting. +- A "Conversion (past month)" tile on the supervisor and admin dashboards covers live events. +- Raw visit records are rolled up into daily totals after 90 days by a daily job (`ANALYTICS_ROLLUP_ENABLED=false` to turn it off). +- The privacy policy's cookies section now describes these statistics. +- New `/api/analytics` endpoints. + - Requires the `add_funnel_analytics` database migration. + +## [1.21.0] - 2026-10-19 + +### Added + +- Post-event feedback, set up in a new Feedback step in the event wizard. + - Questions use the form builder. + - You pick when it's sent (the default is the morning after the event) and who gets it: everyone who checked in, or everyone registered. + - Each person gets a personal link by email (and WhatsApp where they use it). + - Anyone who hasn't answered gets one reminder 3 days later. + - Answers can be anonymous or named. + - "Send now" is available, and the questions lock once people start answering. +- New form field types: **Rating (1–5 stars)** and **Multiple choice**. They're used for feedback, and can also go on attendee forms (registration page, My Events, the kiosk, manual registration and Supervisor → Forms). +- New report, **Feedback summary**: + - response rate; + - average rating per question, with star distribution; + - multiple-choice and yes/no breakdowns as bar charts; + - a list of text answers (with names unless the form is anonymous). + - Select several events to compare their ratings (e.g. Camp 2025 vs Camp 2026). Exports to PDF and Excel like other reports. +- New `/api/feedback` endpoints and a job every 15 minutes (`FEEDBACK_JOB_ENABLED=false` to turn it off). + - Requires the `add_feedback_forms` database migration. + +## [1.20.0] - 2026-10-19 + +### Added + +- Sponsor a spot: a new event setting, "Allow sponsorships" (event wizard → Sponsor a spot). + - It adds a "Sponsor a spot" button on the event page so people can fund a place for someone who can't afford it. + - Sponsors choose one or more whole spots (at the main ticket price) or a custom amount, and pay through Yoco. Guests just give a name and email. + - Sponsors can give anonymously, or add a name and a message for the organisers. + - An optional goal ("12 of 20 spots sponsored") and public progress bar. +- Each sponsorship is recorded as a donation tagged to the event, in that event's sponsorship pool. + - Supervisors assign pool money to registrations with the existing donation assign/unassign flow, fully or partly. + - Under Payments → Donations, sponsorships are labelled, there's an "Only the sponsorship pool" filter, and the sponsor's message is shown. + - Who receives help is never shown to sponsors. +- Sponsors get a "Thank you for sponsoring a spot" receipt. + - Automations has a new "Thank Your Sponsors" email for events with sponsorships. + - Email attendees can target an event's sponsors (`filter.audience: 'sponsors'`). +- The Donations breakdown report has sponsorship pool columns per event: received, assigned and remaining. +- New `/api/sponsorships` endpoints. + - Requires the `add_sponsorships` database migration. + +## [1.19.0] - 2026-10-19 + +### Added + +- Rooms & groups (Supervisor → Rooms & groups), for camps and lockdowns: put attendees into rooms, cabins, small groups, teams or buses. + - Each event can have several allocation sets (e.g. "Rooms" and "Buses"). Each set has groups with an optional capacity, an optional gender restriction and an optional leader (a staff member). + - A drag-and-drop board puts people not yet placed on the left and groups, with capacity counters, on the right. Full groups and groups for the other gender won't accept a person. + - Auto-allocate fills groups evenly with everyone not yet placed, respecting capacity and gender. It can keep people on the same booking together or spread them out. + - Printable lists per group (with leader) and a master list. On youth events they can include medical and emergency details from consent forms; viewing those is recorded in the audit log. + - "Show on tickets" prints the group on each person's ticket and shows it in My Events. + - Email and WhatsApp attendees can be sent to one group ("Bus 2 leaves at 07:30"). Messages go to whoever booked for the people in it. + - Group leaders see their people under Staff → My groups. Medical details are shown to supervisors only. +- New event setting "Ask each person's gender" (under Named attendees). It adds a gender choice for each named person on the registration page, at the door, on the kiosk, in manual registration and in My Events, and is needed for gender-split rooms. +- New `/api/allocations` endpoints. + - Requires the `add_room_allocation` database migration. + +## [1.18.0] - 2026-10-19 + +### Added + +- Ticket transfer. On My Events, "Transfer" hands a ticket to someone else before the event: enter their name and email or phone. + - The new holder gets the ticket by email/WhatsApp with a new QR code. If they're new, an inactive account is created and they get an activation link. + - The old QR code stops working, so screenshots of it won't scan. Scanning it says who the ticket was transferred to, and offline-mode sync flags it. + - For a ticket covering several people, one place is split off to the new holder. + - The payer stays responsible for the registration. +- Transfer rules: + - Only before the event starts, and only for tickets that haven't been scanned. + - It can be turned off per event (new "Ticket transfer" setting in the event wizard, on by default). Supervisors can always transfer, from At the door → Tickets. + - On youth events, the new holder's date of birth, and a parent's details for a minor, are needed, and a new consent request is sent. + - The previous holder's attendee form answers and consent medical details are removed. + - Every transfer is recorded in the audit log. +- New endpoints `POST /api/tickets/:id/transfer` and `GET /api/tickets/:id/transfers`. + - Requires the `add_ticket_transfer` database migration. + +## [1.17.0] - 2026-10-19 + +### Added + +- Offline ticket scanning. While online, staff pick an event and section on the scanner and tap "Enable offline mode". The section (or the whole event) is locked to their device and its tickets are downloaded to the device. + - With no connection, scans are checked against that list and queued on the device. + - The panel shows when the list was downloaded and how many scans are waiting. + - Queued scans sync automatically when the device is back online (or with "Sync now"), and check-in messages go out then. + - "Release section" ends offline mode and deletes the list from the device. +- Only one device can hold a section at a time (a whole-event lock clashes with every section). While a section is locked, other devices see who holds it and can't scan it, online or offline, so a ticket can never be redeemed twice by two offline devices. +- Syncing is idempotent and never redeems more than is left on a ticket. Anything that needs a person to look goes into a sync report: tickets not found, cancelled registrations, used-up tickets, scans outside the locked section, and check-ins without consent. +- Supervisor → Offline scanning page: active locks with force release (for a lost or flat phone; its scans still sync if it reconnects, and are flagged), and sync reports to review. Locks, releases, force-releases and syncs are recorded in the audit log. +- The scanner is installable as an app (web app manifest), and a service worker caches the scanner page and its scripts so it opens with no connection. +- The app now stays signed in with the last confirmed profile when it's reloaded without a connection, instead of sending the user to the login page. +- New `/api/scan-locks` endpoints. + - Requires the `add_offline_scanning` database migration. + +### Changed + +- `POST /api/tickets/scan/:qrCode` now accepts `sectionId` and checks it on the server; this was previously only checked in the browser. + - It now refuses (423) scans in a section that another device has locked for offline scanning. + +## [1.16.0] - 2026-10-19 + +### Added + +- Waitlist for sold-out tickets. A new event setting (event wizard → Visibility) turns it on, with how long offered places are held (24 hours by default) and whether someone can be offered fewer places than they asked for. + - Sold-out tickets show "Join waitlist" on the event page, the register page and the events list. Guests can join on events that allow guest registration. +- When places free up, the next person is emailed/WhatsApped a claim link, and the places are held for them so nobody else can buy them. Places free up through a cancellation (by the person or staff), a smaller booking, or a raised stock limit. + - The claim link opens the register page with the places pre-selected, and works without logging in. + - Unclaimed offers expire (checked every 10 minutes) and move on to the next person. +- People can leave a waitlist from My Events, which now lists their waitlists and any places held for them. +- Supervisor → Waitlist page: the queue per event, with offer now (even over the stock limit), move up/down and remove. +- The daily summary email shows each event's waitlist count. +- New `/api/waitlist` endpoints. `POST /api/registrations` accepts `waitlistToken`. + - Requires the `add_waitlist` database migration. + +### Fixed + +- Manual registrations (Manual registration, At the door, the kiosk) and adding places to an existing booking never checked stock, so either could take an option over its stock limit. Both are now checked like a normal registration. +- Stock is now counted in one place (`utils/stock.js`) for registration checks, `availableCount` and `isSoldOut`, including places held for waitlist offers. + +## [1.15.0] - 2026-10-19 + +### Added + +- Parental consent for youth events. A new "Requires parental consent" event setting (event wizard → Visibility) has its own consent text and optional medical info, emergency contact and photo consent questions. It turns on named attendees automatically. + - Registering then needs a name and date of birth for every main-ticket place. Anyone under 18 on the event's start date needs a parent or guardian's name, email and phone. + - This applies on the registration page, manual registration, at the door, the kiosk, and when editing names in My Events. +- The parent gets an email and a WhatsApp (always both) with a link to a new consent page (`/consent/`). There they read the text, answer the optional questions, type their full name and confirm they're the parent or guardian, then give or decline. + - The system records the time, IP, device, signed name, and the exact consent text and version shown. + - Medical and emergency details are stored encrypted. + - The registrant and the event's notification recipients are told the outcome. +- Tickets are still issued, but the scanner blocks check-in until consent is given, showing why. Supervisors can override, and the override is recorded in the audit log. On a youth event, a ticket with no named attendee counts as missing consent. +- A daily 09:00 job reminds unanswered requests after 2 days, then every 3 days until the event. It also deletes medical and emergency details a set number of days after the event (Site Settings → Legal, default 30). `CONSENT_JOBS_ENABLED=false` turns it off. +- Supervisor → Parental consent page: consent status per attendee, resend one or all pending requests, re-request consent after the consent text changes, and a printable, confidential medical & emergency list. Every view of the list is recorded in the audit log. +- New reports: "Parental consent status" and "Medical & emergency list". +- My Events shows each attendee's consent status, with a "Resend consent" button. +- Anonymising or closing an account also clears that person's attendees' parent, date-of-birth, medical and emergency details. +- New endpoints under `/api/consent`. `GET /api/tickets/scan-preview/:qrCode` now returns `consentStatus`, and `POST /api/tickets/scan/:qrCode` accepts `overrideConsent`. + - Requires the `add_parental_consent` database migration. + +## [1.14.0] - 2026-10-19 + +### Added + +- Group tickets (named attendees). A new "Named attendees" event setting (event wizard → Visibility) lets someone registering several people give each main-ticket place a name, with an optional email and phone. It's offered on the registration page, Manual registration, At the door and the self-service kiosk. + - Each named person gets their own single-person ticket, with their name on the ticket PDF, the scanner's confirm screen and the staff ticket list. Places left unnamed share one quantity ticket as before. + - The payer chooses whether every ticket comes to them or each person gets their own by email/WhatsApp; anyone without contact details falls back to the payer. + - The payer stays the account owner for billing, invoices and payments. + - An attendee whose email or phone matches an existing account is linked to it (never when the email and phone belong to two different accounts). Their ticket then appears in their own My Events, marked "Booked by …", and they can open and submit their own attendee form. +- My Events → registration popup has a new "People" section for adding or changing names and contact details, switching ticket delivery, and sending an attendee a link to fill in their own form (`/forms?registrationId=…&attendeeId=…`). An attendee whose ticket has been scanned can't be removed. +- Attendee forms now show one block per named person, labelled with their name, and each response is saved against that attendee. +- New endpoints `PUT /api/registrations/:id/attendees` and `POST /api/registrations/:id/attendees/:attendeeId/send-form-link`. `POST /api/registrations` and `/manual` accept `attendees` and `ticketDelivery`. + - Requires the `add_named_attendees` database migration. + +### Changed + +- Reducing the quantity of a main ticket removes the newest names beyond the new quantity. +- Check-in confirmations for a named ticket go to that person when the registration sends each person their own tickets. +- Unauthenticated guest registration now matches an existing account by phone as well as email, and is refused (409) when the email and phone belong to two different accounts, instead of silently reusing whichever account the email matched. +- Free registrations now issue tickets through the same generator as paid ones, instead of a separate copy of the logic. + +### Security + +- Registration details (`GET /api/registrations/:id`) hide attendees' email addresses and phone numbers from anyone other than the payer and staff, such as an attendee opening their form link. + +## [1.13.0] - 2026-10-19 + +### Added + +- Coupon codes. Supervisors create percentage, fixed-amount or free ("comp") codes under Supervisor → Coupon codes. + - Codes can be limited to particular events, ticket options or variants, a date window, total and per-person uses (one per person by default), a minimum number of tickets, and specific people, roles (e.g. Staff and above) or an email domain. Restricted codes need a logged-in account, so they can't be shared around. + - By default the better of the code and the early-bird price wins; a code can instead stack on top of early-bird pricing. + - People enter codes under "Have a code?" on the registration page and in My Events (for registrations not yet paid in full). Staff can apply them in Manual registration, At the door and the self-service kiosk. + - The discount is locked in when it's applied, the same way early-bird prices are. It appears as its own line on invoices, receipts, registration and payment emails, WhatsApp messages and the Yoco checkout. + - Editing a registration's items recalculates percentage and free codes; fixed-amount codes keep their amount. Cancelling a registration frees the use. A free code that covers everything marks the registration paid and sends the tickets. + - Use limits are enforced under a database lock, so the last available use can't be claimed twice. +- Staff price: a ticket option or variant can carry a staff price (event wizard → Items & pricing) that Staff and above pay automatically when it's lower than the normal price. +- New "Discounts (coupon codes)" report (Reports → Financial), showing uses and value given away per code and event. The Finance report's "What was sold" is now shown after discounts. +- Coupon activity in the admin audit log: codes created, edited and turned off, and codes applied or removed by staff. +- New endpoints: `POST /api/coupons/validate`, `GET|POST /api/coupons`, `GET|PUT /api/coupons/:id`, `GET /api/coupons/redemptions`, `POST|DELETE /api/registrations/:id/coupon`. `POST /api/registrations` and `/manual` accept `couponCode`. + - Registration responses now include `discountTotal` and `subtotalComputed`. + - Requires the `add_coupon_codes` database migration (`npm run prisma:deploy` in `backend`). + +### Fixed + +- Yoco checkout line items priced each item at its most recent price times the whole quantity. When a line spanned several price tranches (some tickets at early-bird, some at full price), the item lines didn't match the amount charged. They now list each price actually charged. +- The free-registration check on `POST /api/registrations` and `/manual` had the same fault: it used the latest price for the whole quantity instead of the real total. + +## [1.12.0] - 2026-10-19 + +### Added + +- Two-factor authentication is now required for Admin and Supervisor accounts. An admin or supervisor without it is sent a code at their next login (by email, or WhatsApp when SMTP isn't set up), and entering it turns two-factor on — the same code step as before, with a note explaining why. Trusted devices don't skip this first code. They can change whether codes come by email or WhatsApp from Profile & Security, but can no longer turn two-factor off (`POST /api/users/2fa/disable` returns 403 for them). +- Existing admin and supervisor sessions without two-factor are ended on their next request (`401` with `code: "TWO_FACTOR_REQUIRED"`), and the login page explains why. Promoting a user to supervisor or admin also ends their sessions if they don't have two-factor yet, so they enrol at their next login. An admin "Reset 2FA" for a supervisor/admin now means they set it up again at their next login. +- The requirement is skipped when no channel can deliver a code — no SMTP configured and no WhatsApp — so a fresh install (or the setup wizard, which also gets a short grace period) never locks the first admin out. `TWO_FACTOR_REQUIRED_ROLES=false` turns the requirement off as an emergency switch. + +- `FEATURES.md`, a repo-root overview of everything the platform does — roles, public site, events, registration, payments, tickets, messaging, dashboards, cashup, reports, settings, security, background jobs, and a page map. + +### Changed + +- `info.md` (the overview for prospective churches) brought up to date with features added since it was written — donations, invoices and receipts, cashup and costs, profit reporting, audit trail, scheduled messaging, self-service kiosk, scan points, backups, branding, and privacy controls. + +## [1.11.0] - 2026-10-08 + +### Added + +- Optional two-factor authentication. Any user can turn it on from Profile & Security and choose to receive a 6-digit code by email or WhatsApp; the chosen channel is confirmed with a code before it takes effect. At login the code is asked for after the password, expires after 10 minutes and allows 5 attempts, with a "Resend code" option. If a WhatsApp code can't be sent, it falls back to the account's email address. +- "Trust this device for 30 days" on the code step, so a remembered device skips the code. Trusted devices are forgotten when the password is changed or reset, when sessions are signed out everywhere, and when two-factor is turned off. +- Admins can reset two-factor authentication for a user who can no longer receive codes ("Reset 2FA" on the Users page). Turning two-factor on or off shows in Account activity. +- The self-service kiosk asks supervisors with two-factor on for their code at setup. Changing the event now re-confirms the password against the existing kiosk session (`POST /api/users/verify-password`) instead of logging in again. + +### Changed + +- `POST /api/users/login` returns `{ twoFactorRequired, challengeId, method, destination }` instead of a token for accounts with two-factor on; the token is issued by the new `POST /api/users/login/2fa`. Accounts without two-factor are unaffected. Requires the `add_two_factor` database migration (`npm run prisma:deploy` in `backend`). + +## [1.10.6] - 2026-10-08 + +### Fixed + +- The frontend production build (`next build`) no longer hangs or fails when the backend isn't reachable. With no `NEXT_PUBLIC_API_URL`/`API_URL` set, the root layout fetched a relative `/api/settings` URL that never settled during prerender, so every page timed out after 60 seconds; server-side fetches now fail fast when no API base is configured. The home page and the Events page also no longer fail the build when `/api/events` can't be reached — they build with an empty list and fill in on the first revalidation. At runtime a failed fetch still errors, so the last good page keeps being served. + +### Security + +- Updated dependencies to clear `npm audit` advisories: `express`, `multer`, `proxy-addr`, `qs` and others in the backend, `next` (15.5.27) and `sharp` (0.35.5) in the frontend, and `nodemailer` from 9 to 10 (requires Node.js 20 or newer). The root package now overrides `shell-quote` to a patched release, since every `concurrently` version pins a vulnerable one. Backend production dependencies now report no known vulnerabilities; the remaining advisories are in development tooling (`nodemon`, `jest`, `tailwindcss` 3) and have no non-breaking fix. +- Dependency install scripts are now explicitly allow-listed via `allowScripts` in the backend and frontend `package.json` (Prisma, `@sentry/cli`, `unrs-resolver`), so npm no longer blocks them. + +## [1.10.5] - 2026-10-01 + +### Fixed + +- Events that have already started but not yet finished now show on the home page and the Events page. Both pages were hiding an event as soon as its start time passed; they now keep it listed until its end time, which matches what `GET /api/events` already returns. + +## [1.10.4] - 2026-09-01 + +### Fixed + +- "Add to calendar" (`GET /api/events/:id/ics`) always failed with a 400 in production: the `ics` library's `url` field requires a scheme (`https://...`), but `FRONTEND_URL`/`APP_BASE_URL` was configured without one, so `createEvent()` rejected it before generating any output. A missing scheme is now assumed to be `https://` instead of failing. + +## [1.10.3] - 2026-08-28 + +### Fixed + +- Creating an event was never recorded in the admin audit log — 1.10.0 added `event_created` as a logged action on the frontend's filter list, but the backend's `createEvent` never actually called `logAdminAction`, only `updateEvent`/`deleteEvent` did. Event creation is now logged the same way. +- Staff cancelling a registration via `PUT /api/registrations/:id` (the staff status-change endpoint, separate from the owner-facing `DELETE /:id` cancel route) wasn't logged at all — only the `DELETE` path logged `registration_cancelled`. Both paths now log it, verified against all six audit categories promised in 1.10.0 (refunds, donation assign/unassign, manual registrations, staff-initiated cancellations, event create/update/delete, settings changes) with no other gaps found. +- Added a "Back to dashboard" link to Admin → Audit log, matching the back-link pattern already used on the Cashup page. + +## [1.10.2] - 2026-08-28 + +### Fixed + +- Sentry wasn't instrumenting Express (`[Sentry] express is not instrumented` at startup): `express`, `cors`, and `@prisma/client` were required at the top of `backend/src/index.js` before `Sentry.init()` ran, but Sentry's auto-instrumentation patches those modules via a require hook that only works if `Sentry.init()` runs first. `Sentry.init()` now runs immediately after `dotenv.config()`, before any of the libraries it instruments are required. + +## [1.10.1] - 2026-08-28 + +### Security + +- Fixed a path-traversal vulnerability in event-image, branding (logo/favicon), and event-attachment uploads: the stored filename embedded the client-supplied `originalname` unsanitized, so a crafted filename (e.g. containing `../`) could write the uploaded file outside the intended `public/uploads` subfolder anywhere the server process could write. Uploaded files are now always saved under a server-generated random name; the original filename is preserved only as display metadata. +- `express-rate-limit` was declared as a root-only dependency despite being required directly by the backend (`backend/src/index.js`) — a plain `cd backend && npm install`, as documented in the deployment guide, would not have installed it. It's now a proper `backend/package.json` dependency. +- Bumped `next` (frontend) off a version affected by a critical unauthenticated RCE in the React Flight protocol (GHSA-9qr9-h5gf-34mp) and several other CVEs, and switched it from an exact pin to `^15.5.24` so future patch releases install automatically. +- Bumped `multer`, `nodemailer`, `jsonwebtoken`, and `uuid` (backend) to versions fixing DoS, SMTP/CRLF-injection, HMAC-verification, and buffer-bounds advisories; added an `overrides` entry so the vulnerable `uuid` nested under `exceljs` is also patched. Ran `npm audit fix` across all three workspaces (root/backend/frontend) — 0 known vulnerabilities remain. +- `jwt.verify()` now pins `algorithms: ['HS256']` explicitly rather than trusting the algorithm from the token header. +- Uploaded assets served from `/uploads` now get `Content-Security-Policy: default-src 'none'; sandbox` and `X-Content-Type-Options: nosniff`, so an uploaded SVG containing a ` + + +`; diff --git a/apps/events/backend/src/v2/legacy.ts b/apps/events/backend/src/v2/legacy.ts new file mode 100644 index 0000000..74cfe65 --- /dev/null +++ b/apps/events/backend/src/v2/legacy.ts @@ -0,0 +1,32 @@ +/** + * Typed doors into the JavaScript side of the backend. TypeScript infers loose types from the + * .js files (the Prisma client is built by a function, helpers have defaulted options), so v2 + * code imports them from here instead. When a module is converted to TypeScript, its line here + * goes and callers import it directly. + */ +import type { PrismaClient } from '@prisma/client'; + +// The client in config/db.js only adds query hooks (webhooks), so its models are PrismaClient's. +export const prisma = require('../config/db') as PrismaClient; + +type CampusFilter = '' | 'all' | string; +const campuses = require('../utils/campuses') as { + campusesEnabled(): Promise; + resolveCampusFilter(value: string | undefined): Promise; + campusWhere(filter: CampusFilter, opts: { enabled: boolean; withAllCampuses?: boolean }): object; +}; +export const { campusesEnabled, resolveCampusFilter, campusWhere } = campuses; + +export const { publicEventWhere } = require('../utils/series') as { + publicEventWhere(now?: Date): { isActive: true; isHidden: false; goLiveAt: { lte: Date } }; +}; + +type OptionLike = { id: string; price: number; earlyBirdTiers?: unknown[] }; +export const { publicOptions } = require('../utils/volunteers') as { + publicOptions(event: { eventOptions?: O[]; kidsOptionId?: string | null; volunteerOptionId?: string | null }): O[]; +}; + +export const { getEffectiveUnitPrice, computeRegistrationTotalDue } = require('../utils/pricing') as { + getEffectiveUnitPrice(option: OptionLike, referenceTime: Date | null, atTime: Date): number; + computeRegistrationTotalDue(registration: object, atTime: Date): number; +}; diff --git a/apps/events/backend/src/v2/links.ts b/apps/events/backend/src/v2/links.ts new file mode 100644 index 0000000..420a4da --- /dev/null +++ b/apps/events/backend/src/v2/links.ts @@ -0,0 +1,68 @@ +/** + * Incoming webhooks and the links in sent messages on v2 (1.51.16). These aren't JSON API calls, + * so they're plain Express routes, mounted by app.js beside the v2 router: + * + * - `webhooksRouter` at /api/v2/webhooks: Yoco, PayFast and WAWP (WhatsApp) post here. New + * provider registrations use these URLs; the v1 paths (/api/webhooks/…, /api/whatsapp/webhook) + * are still answered by the same handlers, because providers may not follow a redirect on POST. + * - `linksRouter` at /api/v2: the one-click unsubscribe link (RFC 8058) from email headers. + * - `legacyLinkRedirects` at /api: links in messages already sent (calendar files, opening a + * one-click unsubscribe link) answer 308 with their v2 address. A mail app's one-click POST to + * the v1 address is still handled there, like a webhook. + */ +import express, { Router, type RequestHandler } from 'express'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- the handlers are JavaScript */ +const { handleYocoWebhook } = require('../controllers/webhookController') as { handleYocoWebhook: RequestHandler }; +const { handleProviderWebhook } = require('../payments/webhook') as { handleProviderWebhook(id: string): RequestHandler }; +const { handleWebhook: handleWhatsappWebhook } = require('../controllers/whatsappController') as { handleWebhook: RequestHandler }; +const privacy = require('../controllers/privacyController') as { oneClickRedirect: RequestHandler; oneClickUnsubscribe: RequestHandler }; + +/** Paths whose request body is read raw (signatures are checked over the exact bytes). */ +export const RAW_BODY_PREFIXES = ['/api/webhooks', '/api/v2/webhooks']; + +/** WAWP sends JSON (and ?secret=…); on the webhook paths its body arrives raw. */ +export const whatsappWebhook: RequestHandler[] = [(req: any, _res, next) => { + try { req.body = req.rawBody ? JSON.parse(req.rawBody) : {}; } catch { req.body = {}; } + next(); +}, handleWhatsappWebhook]; + +export const webhooksRouter = Router(); +webhooksRouter.post('/yoco', handleYocoWebhook); +webhooksRouter.post('/payfast', handleProviderWebhook('payfast')); +webhooksRouter.post('/whatsapp', ...whatsappWebhook); + +export const linksRouter = Router(); +linksRouter.get('/unsubscribe/:token/one-click', privacy.oneClickRedirect); +linksRouter.post('/unsubscribe/:token/one-click', express.urlencoded({ extended: false }), privacy.oneClickUnsubscribe); + +/** v1 links in messages already sent → their v2 address (308 keeps the method). */ +const REDIRECTS: { method: string; v1: RegExp; v2: (m: RegExpMatchArray) => string }[] = [ + { method: 'GET', v1: /^\/api\/events\/([^/]+)\/ics$/, v2: m => `/api/v2/events/${m[1]}/calendar.ics` }, + { 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) { + const m = req.method === r.method ? path.match(r.v1) : null; + if (m) return res.redirect(308, r.v2(m) + (query ? `?${query}` : '')); + } + next(); +}; diff --git a/apps/events/backend/src/v2/openapi.ts b/apps/events/backend/src/v2/openapi.ts new file mode 100644 index 0000000..834f92f --- /dev/null +++ b/apps/events/backend/src/v2/openapi.ts @@ -0,0 +1,121 @@ +import { z } from 'zod'; +import { routes as allRoutes, type AnyRoute, type Access } from './route'; +import { ERROR_STATUS } from './errors'; +import { PATH_HELP, QUERY_HELP } from './docs'; + +/** + * The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is + * always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2. + */ + +type JsonSchema = Record; + +const toSchema = (schema: z.ZodType, io: 'input' | 'output'): JsonSchema => { + const { $schema: _drop, ...rest } = z.toJSONSchema(schema, { io, unrepresentable: 'any' }) as JsonSchema; + return rest; +}; + +const ACCESS_TEXT: Record = { + public: 'Anyone.', + optional: 'Anyone; signed-in staff may see more.', + user: 'Any signed-in person.', + staff: 'Staff, supervisors and admins.', + supervisor: 'Supervisors and admins.', + admin: 'Admins only.', +}; + +const errorSchema = { + type: 'object', + required: ['error'], + properties: { + error: { + type: 'object', + required: ['code', 'message'], + properties: { + code: { type: 'string', enum: Object.keys(ERROR_STATUS) }, + message: { type: 'string' }, + fields: { type: 'object', additionalProperties: { type: 'string' }, description: 'Per-field problems (VALIDATION_FAILED only)' }, + reason: { type: 'string', description: 'A more specific cause when there is one, e.g. TWO_FACTOR_REQUIRED, IMPERSONATION_ENDED, LICENCE_READ_ONLY, OTHER_CAMPUS' }, + }, + }, + }, +}; + +const errorResponse = (description: string) => ({ description, content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } } }); + +function parameters(def: AnyRoute) { + const out: JsonSchema[] = []; + const add = (schema: z.ZodType | undefined, where: 'path' | 'query') => { + if (!schema) return; + const json = toSchema(schema, 'input') as { properties?: Record; required?: string[] }; + for (const [name, prop] of Object.entries(json.properties || {})) { + const { description: own, ...propSchema } = prop as JsonSchema & { description?: string }; + const description = own || (where === 'query' ? QUERY_HELP[name] : PATH_HELP[name]); + out.push({ name, in: where, required: where === 'path' || (json.required || []).includes(name), ...(description ? { description } : {}), schema: propSchema }); + } + }; + add(def.params, 'path'); + add(def.query, 'query'); + return out; +} + +/** A JSON body; one with nothing in it (an action that takes no input) says so. */ +function requestBody(schema: JsonSchema) { + const empty = !(schema as { properties?: object }).properties || !Object.keys((schema as { properties: object }).properties).length; + return empty + ? { required: true, description: 'No body needed: send an empty object.', content: { 'application/json': { schema } } } + : { required: true, content: { 'application/json': { schema } } }; +} + +export function buildOpenApi(opts: { version: string; serverUrl?: string; list?: AnyRoute[] }) { + const list = opts.list ?? allRoutes; + const paths: Record> = {}; + for (const def of list) { + const path = def.path.replace(/:(\w+)/g, '{$1}'); + const secured = def.access !== 'public' && def.access !== 'optional'; + paths[path] ||= {}; + paths[path][def.method] = { + tags: [def.tag], + summary: def.summary, + description: [def.description, `**Who:** ${ACCESS_TEXT[def.access]}`].filter(Boolean).join('\n\n'), + operationId: `${def.method}${path.replace(/[{}]/g, '').split('/').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join('')}`, + ...(secured ? { security: [{ bearerAuth: [] }] } : def.access === 'optional' ? { security: [{}, { bearerAuth: [] }] } : {}), + parameters: parameters(def), + ...(def.upload + ? { requestBody: { required: true, content: { 'multipart/form-data': { schema: { type: 'object', required: [def.upload.field], properties: { [def.upload.field]: { type: 'string', format: 'binary', description: def.upload.description } } } } } } } + : (def.documented?.body || def.body) ? { requestBody: requestBody(toSchema((def.documented?.body || def.body)!, 'input')) } : {}), + responses: { + [String(def.status ?? 200)]: def.file + ? { description: 'The file', content: { [def.file.contentType]: { schema: { type: 'string' } } } } + : { description: 'OK', content: { 'application/json': { schema: toSchema(def.documented?.response ? z.object({ data: def.documented.response }) : def.response, 'output') } } }, + ...(def.params || def.query || def.body ? { 400: errorResponse('Validation failed (VALIDATION_FAILED)') } : {}), + ...(secured ? { 401: errorResponse('Not signed in (UNAUTHENTICATED)') } : {}), + ...(secured && def.access !== 'user' ? { 403: errorResponse('Not allowed for this role (FORBIDDEN)') } : {}), + ...(def.params ? { 404: errorResponse('Not found (NOT_FOUND)') } : {}), + }, + }; + } + return { + openapi: '3.1.0', + info: { + title: 'Cross Events API', + version: opts.version, + description: [ + 'Version 2 of the Cross Events API. Every response is JSON:', + '- a single item is `{ "data": { … } }`;', + '- a list is `{ "data": [ … ], "meta": { "page", "limit", "total", "pages" } }`, paged with `?page=` and `?limit=` (at most 100);', + '- 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/…`) 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' }], + tags: Array.from(new Set(list.map(r => r.tag))).map(name => ({ name })), + paths, + components: { + securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' } }, + schemas: { Error: errorSchema }, + }, + }; +} diff --git a/apps/events/backend/src/v2/paging.ts b/apps/events/backend/src/v2/paging.ts new file mode 100644 index 0000000..dfcd5ec --- /dev/null +++ b/apps/events/backend/src/v2/paging.ts @@ -0,0 +1,28 @@ +import { z } from 'zod'; + +/** `?page=2&limit=25` on every v2 list (limit 1–100, default 25). */ +export const pageQuery = z.object({ + page: z.coerce.number().int().min(1).default(1).describe('Page number, from 1'), + limit: z.coerce.number().int().min(1).max(100).default(25).describe('Items per page (at most 100)'), +}); +export type PageQuery = z.infer; + +export const pageMeta = z.object({ + page: z.number().int(), + limit: z.number().int(), + total: z.number().int().describe('Items across all pages'), + pages: z.number().int().describe('Number of pages (at least 1)'), +}); + +/** The response shape of a v2 list: `{ data: [...], meta: { page, limit, total, pages } }`. */ +export const paged = (item: T) => z.object({ data: z.array(item), meta: pageMeta }); + +/** The response shape of a single v2 resource: `{ data: {...} }`. */ +export const single = (item: T) => z.object({ data: item }); + +/** Prisma's skip/take for a page. */ +export const skipTake = ({ page, limit }: PageQuery) => ({ skip: (page - 1) * limit, take: limit }); + +export function pageOf(data: T[], total: number, { page, limit }: PageQuery) { + return { data, meta: { page, limit, total, pages: Math.max(1, Math.ceil(total / limit)) } }; +} diff --git a/apps/events/backend/src/v2/resources/adminPrivacy.ts b/apps/events/backend/src/v2/resources/adminPrivacy.ts new file mode 100644 index 0000000..bb52820 --- /dev/null +++ b/apps/events/backend/src/v2/resources/adminPrivacy.ts @@ -0,0 +1,162 @@ +/** + * Privacy and admin on v2 (1.51.15): my privacy (news consent, my data, requests, the notice), + * unsubscribe links, the privacy admin (requests, notice drafts, operators, logs, retention, + * breaches), the audit log, jobs, impersonation, site settings and first-run set-up, the Hub, + * outbound webhooks and backups. Each route runs the v1 handler (viaV1.ts) behind the same + * access checks as v1. + */ +import { z } from 'zod'; +import { idParams } from '../schemas'; +import { v1Route } from '../viaV1'; +import * as D from '../docs'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- v1 handlers and middleware are JavaScript */ +const rateLimit = require('express-rate-limit') as (opts: object) => any; +const { campusIndependent } = require('../../utils/campusScope') as { campusIndependent(reason: string): any }; +const privacy = { ...require('../../controllers/privacyController'), ...require('../../controllers/privacyAdminController') }; +const audit = require('../../controllers/adminAuditController'); +const imp = require('../../controllers/impersonationController'); +const jobs = require('../../controllers/jobsController'); +const settings = require('../../controllers/settingsController'); +const hub = require('../../controllers/hubController'); +const hooks = require('../../controllers/outboundWebhookController'); +const backups = require('../../controllers/backupController'); + +const loose = z.looseObject({}); +const filters = (...names: string[]) => z.looseObject(Object.fromEntries(names.map(n => [n, z.string().max(4000).optional()]))); +const tokenParams = z.object({ token: z.string().min(1).max(500) }); +const exportLimiter = rateLimit({ windowMs: 10 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false }); + +// ─── Documented shapes (docs.ts) ───────────────────────────────────────────── + +const news = D.obj({ email: D.bool, whatsapp: D.bool }); +const dataRequest = D.obj({ + id: D.str, type: z.enum(['access', 'correction', 'deletion']), status: z.enum(['open', 'completed', 'rejected', 'cancelled']), + userId: D.optStr, name: D.str.optional(), email: D.str.optional(), details: D.optStr, response: D.optStr, dueAt: D.optDate.describe('30 days after it was made'), + closedAt: D.optDate, createdAt: D.date, +}); +const noticeSection = D.obj({ key: D.str.optional(), title: D.str, body: D.str.describe('Text; {placeholders} are filled in') }); +const operatorInput = D.obj({ name: D.str, purpose: D.str.describe('What they do for the church'), dataShared: D.optStr, location: D.optStr.describe('Country the data is kept in'), website: D.optStr, active: D.optBool, order: D.optNum }); +const operator = operatorInput.extend({ id: D.str, active: D.bool, order: D.num, createdAt: D.date, updatedAt: D.date }); +const logPage = (row: T) => D.obj({ total: D.num, pageSize: D.num, rows: z.array(row) }); +const breachInput = D.obj({ + title: D.str, description: D.str, dataAffected: D.str, peopleAffected: D.numeric.nullish(), whoAffected: D.optStr, consequences: D.optStr, + actionsTaken: D.optStr, adviceToPeople: D.optStr, causedBy: D.optStr, status: D.optStr.describe('open or closed'), + discoveredAt: D.date, occurredAt: D.optDate, regulatorNotifiedAt: D.optDate.describe('When the Information Regulator was told'), peopleNotifiedAt: D.optDate, +}); +const breach = breachInput.extend({ id: D.str, status: D.str, createdAt: D.date, updatedAt: D.date, createdBy: D.obj({ name: D.str }).nullish() }); +const retentionState = D.obj({ + policies: D.anyObj.describe('Per kind of information: how long it is kept'), definitions: D.anyObj, preview: D.anyObj.describe('What the rules would remove now'), + lastRun: D.anyObj.nullish(), related: D.obj({ medicalDays: D.num, backupCount: D.num, analyticsDays: D.num }), +}); +const hubStatus = D.obj({ + state: D.str.describe('active, grace, suspended, revoked, none…'), readOnly: D.bool, daysLeft: D.optNum, endsAt: D.optDate, graceEndsAt: D.optDate, + licence: D.obj({ customer: D.optStr, plan: D.optStr, status: D.optStr, licenceExpiresAt: D.optDate, graceDays: D.optNum, issuedAt: D.optDate, validUntil: D.optDate, limits: D.anyObj }).nullish(), + connected: D.bool, keyConfigured: D.bool, hubUrl: D.optStr, lastHeartbeatAt: D.optDate, lastError: D.optStr, + version: D.str.describe('This site\'s version'), latestVersion: D.optStr, updateAvailable: D.bool, urgentUpdate: D.bool, updateSnoozed: D.optBool, + releases: z.array(D.anyObj).optional().describe('What\'s new in each version since this one'), updateRequest: D.anyObj.nullish(), notices: z.array(D.anyObj).optional(), +}); +const webhook = D.obj({ + id: D.str, name: D.str, url: D.str, events: z.array(D.str).describe('Event types it gets'), isActive: D.bool, operatorId: D.optStr.describe('Its entry in the operator register'), + lastSuccessAt: D.optDate, lastFailureAt: D.optDate, createdAt: D.date, +}); +const delivered = D.obj({ status: D.optStr.describe('succeeded, failed, retrying…'), statusCode: D.optNum, error: D.optStr }); + +// ─── My privacy ────────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/me/privacy', tag: 'Privacy', summary: 'My privacy settings', description: 'News consent, open requests, and whether there\'s a privacy notice to accept.', access: 'user', documented: { response: D.obj({ news, newsAskedAt: D.optDate, canWhatsApp: D.bool, notificationPreference: D.optStr, history: z.array(D.anyObj).describe('Every change to my news consent'), requests: z.array(dataRequest) }) }, v1: privacy.getMyPrivacy }); +v1Route({ method: 'put', path: '/me/privacy/news', tag: 'Privacy', summary: 'Choose whether to get news', access: 'user', body: loose, documented: { body: D.obj({ email: D.optBool, whatsapp: D.optBool, source: D.optStr.describe('Where it was changed, for the consent log') }), response: D.obj({ news, newsAskedAt: D.optDate }) }, v1: privacy.updateMyNews }); +v1Route({ method: 'get', path: '/me/privacy/export', tag: 'Privacy', summary: 'Download everything held about me', description: '`format=pdf` or JSON (the default).', access: 'user', middleware: [exportLimiter], query: filters('format'), file: { contentType: 'application/json' }, v1: privacy.exportMyData }); +v1Route({ method: 'post', path: '/me/privacy/requests', tag: 'Privacy', summary: 'Ask for my data to be corrected or deleted', access: 'user', status: 201, body: loose, documented: { body: D.obj({ type: z.enum(['correction', 'deletion']), details: D.optStr.describe('A correction: what to change'), password: D.optStr.describe('A deletion: closes the account too') }), response: D.obj({ request: dataRequest, message: D.str }) }, v1: privacy.createMyRequest }); +v1Route({ method: 'post', path: '/me/privacy/notice/accept', tag: 'Privacy', summary: 'Accept the privacy notice', access: 'user', body: loose, documented: { response: D.obj({ version: D.num.describe('The version accepted') }) }, v1: privacy.acceptMyNotice }); +v1Route({ method: 'get', path: '/privacy/notice', tag: 'Privacy', summary: 'The published privacy notice', access: 'public', query: filters('version'), documented: { response: D.obj({ version: D.num.describe('0: the built-in text'), builtIn: D.optBool, current: D.optBool, publishedAt: D.optDate, effectiveDate: D.optStr, changeSummary: D.optStr, sections: z.array(D.anyObj).describe('Rendered sections'), versions: z.array(D.anyObj).describe('Every published version') }) }, v1: privacy.getNotice }); +v1Route({ method: 'get', path: '/unsubscribe/:token', tag: 'Privacy', summary: 'What an unsubscribe link is for', description: 'The token in the link is the credential.', access: 'public', params: tokenParams, documented: { response: D.obj({ kind: z.enum(['account', 'address']), email: D.optStr.describe('Partly hidden'), hasPhone: D.optBool, news: D.obj({ email: D.bool, whatsapp: D.bool }).optional(), address: D.optStr.describe('kind address: the email or phone, partly hidden') }) }, v1: privacy.getUnsubscribe }); +v1Route({ method: 'post', path: '/unsubscribe/:token', tag: 'Privacy', summary: 'Unsubscribe with a link', access: 'public', params: tokenParams, body: loose, documented: { body: D.obj({ channels: z.array(z.enum(['email', 'whatsapp'])).optional().describe('Default: the link\'s channel') }), response: D.message }, v1: privacy.postUnsubscribe }); + +// ─── Privacy admin ─────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/privacy/requests', tag: 'Privacy', summary: 'Data requests', description: '`status=open` (default), `closed` or `all`.', access: 'admin', query: filters('status', 'search', 'page', 'limit'), documented: { response: D.obj({ requests: z.array(dataRequest.extend({ overdue: D.optBool, blockers: z.array(D.anyObj).optional().describe('Upcoming registrations that stop a deletion') })), openCount: D.num, total: D.num, page: D.num, limit: D.num, pages: D.num }) }, v1: privacy.listRequests }); +v1Route({ method: 'post', path: '/privacy/requests/:id/complete', tag: 'Privacy', summary: 'Mark a data request done', access: 'admin', params: idParams, body: loose, documented: { body: D.obj({ response: D.optStr.describe('Emailed to them; needed for a correction') }), response: D.obj({ request: dataRequest, anonymised: D.anyObj.nullish().describe('A deletion: what was removed') }) }, v1: privacy.completeRequest }); +v1Route({ method: 'post', path: '/privacy/requests/:id/reject', tag: 'Privacy', summary: 'Turn down a data request', access: 'admin', params: idParams, body: loose, documented: { body: D.obj({ response: D.str.describe('The reason, emailed to them'), cancelled: D.optBool.describe('They withdrew it') }), response: D.obj({ request: dataRequest }) }, v1: privacy.rejectRequest }); +v1Route({ method: 'get', path: '/privacy/notice/draft', tag: 'Privacy', summary: 'The privacy notice being drafted', access: 'admin', documented: { response: D.obj({ sections: z.array(noticeSection), isDraft: D.optBool, rendered: z.array(D.anyObj).describe('The sections with placeholders filled in'), placeholders: z.array(D.str).describe('The placeholders the text can use'), versions: z.array(D.anyObj).describe('Published versions'), builtIn: z.array(noticeSection), builtInUpdates: z.array(D.anyObj).describe('Changes to the built-in text not reviewed yet') }) }, v1: privacy.getNoticeDraft }); +v1Route({ method: 'put', path: '/privacy/notice/draft', tag: 'Privacy', summary: 'Save the draft notice', access: 'admin', body: loose, documented: { body: D.obj({ sections: z.array(noticeSection) }), response: D.obj({ sections: z.array(noticeSection), rendered: z.array(D.anyObj), isDraft: z.literal(true), savedAt: D.date }) }, v1: privacy.saveNoticeDraft }); +v1Route({ method: 'delete', path: '/privacy/notice/draft', tag: 'Privacy', summary: 'Throw the draft away', access: 'admin', documented: { response: D.message }, v1: privacy.discardNoticeDraft }); +v1Route({ method: 'post', path: '/privacy/notice/publish', tag: 'Privacy', summary: 'Publish the draft notice', description: 'Everyone is asked to accept it at their next sign-in.', access: 'admin', body: loose, documented: { body: D.obj({ sections: z.array(noticeSection).optional(), changeSummary: D.str.describe('Shown to people asked to accept it'), requiresAcceptance: D.optBool }), response: D.obj({ version: D.num, publishedAt: D.date, requiresAcceptance: D.bool }) }, v1: privacy.publishNotice }); +v1Route({ method: 'post', path: '/privacy/notice/builtin-reviewed', tag: 'Privacy', summary: 'Mark the built-in notice as reviewed', access: 'admin', body: loose, documented: { response: D.obj({ builtInUpdates: z.array(D.anyObj) }) }, v1: privacy.markBuiltInReviewed }); +v1Route({ method: 'get', path: '/privacy/operators', tag: 'Privacy', summary: 'Who processes personal information for the church', access: 'admin', documented: { response: z.array(operator) }, v1: privacy.listOperators }); +v1Route({ method: 'post', path: '/privacy/operators', tag: 'Privacy', summary: 'Add an operator', access: 'admin', status: 201, body: loose, documented: { body: operatorInput, response: operator }, v1: privacy.createOperator }); +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.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 }); +v1Route({ method: 'post', path: '/privacy/retention/run', tag: 'Privacy', summary: 'Apply the retention rules now', access: 'admin', body: loose, documented: { response: D.obj({ result: D.anyObj.describe('What was removed or anonymised'), state: retentionState }) }, v1: privacy.runRetentionNow }); +v1Route({ method: 'get', path: '/privacy/breaches', tag: 'Privacy', summary: 'Recorded data breaches', access: 'admin', documented: { response: z.array(breach) }, v1: privacy.listBreaches }); +v1Route({ method: 'post', path: '/privacy/breaches', tag: 'Privacy', summary: 'Record a data breach', access: 'admin', status: 201, body: loose, documented: { body: breachInput, response: breach }, v1: privacy.createBreach }); +v1Route({ method: 'put', path: '/privacy/breaches/:id', tag: 'Privacy', summary: 'Update a data breach', access: 'admin', params: idParams, body: loose, documented: { body: breachInput.partial(), response: breach }, v1: privacy.updateBreach }); + +// ─── Admin ─────────────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/admin/audit-log', tag: 'Admin', summary: 'The audit log', access: 'admin', query: filters('page', 'limit', 'actorId', 'action', 'role', 'from', 'to', 'search'), documented: { response: D.obj({ rows: z.array(D.auditEntry), total: D.num, page: D.num, limit: D.num }) }, v1: audit.listAuditLog }); +v1Route({ method: 'get', path: '/admin/jobs', tag: 'Admin', summary: 'Background jobs', access: 'admin', documented: { response: D.obj({ mode: D.str.describe('on, off or timers'), timezone: D.str, jobs: z.array(D.obj({ name: D.str, label: D.str, cron: D.optStr, enabled: D.bool, envFlag: D.optStr, nextRun: D.optDate, recent: z.array(D.anyObj).describe('Recent runs') })) }) }, v1: jobs.listJobs }); +v1Route({ method: 'post', path: '/admin/jobs/:name/run', tag: 'Admin', summary: 'Run a background job now', access: 'admin', params: z.object({ name: z.string().min(1).max(100) }), body: loose, documented: { response: D.obj({ queued: D.bool, id: D.optStr, output: z.unknown().optional().describe('When it ran straight away') }) }, v1: jobs.runJobNow }); +v1Route({ method: 'get', path: '/admin/impersonation-sessions', tag: 'Admin', summary: 'Times admins viewed the site as someone else', access: 'admin', query: filters('limit'), documented: { response: z.array(D.obj({ id: D.str, reason: D.optStr, startedAt: D.optDate, endedAt: D.optDate, expiresAt: D.optDate, admin: D.obj({ name: D.str, email: D.optStr }).nullish(), target: D.obj({ name: D.str, email: D.optStr }).nullish(), requests: z.array(D.obj({ method: D.str, path: D.str, blocked: D.bool, createdAt: D.date })).describe('What they did (up to 500)') })) }, v1: imp.listSessions }); +v1Route({ method: 'post', path: '/admin/impersonate/:userId', tag: 'Admin', summary: 'View the site as someone (read-only)', description: 'Answers a token for a read-only session, logged.', access: 'admin', params: z.object({ userId: z.string().min(1).max(64) }), body: loose, documented: { body: D.obj({ reason: D.str.describe('Why — kept in the log') }), response: D.obj({ token: D.str.describe('A read-only sign-in token'), session: D.obj({ id: D.str, expiresAt: D.date, target: D.obj({ id: D.str, name: D.str, email: D.str, role: D.str }) }) }) }, v1: imp.startImpersonation }); +v1Route({ method: 'get', path: '/me/impersonation', tag: 'Admin', summary: 'The viewing-as session I\'m in, if any', access: 'user', documented: { response: D.obj({ id: D.str, expiresAt: D.date, target: D.userRef }).nullable() }, v1: imp.currentImpersonation }); +v1Route({ method: 'post', path: '/me/impersonation/end', tag: 'Admin', summary: 'Stop viewing as someone', access: 'user', body: loose, documented: { response: D.message }, v1: imp.endImpersonation }); +v1Route({ method: 'post', path: '/me/impersonation/log', tag: 'Admin', summary: 'Record a page viewed while viewing as someone', access: 'user', body: loose, documented: { body: D.obj({ path: D.str }), response: z.null().describe('Always 204, no content') }, v1: imp.logPageView }); + +// ─── Settings and first-run set-up ─────────────────────────────────────────── + +v1Route({ method: 'get', path: '/settings', tag: 'Site', summary: 'Public site settings', description: 'Name, branding, contact details and what\'s switched on.', access: 'public', documented: { response: z.record(z.string(), z.string()).describe('Setting key → value: name, logo, colours, contact details, what\'s switched on') }, v1: settings.getSettings }); +v1Route({ method: 'get', path: '/settings/all', tag: 'Site', summary: 'Every setting', description: 'Admins. Secrets are masked.', access: 'admin', documented: { response: z.record(z.string(), z.unknown()).describe('Setting key → value; secrets masked') }, v1: settings.getAllSettings }); +v1Route({ method: 'put', path: '/settings', tag: 'Site', summary: 'Change settings', access: 'admin', body: loose, documented: { body: z.record(z.string(), z.unknown()).describe('Setting key → new value'), response: D.message }, v1: settings.updateSettings }); +v1Route({ method: 'post', path: '/settings/test-smtp', tag: 'Site', summary: 'Send a test email', access: 'admin', body: loose, documented: { body: D.obj({ host: D.optStr, port: D.numeric.optional(), secure: z.union([D.bool, D.str]).optional(), user: D.optStr, pass: D.optStr, from: D.optStr }).describe('Unsaved SMTP details to try (default: the saved ones)'), response: D.message }, v1: settings.testSmtp }); +v1Route({ method: 'get', path: '/setup/needed', tag: 'Site', summary: 'Does the site still need setting up?', access: 'public', documented: { response: D.obj({ needsSetup: D.bool }) }, v1: settings.needsSetup }); +v1Route({ method: 'post', path: '/setup/register', tag: 'Site', summary: 'Create the first admin', description: 'Only while no account exists.', access: 'public', body: loose, documented: { body: D.obj({ adminName: D.str, adminEmail: D.str, adminPassword: D.str.describe('At least 8 characters') }), response: D.obj({ token: D.str, name: D.str, email: D.str }) }, v1: settings.setupRegister }); +v1Route({ method: 'post', path: '/setup', tag: 'Site', summary: 'Finish first-run set-up', access: 'admin', body: loose, documented: { body: D.obj({ settings: z.record(z.string(), z.unknown()).describe('Setting key → value') }), response: D.message }, v1: settings.runSetup }); + +// ─── Hub ───────────────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/hub/status', tag: 'Site', summary: 'The connection to the provider\'s Hub', access: 'admin', documented: { response: hubStatus }, v1: hub.getStatus }); +v1Route({ method: 'post', path: '/hub/connect', tag: 'Site', summary: 'Connect to the Hub', access: 'admin', body: loose, documented: { body: D.obj({ licenceKey: D.str }), response: hubStatus }, v1: hub.connect }); +v1Route({ method: 'post', path: '/hub/heartbeat', tag: 'Site', summary: 'Check in with the Hub now', access: 'admin', body: loose, documented: { response: hubStatus }, v1: hub.heartbeatNow }); +v1Route({ method: 'post', path: '/hub/update-request', tag: 'Site', summary: 'Ask for the update to be installed', access: 'admin', body: loose, documented: { response: hubStatus }, v1: hub.requestUpdate }); +v1Route({ method: 'post', path: '/hub/update-request/cancel', tag: 'Site', summary: 'Withdraw the update request', access: 'admin', body: loose, documented: { response: hubStatus }, v1: hub.cancelUpdateRequest }); +v1Route({ method: 'post', path: '/hub/update-snooze', tag: 'Site', summary: 'Remind me about the update later', access: 'admin', body: loose, documented: { body: D.obj({ snooze: D.optBool.describe('false: stop putting it off') }), response: hubStatus }, v1: hub.snoozeUpdate }); +v1Route({ + method: 'get', path: '/hub/notices', tag: 'Site', summary: 'Notices from the provider', + access: 'supervisor', campusScope: 'campusIndependent (notices from the provider are for the whole site)', middleware: [campusIndependent('notices from the provider are for the whole site')], documented: { response: z.array(D.obj({ id: D.str, level: D.str.describe('info, warning, critical'), title: D.str, message: D.str, startsAt: D.optDate, endsAt: D.optDate, updatedAt: D.optDate })) }, v1: hub.getNotices, +}); + +// ─── Outbound webhooks ─────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/outbound-webhooks', tag: 'Webhooks', summary: 'Webhooks the site sends', access: 'admin', documented: { response: D.obj({ eventTypes: z.array(D.anyObj).describe('Every event type, with an example body'), keepDays: D.num.describe('How long deliveries are kept'), endpoints: z.array(webhook.extend({ lastWeek: z.record(z.string(), z.number()).describe('Status → deliveries in the last 7 days') })) }) }, v1: hooks.list }); +v1Route({ method: 'post', path: '/outbound-webhooks', tag: 'Webhooks', summary: 'Add a webhook', description: 'Answers its signing secret once.', access: 'admin', status: 201, body: loose, documented: { body: D.obj({ name: D.str, url: D.str.describe('https:// address'), events: z.array(D.str) }), response: webhook.extend({ secret: D.str.describe('For checking signatures — shown only now') }) }, v1: hooks.create }); +v1Route({ method: 'post', path: '/outbound-webhook-deliveries/:id/resend', tag: 'Webhooks', summary: 'Send a delivery again', access: 'admin', params: idParams, body: loose, documented: { response: delivered }, v1: hooks.resend }); +v1Route({ method: 'patch', path: '/outbound-webhooks/:id', tag: 'Webhooks', summary: 'Change a webhook', access: 'admin', params: idParams, body: loose, documented: { body: D.obj({ name: D.optStr, url: D.optStr, events: z.array(D.str).optional(), isActive: D.optBool }), response: webhook }, v1: hooks.update }); +v1Route({ method: 'delete', path: '/outbound-webhooks/:id', tag: 'Webhooks', summary: 'Remove a webhook', access: 'admin', params: idParams, documented: { response: D.ok }, v1: hooks.remove }); +v1Route({ method: 'post', path: '/outbound-webhooks/:id/rotate-secret', tag: 'Webhooks', summary: 'Give a webhook a new signing secret', access: 'admin', params: idParams, body: loose, documented: { response: D.obj({ secret: D.str.describe('Shown only now; the old one stops working') }) }, v1: hooks.rotateSecret }); +v1Route({ method: 'post', path: '/outbound-webhooks/:id/test', tag: 'Webhooks', summary: 'Send a test delivery', access: 'admin', params: idParams, body: loose, documented: { response: delivered }, v1: hooks.test }); +v1Route({ method: 'get', path: '/outbound-webhooks/:id/deliveries', tag: 'Webhooks', summary: 'A webhook\'s recent deliveries', access: 'admin', params: idParams, query: filters('page', 'limit', 'status', 'before'), documented: { response: z.array(D.obj({ id: D.str, eventId: D.str, type: D.str.describe('The event type'), payload: z.unknown(), status: D.str.describe('pending, sending, retrying, succeeded, failed'), attempts: D.num, nextAttemptAt: D.optDate, lastStatusCode: D.optNum, lastError: D.optStr, createdAt: D.date, deliveredAt: D.optDate })) }, v1: hooks.deliveries }); + +// ─── Backups ───────────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/backups', tag: 'Admin', summary: 'Database backups', access: 'admin', documented: { response: z.array(D.obj({ filename: D.str, size: D.num.describe('Bytes'), createdAt: D.date })) }, v1: backups.getBackups }); +v1Route({ method: 'post', path: '/backups/run', tag: 'Admin', summary: 'Back up the database now', access: 'admin', body: loose, documented: { response: D.anyObj.describe('The backup made') }, v1: backups.triggerBackup }); +v1Route({ method: 'get', path: '/backups/:filename/download', tag: 'Admin', summary: 'Download a backup', access: 'admin', params: z.object({ filename: z.string().min(1).max(200) }), file: { contentType: 'application/octet-stream' }, v1: backups.downloadBackup }); + +// ─── Yoco and PayFast settings (admins; their incoming webhooks are separate) ─ + +const yoco = require('../../controllers/yocoController'); +const payfast = require('../../controllers/payfastController'); +v1Route({ method: 'get', path: '/payments/yoco/config', tag: 'Payments', summary: 'Yoco settings', description: 'Keys are masked.', access: 'admin', documented: { response: D.obj({ secretKeyMasked: D.str, secretKeySource: D.optStr.describe('settings or env'), mode: D.optStr.describe('test or live'), webhookSecretMasked: D.str, webhookSecretSource: D.optStr, webhookId: D.str, webhookUrl: D.str, configured: D.bool }) }, v1: yoco.getConfig }); +v1Route({ method: 'put', path: '/payments/yoco/config', tag: 'Payments', summary: 'Change Yoco settings', access: 'admin', body: loose, documented: { body: D.obj({ secretKey: D.optStr.describe('sk_test_… or sk_live_…'), webhookSecret: D.optStr.describe('whsec_…') }), response: D.message }, v1: yoco.updateConfig }); +v1Route({ method: 'get', path: '/payments/yoco/webhooks', tag: 'Payments', summary: 'Webhooks registered with Yoco', access: 'admin', documented: { response: D.obj({ webhooks: z.array(D.obj({ id: D.str, name: D.optStr, url: D.str, mode: D.optStr, isActive: D.bool, pointsHere: D.bool })), defaultUrl: D.str }) }, v1: yoco.getWebhooks }); +v1Route({ method: 'post', path: '/payments/yoco/webhooks', tag: 'Payments', summary: 'Register a webhook with Yoco', access: 'admin', body: loose, documented: { body: D.obj({ name: D.optStr, url: D.optStr.describe('Default: this site\'s webhook address') }), response: D.obj({ message: D.str, webhook: D.obj({ id: D.str, name: D.optStr, url: D.str, mode: D.optStr }), webhookSecretMasked: D.str }) }, v1: yoco.createWebhook }); +v1Route({ method: 'delete', path: '/payments/yoco/webhooks/:id', tag: 'Payments', summary: 'Remove a webhook from Yoco', access: 'admin', params: z.object({ id: z.string().min(1).max(200) }), documented: { response: D.obj({ message: D.str, clearedSecret: D.bool }) }, v1: yoco.removeWebhook }); +v1Route({ method: 'get', path: '/payments/payfast/config', tag: 'Payments', summary: 'PayFast settings', description: 'The passphrase is masked.', access: 'admin', documented: { response: D.obj({ merchantId: D.str, merchantKey: D.str, passphraseMasked: D.str, hasPassphrase: D.bool, mode: z.enum(['sandbox', 'live']), notifyUrl: D.str, notifyUrlProblem: D.optStr.describe('Why PayFast couldn\'t reach it'), configured: D.bool }) }, v1: payfast.getConfig }); +v1Route({ method: 'put', path: '/payments/payfast/config', tag: 'Payments', summary: 'Change PayFast settings', access: 'admin', body: loose, documented: { body: D.obj({ merchantId: D.optStr, merchantKey: D.optStr, passphrase: D.optStr.describe('At most 32 characters'), mode: z.enum(['sandbox', 'live']).optional() }), response: D.message }, v1: payfast.updateConfig }); +v1Route({ method: 'post', path: '/payments/payfast/test', tag: 'Payments', summary: 'Check the PayFast details work', access: 'admin', body: loose, documented: { response: D.message }, v1: payfast.testConnection }); diff --git a/apps/events/backend/src/v2/resources/ai.ts b/apps/events/backend/src/v2/resources/ai.ts new file mode 100644 index 0000000..ddb8559 --- /dev/null +++ b/apps/events/backend/src/v2/resources/ai.ts @@ -0,0 +1,194 @@ +import { z } from 'zod'; +import { defineRoute } from '../route'; +import { single } from '../paging'; +import { id } from '../schemas'; +import { notFound } from '../errors'; +import { prisma } from '../legacy'; +import { aiStatus, getAiSettings, saveAiSettings, usageThisMonth, HELPERS, clearAiStatusCache } from '../../ai'; +import { draftEvent, summariseReport, draftMessage, summariseFeedback, improveText, REPORTS_WITHOUT_PEOPLE, REPORTS_WITH_PEOPLE, REPORT_KEYS, SENSITIVE_REPORTS, type FeedbackQuestion } from '../../ai/helpers'; + +const ACCESS_AI_REPORT = 'Report summarised by the AI helper (anonymised totals)'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */ +const { campusIndependent, scopeBody } = require('../../utils/campusScope') as { campusIndependent(reason: string): any; scopeBody(targets: [string, string][], opts?: object): any }; +const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; +const { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; what?: string; eventId?: string; records?: number; sensitive?: boolean }): Promise }; +const feedbackUtils = require('../../utils/feedback') as { summarise(fields: unknown[], answers: { fieldId: string; value: string }[]): any[] }; + +const helperFlags = z.object(Object.fromEntries(HELPERS.map(h => [h, z.boolean()])) as Record<(typeof HELPERS)[number], z.ZodBoolean>); + +const status = z.object({ + enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'), + capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'), + available: z.boolean().describe('false: the Hub couldn\'t be reached just now'), + capCents: z.number().describe('The monthly allowance, in cents'), + usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'), + usedPercent: z.number(), + renewsOn: z.string().nullable().describe('YYYY-MM-DD'), + helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'), +}); + +const settings = z.object({ + helpers: helperFlags, + dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'), +}); + +const use = z.object({ uses: z.number().int(), chargedCents: z.number() }); + +export const getAiStatus = defineRoute({ + method: 'get', + path: '/ai/status', + tag: 'AI', + summary: 'Whether to show the AI buttons', + description: 'Hidden when `enabled` is false; shown but disabled when `capReached` (until `renewsOn`, or until the allowance is raised). Cached for a minute; every AI call refreshes it.', + access: 'supervisor', + campusScope: 'campusIndependent (the site\'s AI allowance)', + middleware: [campusIndependent('the site\'s AI allowance')], + response: single(status), + async handler() { + return { data: await aiStatus() }; + }, +}); + +export const getAiUsage = defineRoute({ + method: 'get', + path: '/ai/usage', + tag: 'AI', + summary: 'AI use this month', + description: 'For Site settings → AI: the allowance, this site\'s switches, and this month\'s use per person, per helper and per day.', + access: 'admin', + response: single(z.object({ + status, + settings, + people: z.array(use.extend({ userId: z.string().nullable(), name: z.string() })), + helpers: z.array(use.extend({ helper: z.string() })), + days: z.array(use.extend({ day: z.string() })), + })), + async handler() { + clearAiStatusCache(); + const [s, settingsNow, usage] = await Promise.all([aiStatus({ fresh: true }), getAiSettings(), usageThisMonth()]); + return { data: { status: s, settings: settingsNow, ...usage } }; + }, +}); + +export const updateAiSettings = defineRoute({ + method: 'put', + path: '/ai/settings', + tag: 'AI', + summary: 'Switch helpers on or off, and set a daily limit', + access: 'admin', + body: z.object({ helpers: helperFlags.partial().optional(), dailyLimitPerPerson: z.number().int().min(0).max(1000).optional() }), + response: single(settings), + async handler({ body, user, req }) { + return { data: await saveAiSettings(body, user!, getClientIp(req)) }; + }, +}); + +// ─── The helpers ────────────────────────────────────────────────────────────── +// Each answer is a suggestion for a person to check: nothing is saved or sent by these routes. + +const withStatus = (output: T) => single(z.object({ output, status })); +const HELPER_SCOPE = 'campusIndependent (an AI suggestion from what is sent; nothing is read or changed)'; +const helperAccess = { access: 'supervisor' as const, campusScope: HELPER_SCOPE, middleware: [campusIndependent('an AI suggestion from what is sent; nothing is read or changed')] }; +const AI_DESCRIPTION = 'Goes through the Cross Events Hub, which counts it against the site\'s monthly AI allowance. Errors carry a `reason`: AI_OFF, AI_HELPER_OFF, AI_CAP_REACHED, AI_DAILY_LIMIT, AI_REFUSED, AI_INCOMPLETE, AI_UNAVAILABLE.'; + +const textList = z.array(z.string()); +const eventDraft = z.object({ + title: z.string(), summary: z.string(), description: z.string(), + startDate: z.string(), startTime: z.string(), endDate: z.string(), endTime: z.string(), + location: z.string(), capacity: z.number(), needsParentalConsent: z.boolean(), ageGroup: z.string(), + ticketOptions: z.array(z.object({ name: z.string(), priceRand: z.number(), description: z.string(), earlyBirdPriceRand: z.number(), earlyBirdUntil: z.string() })), + sessions: z.array(z.object({ date: z.string(), startTime: z.string(), endTime: z.string(), label: z.string() })), + costs: z.array(z.object({ item: z.string(), basis: z.string(), amountRand: z.number() })), + checks: textList, +}); + +export const aiDraftEvent = defineRoute({ + method: 'post', path: '/ai/draft-event', tag: 'AI', summary: 'Draft an event from a description', + description: `Fills in the event form from the organiser's notes. \`warnings\` are checked in code (a weekday that doesn't match its date, costs that a full event can't cover); \`draft.checks\` are the AI's own. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ notes: z.string().trim().min(10).max(4000) }), + response: withStatus(z.object({ draft: eventDraft, warnings: textList, totalCostRand: z.number(), breakEvenPlaces: z.number().nullable() })), + async handler({ body, user }) { + const { status: s, ...output } = await draftEvent(user!.id, body.notes); + return { data: { output, status: s } }; + }, +}); + +export const aiSummariseReport = defineRoute({ + method: 'post', path: '/ai/summarise-report', tag: 'AI', summary: 'Summarise a report', + description: `A few plain-language insights on a report. Reports without people in them (${REPORTS_WITHOUT_PEOPLE.join(', ')}) are sent as they are on screen; reports that list people (${REPORTS_WITH_PEOPLE.join(', ')}) only as anonymised totals: a column that would carry a person (name, email, notes, …) is refused with \`AI_REPORT_HAS_PEOPLE\`, and each one is recorded in the access log. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ + reportKey: z.enum(REPORT_KEYS), + title: z.string().max(300), subtitle: z.string().max(500).optional(), + stats: z.array(z.object({ label: z.string().max(200), value: z.union([z.string().max(200), z.number()]) })).max(40).optional(), + columns: z.array(z.string().max(200)).max(40), + rows: z.array(z.array(z.union([z.string().max(500), z.number(), z.null()]).transform(v => v ?? ''))).max(5000), + }), + response: withStatus(z.object({ headline: z.string(), insights: z.array(z.object({ title: z.string(), detail: z.string() })), watchOut: textList })), + async handler({ body, user, req }) { + const { summary, status: s } = await summariseReport(user!.id, body); + if ((REPORTS_WITH_PEOPLE as readonly string[]).includes(body.reportKey)) { + await logDataAccess(req, { action: 'ai_report', what: `${ACCESS_AI_REPORT}: ${body.title}`, records: body.rows.length, sensitive: SENSITIVE_REPORTS.includes(body.reportKey) }); + } + return { data: { output: summary, status: s } }; + }, +}); + +export const aiDraftMessage = defineRoute({ + method: 'post', path: '/ai/draft-message', tag: 'AI', summary: 'Draft an email or WhatsApp message', + description: `Turns a short note into a message, using {{name}} and the event placeholders. With \`eventId\`, the event's title, start and place are given to the AI as facts. ${AI_DESCRIPTION}`, + access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])], + body: z.object({ channel: z.enum(['email', 'whatsapp']), note: z.string().trim().min(3).max(3000), eventId: id.optional() }), + response: withStatus(z.object({ subject: z.string(), body: z.string() })), + async handler({ body, user }) { + let event = null; + if (body.eventId) { + const e = await prisma.event.findUnique({ where: { id: body.eventId }, select: { title: true, startDate: true, location: true } }); + if (!e) throw notFound('The event'); + event = { title: e.title, start: e.startDate.toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }), location: e.location }; + } + const { message, status: s } = await draftMessage(user!.id, { channel: body.channel, note: body.note, event }); + return { data: { output: message, status: s } }; + }, +}); + +export const aiSummariseFeedback = defineRoute({ + method: 'post', path: '/ai/summarise-feedback', tag: 'AI', summary: 'Summarise an event\'s feedback', + description: `Themes, what people liked, what to improve and suggestions, from the event's feedback. Sent without who answered; contact details in comments are kept back. Recorded in the access log. ${AI_DESCRIPTION}`, + access: 'supervisor', campusScope: 'scopeBody(eventId)', middleware: [scopeBody([['eventId', 'event']])], + body: z.object({ eventId: id }), + response: withStatus(z.object({ + overall: z.string(), liked: z.array(z.object({ theme: z.string(), mentions: z.number() })), improve: z.array(z.object({ theme: z.string(), mentions: z.number() })), + quotes: textList, nextTime: textList, responses: z.number(), + })), + async handler({ body, user, req }) { + const form = await prisma.feedbackForm.findUnique({ + where: { eventId: body.eventId }, + include: { event: { select: { title: true } }, fields: { orderBy: { order: 'asc' } }, responses: { include: { answers: true } }, _count: { select: { invites: true } } }, + }); + if (!form) throw notFound('Feedback for this event'); + if (!form.responses.length) throw Object.assign(notFound('Feedback answers for this event'), { reason: 'AI_NOTHING_TO_SUMMARISE' }); + // Never who answered: only the answers. + const answers = form.responses.flatMap(r => r.answers.map(a => ({ fieldId: a.fieldId, value: a.value }))); + const questions: FeedbackQuestion[] = feedbackUtils.summarise(form.fields, answers).map((q: any) => ({ + label: q.label, type: q.type, answered: q.answered, average: q.average, counts: q.counts, texts: q.texts?.map((t: { value: string }) => t.value), + })); + await logDataAccess(req, { action: 'ai_feedback', eventId: body.eventId, records: form.responses.length }); + const { summary, status: s } = await summariseFeedback(user!.id, { event: form.event, responses: form.responses.length, invited: form._count.invites, questions }); + return { data: { output: { ...summary, responses: form.responses.length }, status: s } }; + }, +}); + +export const aiImproveText = defineRoute({ + method: 'post', path: '/ai/improve-text', tag: 'AI', summary: 'Improve a piece of text', + description: `Fixes spelling and grammar and makes it clearer (\`improve\`), shorter (\`shorter\`) or only fixes mistakes (\`fix\`), keeping every fact. ${AI_DESCRIPTION}`, + ...helperAccess, + body: z.object({ text: z.string().trim().min(3).max(8000), mode: z.enum(['improve', 'shorter', 'fix']).default('improve'), where: z.enum(['description', 'banner', 'message']).default('description') }), + response: withStatus(z.object({ text: z.string(), changes: textList })), + async handler({ body, user }) { + const { result, status: s } = await improveText(user!.id, body); + return { data: { output: result, status: s } }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/attendance.ts b/apps/events/backend/src/v2/resources/attendance.ts new file mode 100644 index 0000000..7415c71 --- /dev/null +++ b/apps/events/backend/src/v2/resources/attendance.ts @@ -0,0 +1,230 @@ +/** + * Tickets and attendance on v2 (1.51.12): tickets (mine, one, sending, transfers, the staff + * lists, generating), scan locks (offline scanning), the attendance register and certificates, + * and allocations (groups, rooms, teams). Each route runs the v1 handler (viaV1.ts) behind the + * same access and campus checks as v1. Scanning itself is /checkin (1.51.2). + */ +import { z } from 'zod'; +import { id, idParams } from '../schemas'; +import { v1Route } from '../viaV1'; +import * as D from '../docs'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- v1 handlers and middleware are JavaScript */ +const cs = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown; ownerOk?: boolean; nameCampus?: boolean }): any; + scopeBody(targets: [string, string][], opts?: { need?: 'view' | 'manage'; orphan?: 'pass' | 'deny' }): any; + scopeList: any; + campusIndependent(reason: string): any; +}; +const t = require('../../controllers/ticketController'); +const locks = require('../../controllers/scanLockController'); +const att = require('../../controllers/attendanceController'); +const alloc = require('../../controllers/allocationController'); + +const filters = (...names: string[]) => z.looseObject(Object.fromEntries(names.map(n => [n, z.string().max(4000).optional()]))); +const asEvent = (ctx: any) => ({ params: { ...ctx.req.params, eventId: ctx.params.id } }); +const loose = z.looseObject({}); +const tokenParams = z.object({ token: z.string().min(1).max(200) }); +const SCOPE_LIST = 'scopeList (the handler filters by listWhere)'; + +// ─── Documented shapes (docs.ts) ───────────────────────────────────────────── + +const usage = D.obj({ id: D.str.optional(), scannedAt: D.date, quantityRedeemed: D.num, sessionId: D.optStr, manual: D.optBool.describe('Ticked present by hand') }); +const ticketFull = D.ticket.extend({ + usages: z.array(usage).optional().describe('Check-ins'), + event: D.event.partial().nullish(), + user: D.userSummary.nullish().describe('The payer'), + attendee: D.obj({ name: D.str }).nullish(), + registrationOption: D.obj({ eventOption: D.eventOption.partial().nullish(), variant: D.obj({ name: D.str }).nullish(), registration: D.registration.partial().nullish() }).nullish(), +}); +const sent = D.obj({ message: D.str, ticketIds: D.ids.optional().describe('The tickets sent') }); +const lockView = D.obj({ + id: D.str, eventId: D.str, sectionId: D.optStr, sectionName: D.optStr, deviceId: D.str, deviceName: D.optStr, + user: D.userRef.nullish().describe('Who holds it'), lockedAt: D.date, snapshotAt: D.optDate, lastSyncAt: D.optDate, releasedAt: D.optDate, +}); +const transferInput = D.obj({ + name: D.str.describe('Who it goes to'), email: D.optStr, phone: D.optStr.describe('Email or phone needed'), + dateOfBirth: D.optDate.describe('Youth events'), gender: D.optStr, parentName: D.optStr, parentEmail: D.optStr, parentPhone: D.optStr, +}); +const certificate = D.obj({ id: D.str, code: D.str.describe('For checking it at /verify'), name: D.str, issuedAt: D.date, sessionsAttended: D.optNum, totalSessions: D.optNum, event: D.eventRef.partial().nullish() }); +const registerRow = D.obj({ + ticketId: D.str, bookedSessions: D.ids.nullable().describe('Picked/ticked sessions (null: all)'), sessionTickets: z.record(z.string(), z.string()).nullable(), + name: D.str, bookedBy: D.str, email: D.str, phone: D.str, option: D.str, variant: D.optStr, quantity: D.num, + checkIns: z.record(z.string(), z.number()).describe('Session id (or `event`) → people checked in'), + attended: D.num, total: D.num, completed: D.bool.describe('Meets the certificate rule'), certificate: D.anyObj.nullish(), +}); +const groupInput = D.obj({ + name: D.optStr, capacity: D.numeric.nullish(), gender: z.enum(['male', 'female', 'mixed']).nullish(), leaderUserId: D.optStr.describe('A staff member'), + minAge: D.numeric.nullish(), maxAge: D.numeric.nullish(), ratio: D.numeric.nullish().describe('Children per leader'), +}); +const group = D.obj({ id: D.str, setId: D.str, name: D.str, capacity: D.optNum, gender: D.optStr, leaderUserId: D.optStr, minAge: D.optNum, maxAge: D.optNum, ratio: D.optNum, order: D.num }); +const allocationSet = D.obj({ id: D.str, eventId: D.str, name: D.str, showOnTicket: D.bool, order: D.num }); +const member = D.obj({ attendeeId: D.str.optional(), name: D.str, gender: D.optStr, dateOfBirth: D.optDate, groupId: D.optStr }); +const ticketOwner = cs.scopeEvent({ resolve: 'ticket', ownerOk: true }); +const qrScope = cs.scopeEvent({ resolve: 'ticketQr', from: (req: any) => req.params.qrCode, nameCampus: true }); + +// ─── Tickets ───────────────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/me/tickets', tag: 'Tickets', summary: 'My tickets', description: 'Including ones transferred to me.', access: 'user', documented: { response: z.array(ticketFull) }, v1: t.getUserTickets }); +v1Route({ + method: 'post', path: '/me/tickets/email', tag: 'Tickets', summary: 'Send me my tickets', + description: 'For a registration (`registrationId`) or chosen tickets (`ticketIds`), by email and/or WhatsApp (`channel`).', + access: 'user', body: z.looseObject({ registrationId: id.optional(), ticketIds: z.array(id).max(500).optional(), channel: z.string().max(20).optional() }), documented: { response: sent }, v1: t.emailTickets, +}); +v1Route({ + method: 'get', path: '/tickets/scans/recent', tag: 'Tickets', summary: 'Recent scans', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventId', 'limit'), documented: { response: z.array(D.obj({ id: D.str, scannedAt: D.date, quantityRedeemed: D.num, scannedBy: D.userRef.nullish(), ticket: D.obj({ id: D.str, event: D.obj({ title: D.str }), registrationOption: D.anyObj.nullish() }) })) }, v1: t.getRecentScans, +}); +v1Route({ + method: 'get', path: '/tickets/scans/stats', tag: 'Tickets', summary: 'Scan counts', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventId'), documented: { response: D.obj({ totalToday: D.num, myToday: D.num, lastHour: D.num, byStaff: z.array(D.obj({ scannedById: D.str, name: D.str, count: D.num })) }) }, v1: t.getScanStats, +}); +v1Route({ + method: 'post', path: '/tickets/send', tag: 'Tickets', summary: 'Send tickets to someone', + description: 'Staff: a registration\'s tickets (or chosen ones) to an email address or phone number.', + access: 'staff', campusScope: 'scopeBody(registrationId, ticketIds)', middleware: [cs.scopeBody([['registrationId', 'registration'], ['ticketIds', 'ticket']])], body: loose, documented: { body: D.obj({ registrationId: D.optStr, ticketIds: D.ids.optional().describe('Or registrationId'), channel: D.channel, overrideEmail: D.optStr.describe('Send here instead'), overridePhone: D.optStr }), response: sent }, v1: t.sendTicketsTo, +}); +v1Route({ + method: 'post', path: '/tickets/generate', tag: 'Tickets', summary: 'Issue a registration\'s tickets', + access: 'supervisor', campusScope: 'scopeBody(registrationId)', middleware: [cs.scopeBody([['registrationId', 'registration']])], body: z.looseObject({ registrationId: id }), documented: { response: D.obj({ message: D.str, tickets: z.array(ticketFull) }) }, v1: t.generateTickets, +}); +v1Route({ + method: 'post', path: '/tickets/email-sent', tag: 'Tickets', summary: 'Mark tickets as emailed', access: 'admin', body: loose, documented: { body: D.obj({ ticketIds: D.ids }), response: D.message }, v1: t.markTicketsAsEmailSent, +}); +v1Route({ + method: 'get', path: '/tickets', tag: 'Tickets', summary: 'Every ticket', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventId', 'page', 'limit'), documented: { response: D.v1Page(ticketFull) }, v1: t.getTickets, +}); +v1Route({ + method: 'get', path: '/tickets/qr/:qrCode', tag: 'Tickets', summary: 'The ticket for a QR code', + description: 'Without checking it in (that\'s POST /checkin/{qrCode}).', + access: 'staff', campusScope: 'scopeEvent(ticketQr)', middleware: [qrScope], params: z.object({ qrCode: z.string().min(1).max(200) }), documented: { response: ticketFull }, v1: t.getTicketByQrCode, +}); +v1Route({ + method: 'get', path: '/events/:id/tickets', tag: 'Tickets', summary: 'An event\'s tickets', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: z.array(ticketFull) }, v1: t.getTicketsByEvent, +}); +v1Route({ + method: 'get', path: '/ticket-transfers/:token', tag: 'Tickets', summary: 'A ticket someone is giving you', + description: 'What the transfer link shows (the token is the credential).', access: 'public', params: tokenParams, documented: { response: D.obj({ status: D.str.describe('pending, accepted, declined, cancelled, expired'), toName: D.str, expiresAt: D.date, fromName: D.str, event: D.event.partial(), option: D.str }) }, v1: t.getTransferOffer, +}); +v1Route({ method: 'post', path: '/ticket-transfers/:token/accept', tag: 'Tickets', summary: 'Accept a ticket', access: 'public', params: tokenParams, body: loose, documented: { response: D.obj({ message: D.str, ticketId: D.str }) }, v1: t.acceptTransferOffer }); +v1Route({ method: 'post', path: '/ticket-transfers/:token/decline', tag: 'Tickets', summary: 'Decline a ticket', access: 'public', params: tokenParams, body: loose, documented: { response: D.message }, v1: t.declineTransferOffer }); +v1Route({ + method: 'get', path: '/tickets/:id', tag: 'Tickets', summary: 'One ticket', access: 'user', campusScope: 'scopeEvent(ticket, owner-ok)', middleware: [ticketOwner], params: idParams, documented: { response: ticketFull }, v1: t.getTicketById, +}); +v1Route({ + method: 'post', path: '/tickets/:id/transfer', tag: 'Tickets', summary: 'Give a ticket to someone', + description: 'Sends them a link to accept it; the ticket is theirs once they do.', + access: 'user', campusScope: 'scopeEvent(ticket, owner-ok)', middleware: [ticketOwner], params: idParams, body: loose, documented: { body: transferInput, response: D.obj({ message: D.str, requestId: D.str, expiresAt: D.date }) }, v1: t.transferTicketHandler, +}); +v1Route({ + method: 'delete', path: '/tickets/:id/transfer', tag: 'Tickets', summary: 'Cancel a ticket transfer', access: 'user', campusScope: 'scopeEvent(ticket, owner-ok)', middleware: [ticketOwner], params: idParams, documented: { response: D.message }, v1: t.cancelTransferHandler, +}); +v1Route({ + method: 'get', path: '/tickets/:id/transfers', tag: 'Tickets', summary: 'A ticket\'s transfers', access: 'user', campusScope: 'scopeEvent(ticket, owner-ok)', middleware: [ticketOwner], params: idParams, documented: { response: z.array(D.obj({ id: D.str, ticketId: D.str, fromUserId: D.optStr, toUserId: D.optStr, createdAt: D.date })) }, v1: t.getTicketTransfers, +}); + +// ─── Scan locks (offline scanning) ─────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/scan-locks', tag: 'Check-in', summary: 'Devices scanning offline for an event', + access: 'staff', campusScope: 'scopeEvent(query.eventId)', middleware: [cs.scopeEvent({ from: (req: any) => req.query.eventId })], query: z.looseObject({ eventId: id }), documented: { response: z.array(lockView) }, v1: locks.listLocks, +}); +v1Route({ + method: 'post', path: '/scan-locks', tag: 'Check-in', summary: 'Take tickets offline on this device', + description: 'Locks the chosen tickets to this device until it syncs or releases them.', + access: 'staff', campusScope: 'scopeEvent(body.eventId)', middleware: [cs.scopeEvent({ from: (req: any) => req.body?.eventId })], status: 201, body: z.looseObject({ eventId: id }), documented: { body: D.obj({ eventId: D.str, sectionId: D.optStr.describe('Just this section (default: the whole event)'), deviceId: D.str, deviceName: D.optStr }), response: lockView }, v1: locks.createLock, +}); +v1Route({ + method: 'get', path: '/scan-locks/reports', tag: 'Check-in', summary: 'Offline sync reports to review', + access: 'supervisor', campusScope: 'scopeEvent(query.eventId)', middleware: [cs.scopeEvent({ from: (req: any) => req.query.eventId })], query: z.looseObject({ eventId: id, unreviewed: z.string().max(10).optional() }), documented: { response: z.array(D.obj({ id: D.str, accepted: D.optNum, duplicates: D.optNum, conflicts: z.unknown().optional(), reviewedAt: D.optDate, createdAt: D.date, scanLock: lockView })) }, v1: locks.listReports, +}); +v1Route({ + method: 'post', path: '/scan-locks/reports/:id/review', tag: 'Check-in', summary: 'Mark a sync report reviewed', + access: 'supervisor', campusScope: 'scopeEvent(syncReport)', middleware: [cs.scopeEvent({ resolve: 'syncReport' })], params: idParams, body: loose, documented: { response: D.obj({ id: D.str, reviewedAt: D.date, reviewedById: D.str }) }, v1: locks.reviewReport, +}); +v1Route({ + method: 'get', path: '/scan-locks/:id/snapshot', tag: 'Check-in', summary: 'The tickets a device took offline', + access: 'staff', campusScope: 'scopeEvent(scanLock)', middleware: [cs.scopeEvent({ resolve: 'scanLock' })], params: idParams, query: filters('deviceId'), documented: { response: D.obj({ lock: lockView, snapshotAt: D.date, session: D.obj({ id: D.str, label: D.str }).nullable(), noSessionToday: D.bool, tickets: z.array(D.obj({ id: D.str, qrCode: D.str, holder: D.str, bookedBy: D.str, option: D.str, variant: D.optStr, quantity: D.num, remaining: D.num, consentStatus: D.str })) }) }, v1: locks.getSnapshot, +}); +v1Route({ + method: 'post', path: '/scan-locks/:id/sync', tag: 'Check-in', summary: 'Upload scans made offline', + access: 'staff', campusScope: 'scopeEvent(scanLock)', middleware: [cs.scopeEvent({ resolve: 'scanLock' })], params: idParams, body: loose, documented: { body: D.obj({ deviceId: D.str, scans: z.array(D.obj({ clientScanId: D.str.describe('The device\'s id for the scan (repeats are ignored)'), qrCode: D.str, qty: D.numeric.optional(), scannedAt: D.optDate, sessionId: D.optStr })).max(2000) }), response: D.obj({ accepted: D.num, duplicates: D.num, conflicts: z.array(D.anyObj).describe('Scans that clashed with online check-ins'), reportId: D.str, released: D.bool }) }, v1: locks.syncLock, +}); +v1Route({ + method: 'post', path: '/scan-locks/:id/force-release', tag: 'Check-in', summary: 'Release a lost device\'s tickets', + access: 'supervisor', campusScope: 'scopeEvent(scanLock)', middleware: [cs.scopeEvent({ resolve: 'scanLock' })], params: idParams, body: loose, documented: { response: D.message }, v1: locks.forceRelease, +}); +v1Route({ + method: 'delete', path: '/scan-locks/:id', tag: 'Check-in', summary: 'Release tickets back online', + access: 'staff', campusScope: 'scopeEvent(scanLock)', middleware: [cs.scopeEvent({ resolve: 'scanLock' })], params: idParams, body: z.looseObject({ deviceId: z.string().max(200).optional() }), documented: { response: D.message }, v1: locks.releaseLock, +}); + +// ─── Attendance and certificates ───────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/certificates/verify/:code', tag: 'Attendance', summary: 'Check a certificate is genuine', + access: 'public', params: z.object({ code: z.string().min(1).max(100) }), documented: { response: D.obj({ valid: D.bool, revoked: D.optBool, name: D.optStr, event: D.optStr, completedOn: D.optDate, issuedAt: D.optDate }) }, v1: att.verifyCertificate, +}); +v1Route({ method: 'get', path: '/me/certificates', tag: 'Me', summary: 'My certificates', access: 'user', documented: { response: z.array(certificate) }, v1: att.myCertificates }); +v1Route({ + method: 'post', path: '/certificates/preview', tag: 'Attendance', summary: 'Preview a certificate template', + access: 'supervisor', campusScope: 'campusIndependent (previews a template from the request body)', middleware: [cs.campusIndependent('previews a certificate template from the request body')], body: loose, file: { contentType: 'application/pdf' }, documented: { body: D.obj({ title: D.optStr.describe('Event title to show'), config: D.obj({ template: D.optStr.describe('classic, modern, elegant, simple'), title: D.optStr, body: D.optStr.describe('{name} and {event} are filled in') }).optional() }) }, v1: att.previewCertificate, +}); +v1Route({ + method: 'get', path: '/certificates/:id/pdf', tag: 'Attendance', summary: 'Download a certificate', + description: 'Its owner, or staff.', access: 'user', params: idParams, file: { contentType: 'application/pdf' }, v1: att.downloadCertificate, +}); +v1Route({ + method: 'post', path: '/certificates/:id/revoke', tag: 'Attendance', summary: 'Withdraw a certificate', + access: 'supervisor', campusScope: 'scopeEvent(certificate)', middleware: [cs.scopeEvent({ resolve: 'certificate' })], params: idParams, body: loose, documented: { response: D.ok }, v1: att.revokeCertificate, +}); +v1Route({ + method: 'get', path: '/events/:id/attendance', tag: 'Attendance', summary: 'An event\'s attendance register', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: D.obj({ event: D.event.partial().extend({ certificatesEnabled: D.optBool, certificateConfig: D.anyObj.nullish() }), columns: z.array(D.obj({ id: D.str.describe('Session id, or `event`'), label: D.str })), rows: z.array(registerRow), totals: z.record(z.string(), z.number()) }) }, v1: att.getRegister, +}); +v1Route({ + method: 'get', path: '/events/:id/attendance/export', tag: 'Attendance', summary: 'The register as a file', + description: '`format=pdf` or `xlsx`.', access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, query: filters('format', 'sessionId'), + file: { contentType: 'application/pdf' }, map: asEvent, v1: att.exportRegister, +}); +v1Route({ + method: 'post', path: '/events/:id/attendance', tag: 'Attendance', summary: 'Mark attendance', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ ticketId: D.str, sessionId: D.str.describe('A session id, or `event` on a single-date event'), present: D.bool }), response: D.ok }, v1: att.markAttendance, +}); +v1Route({ + method: 'post', path: '/events/:id/certificates', tag: 'Attendance', summary: 'Issue certificates', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ ticketId: D.optStr.describe('Just this person (default: everyone who qualifies)') }), response: D.obj({ issued: D.num }) }, v1: att.issueCertificates, +}); +v1Route({ + method: 'post', path: '/events/:id/certificates/send', tag: 'Attendance', summary: 'Send certificates', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ certificateId: D.optStr.describe('Just this one (default: every one not sent yet)') }), response: D.obj({ sent: D.num, skipped: D.num }) }, v1: att.sendCertificatesHandler, +}); +v1Route({ + method: 'get', path: '/events/:id/certificates.pdf', tag: 'Attendance', summary: 'Every certificate for an event, as one PDF', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, file: { contentType: 'application/pdf' }, map: asEvent, v1: att.downloadEventCertificates, +}); + +// ─── Allocations (groups, rooms, teams) ────────────────────────────────────── + +v1Route({ + method: 'get', path: '/me/allocation-groups', tag: 'Allocations', summary: 'Groups I lead', + access: 'staff', campusScope: 'campusIndependent (only the groups the signed-in person leads)', middleware: [cs.campusIndependent('only the groups the signed-in person leads')], documented: { response: D.obj({ medicalShown: D.bool, groups: z.array(D.obj({ id: D.str, name: D.str, capacity: D.optNum, gender: D.optStr, setName: D.str, event: D.eventRef.partial(), members: z.array(member) })) }) }, v1: alloc.getMyGroups, +}); +v1Route({ + method: 'get', path: '/events/:id/allocations', tag: 'Allocations', summary: 'An event\'s allocation board', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: D.obj({ event: D.anyObj, sets: z.array(allocationSet.extend({ groups: z.array(group), assignments: z.array(D.obj({ attendeeId: D.str, groupId: D.str })) })), attendees: z.array(D.obj({ id: D.str, name: D.str, gender: D.optStr, dateOfBirth: D.optDate, registrationId: D.str, bookedBy: D.str })), leaders: z.array(D.userRef), unnamedPlaces: D.num.describe('Places with no name yet') }) }, v1: alloc.getBoard, +}); +v1Route({ + method: 'post', path: '/allocation-sets', tag: 'Allocations', summary: 'Start a set of groups', + access: 'supervisor', campusScope: 'scopeEvent(body.eventId)', middleware: [cs.scopeEvent({ from: (req: any) => req.body?.eventId })], status: 201, body: z.looseObject({ eventId: id }), documented: { body: D.obj({ eventId: D.str, name: D.str.describe('e.g. Cabins, Buses'), showOnTicket: D.optBool }), response: allocationSet }, v1: alloc.createSet, +}); +const setScope = cs.scopeEvent({ resolve: 'allocationSet' }); +const groupScope = cs.scopeEvent({ resolve: 'allocationGroup' }); +v1Route({ method: 'patch', path: '/allocation-sets/:id', tag: 'Allocations', summary: 'Change a set', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, body: loose, documented: { body: D.obj({ name: D.optStr, showOnTicket: D.optBool }), response: allocationSet }, v1: alloc.updateSet }); +v1Route({ method: 'delete', path: '/allocation-sets/:id', tag: 'Allocations', summary: 'Delete a set', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, documented: { response: D.message }, v1: alloc.deleteSet }); +v1Route({ method: 'get', path: '/allocation-sets/:id/lists', tag: 'Allocations', summary: 'A set\'s lists (who is in each group)', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, query: filters('medical'), documented: { response: D.obj({ set: D.obj({ id: D.str, name: D.str }), event: D.anyObj, groups: z.array(D.obj({ id: D.str, name: D.str, capacity: D.optNum, gender: D.optStr, leader: D.optStr, members: z.array(member) })) }) }, v1: alloc.getSetLists }); +v1Route({ method: 'post', path: '/allocation-sets/:id/groups', tag: 'Allocations', summary: 'Add a group', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], status: 201, params: idParams, body: loose, documented: { body: groupInput, response: group }, v1: alloc.createGroup }); +v1Route({ method: 'put', path: '/allocation-sets/:id/assignments', tag: 'Allocations', summary: 'Put people in groups', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, body: loose, documented: { body: D.obj({ attendeeId: D.str, groupId: D.optStr.describe('null takes them out') }), response: D.message }, v1: alloc.assign }); +v1Route({ method: 'delete', path: '/allocation-sets/:id/assignments', tag: 'Allocations', summary: 'Empty every group', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, documented: { response: D.message }, v1: alloc.clearAssignments }); +v1Route({ method: 'post', path: '/allocation-sets/:id/auto', tag: 'Allocations', summary: 'Fill the groups automatically', access: 'supervisor', campusScope: 'scopeEvent(allocationSet)', middleware: [setScope], params: idParams, body: loose, documented: { body: D.obj({ mode: z.enum(['together', 'split']).optional().describe('Keep each booking together, or spread them') }), response: D.obj({ placed: D.num, unplaced: D.num, message: D.str }) }, v1: alloc.autoAssign }); +v1Route({ method: 'patch', path: '/allocation-groups/:id', tag: 'Allocations', summary: 'Change a group', access: 'supervisor', campusScope: 'scopeEvent(allocationGroup)', middleware: [groupScope], params: idParams, body: loose, documented: { body: groupInput, response: group }, v1: alloc.updateGroup }); +v1Route({ method: 'delete', path: '/allocation-groups/:id', tag: 'Allocations', summary: 'Delete a group', access: 'supervisor', campusScope: 'scopeEvent(allocationGroup)', middleware: [groupScope], params: idParams, documented: { response: D.message }, v1: alloc.deleteGroup }); diff --git a/apps/events/backend/src/v2/resources/auth.ts b/apps/events/backend/src/v2/resources/auth.ts new file mode 100644 index 0000000..0c22b4c --- /dev/null +++ b/apps/events/backend/src/v2/resources/auth.ts @@ -0,0 +1,105 @@ +import { z } from 'zod'; +import type { Request } from 'express'; +import { defineRoute } from '../route'; +import { single } from '../paging'; +import { id } from '../schemas'; +import auth from '../../middleware/authMiddleware'; +import { signUp, logIn, verifyLoginCode, type Session } from '../../services/auth'; + +const requestInfo = (req: Request) => { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { ip: getClientIp(req), userAgent: req.headers['user-agent'] }; +}; + +const session = z.object({ + status: z.literal('signed_in'), + token: z.string().describe('Send as `Authorization: Bearer `'), + user: z.object({ id, name: z.string(), email: z.string(), role: z.enum(['admin', 'supervisor', 'staff', 'user']) }), + newsPromptPending: z.boolean().describe('Ask once whether they want News & announcements'), + noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]).describe('A privacy notice they must accept: never accepted (first) or a newer version (updated)'), + deviceToken: z.string().optional().describe('With rememberDevice: send it with the next login to skip the code on this device'), +}); + +const toSession = (s: Session): z.input => ({ + status: 'signed_in', + token: s.token, + user: { id: s.id, name: s.name, email: s.email, role: s.role as 'admin' | 'supervisor' | 'staff' | 'user' }, + newsPromptPending: s.newsPromptPending, + noticePromptPending: s.noticePromptPending, + ...(s.deviceToken ? { deviceToken: s.deviceToken } : {}), +}); + +export const signup = defineRoute({ + method: 'post', + path: '/auth/signup', + tag: 'Accounts', + summary: 'Create an account', + description: 'Signs the new account in straight away. `acceptTerms` must be true (the Terms of Use and Privacy Policy); `newsOptIn` is the unticked "News & announcements" box.', + access: 'public', + status: 201, + body: z.object({ + name: z.string().trim().min(1).max(200), + email: z.email().max(200), + password: z.string().min(8).max(200), + phone: z.string().trim().max(40).optional(), + notificationPreference: z.enum(['email', 'whatsapp', 'both']).optional().describe('WhatsApp needs a valid South African number; otherwise email is used'), + newsOptIn: z.boolean().optional(), + acceptTerms: z.literal(true), + }), + response: single(session), + async handler({ body, req }) { + const made = await signUp({ name: body.name, email: body.email, password: body.password, phoneNumber: body.phone, notificationPreference: body.notificationPreference, newsOptIn: body.newsOptIn }, requestInfo(req)); + return { data: { status: 'signed_in' as const, token: made.token, user: { id: made.id, name: made.name, email: made.email, role: made.role }, newsPromptPending: false, noticePromptPending: false as const } }; + }, +}); + +export const login = defineRoute({ + method: 'post', + path: '/auth/login', + tag: 'Accounts', + summary: 'Log in', + description: [ + 'With an email address or phone number. Five wrong passwords lock the account for five minutes (`RATE_LIMITED`).', + 'With two-factor authentication (always for supervisors and admins), the answer is `code_required`: a code was sent by email or WhatsApp — finish with `POST /auth/login/code`.', + ].join('\n\n'), + access: 'public', + middleware: [auth.loginLimiter], + body: z.object({ + identifier: z.string().trim().min(1).max(200).describe('Email address or phone number'), + password: z.string().min(1).max(200), + deviceToken: z.string().max(500).optional().describe('From an earlier login with rememberDevice'), + }), + response: single(z.discriminatedUnion('status', [ + session, + z.object({ + status: z.literal('code_required'), + challengeId: z.string(), + method: z.enum(['email', 'whatsapp']), + destination: z.string().nullable().describe('Where the code went, partly hidden'), + enrolling: z.boolean().describe('true = this turns two-factor on (required for the role)'), + }), + ])), + async handler({ body, req }) { + const result = await logIn(body, requestInfo(req)); + if (result.status === 'signed_in') return { data: toSession(result.session) }; + return { data: { status: 'code_required' as const, challengeId: result.challenge.challengeId, method: result.challenge.method as 'email' | 'whatsapp', destination: result.challenge.destination ?? null, enrolling: result.enrolling } }; + }, +}); + +export const loginCode = defineRoute({ + method: 'post', + path: '/auth/login/code', + tag: 'Accounts', + summary: 'Finish logging in with the code', + access: 'public', + middleware: [auth.loginLimiter], + body: z.object({ + challengeId: z.string().min(1).max(100), + code: z.string().trim().min(4).max(12), + rememberDevice: z.boolean().optional().describe('Skip the code on this device next time (30 days)'), + }), + response: single(session), + async handler({ body, req }) { + return { data: toSession(await verifyLoginCode(body, requestInfo(req))) }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/checkin.ts b/apps/events/backend/src/v2/resources/checkin.ts new file mode 100644 index 0000000..4f7f551 --- /dev/null +++ b/apps/events/backend/src/v2/resources/checkin.ts @@ -0,0 +1,133 @@ +import { z } from 'zod'; +import type { Request } from 'express'; +import { defineRoute } from '../route'; +import { ApiError } from '../errors'; +import { single } from '../paging'; +import { id } from '../schemas'; +import { previewScan, scanTicket, type ScanTicket } from '../../services/checkin'; + +const OUTCOMES = ['checked_in', 'already_used', 'consent_required', 'wrong_event', 'wrong_section', 'section_not_found', 'no_session', 'locked', 'transferred'] as const; + +const qrParams = z.object({ qrCode: z.string().min(1).max(200).describe('The code in the ticket\'s QR') }); + +/** + * Campus-scoped staff may only check in tickets for their campuses' events (and church-wide + * ones) — the same rule as v1's scopeEvent({ resolve: 'ticketQr', nameCampus: true }). + */ +async function assertTicketCampus(req: Request, qrCode: string) { + const cs = require('../../utils/campusScope') as { + scopeFor(req: unknown): Promise; + eventOf(resolve: string, value: string): Promise<{ campusId: string | null; campusName?: string | null } | null>; + canView(scope: object, campusId: string | null): boolean; + }; + const scope = await cs.scopeFor(req); + if (!scope) return; + const ev = await cs.eventOf('ticketQr', qrCode); + if (ev && !cs.canView(scope, ev.campusId)) throw new ApiError('FORBIDDEN', `This ticket is for an event at ${ev.campusName || 'another campus'}.`); +} + +const ticketInfo = z.object({ + id, + eventId: id, + eventTitle: z.string().nullable(), + ticketName: z.string().nullable().describe('The ticket option, e.g. "Adult"'), + quantity: z.number().int().describe('People on this ticket'), +}); +const toTicketInfo = (t: ScanTicket) => ({ id: t.id, eventId: t.eventId, eventTitle: t.event.title ?? null, ticketName: t.registrationOption.eventOption.name ?? null, quantity: t.quantity }); + +const sessionRef = z.object({ id, label: z.string() }); + +export const preview = defineRoute({ + method: 'get', + path: '/checkin/:qrCode', + tag: 'Check-in', + summary: 'Look a ticket up before checking it in', + description: 'Who it is for, how many are left to check in (for today\'s session on multi-day events, or `sessionId`), and parental consent. Nothing is changed.', + access: 'staff', + campusScope: 'event:ticketQr:view (assertTicketCampus)', + params: qrParams, + query: z.object({ sessionId: id.optional().describe('Multi-day events: the session (default: today\'s)') }), + response: single(z.object({ + outcome: z.enum(['found', 'transferred']), + message: z.string().nullable().describe('For a transferred ticket: who has it now'), + ticket: z.object({ + id, + eventId: id, + eventTitle: z.string().nullable(), + ticketOptionId: id.nullable().describe('For section checks'), + ticketName: z.string().nullable(), + variant: z.string().nullable(), + attendee: z.string().nullable().describe('The attendee named on it, if any'), + bookedBy: z.string().nullable().describe('Who registered'), + quantity: z.number().int(), + remaining: z.number().int().describe('Still to check in (this session, on multi-day events)'), + session: sessionRef.nullable(), + sessionError: z.string().nullable().describe('Why no session is open for check-in now'), + consentStatus: z.string().describe('not_required, given, pending, declined or missing'), + }).nullable(), + })), + async handler({ params, query, req }) { + await assertTicketCampus(req, params.qrCode); + const result = await previewScan(params.qrCode, { sessionId: query.sessionId ?? null }); + if (result.outcome === 'transferred') return { data: { outcome: 'transferred' as const, message: result.message, ticket: null } }; + const t = result.ticket; + return { + data: { + outcome: 'found' as const, + message: null, + ticket: { + id: t.id, eventId: t.eventId, eventTitle: t.event.title ?? null, ticketName: t.registrationOption.eventOption.name ?? null, + ticketOptionId: t.registrationOption.eventOption.id ?? null, variant: t.registrationOption.variant?.name ?? null, + attendee: t.attendee?.name ?? null, bookedBy: t.user.name ?? null, quantity: t.quantity, + remaining: t.remaining, session: t.session, sessionError: t.sessionError, consentStatus: t.consentStatus, + }, + }, + }; + }, +}); + +export const scan = defineRoute({ + method: 'post', + path: '/checkin/:qrCode', + tag: 'Check-in', + summary: 'Check a ticket in', + description: [ + 'Checks in everyone left on the ticket, or `people`. Every normal result is a 200 with an `outcome`:', + '`checked_in`, `already_used`, `consent_required` (a supervisor can resend with `overrideConsent`, which is logged), `wrong_event`, `wrong_section`, `section_not_found`, `no_session` (multi-day: nothing open now), `locked` (offline-locked to another device) or `transferred` (handed on; `message` says to whom).', + 'An unknown code is `NOT_FOUND`.', + ].join('\n\n'), + access: 'staff', + campusScope: 'event:ticketQr:view (assertTicketCampus)', + params: qrParams, + body: z.object({ + eventId: id.optional().describe('Refuse tickets for any other event'), + sectionId: id.optional().describe('Only tickets valid for this section'), + sessionId: id.optional().describe('Multi-day events: the session (default: today\'s)'), + people: z.number().int().min(1).max(10000).optional().describe('How many to check in (default: everyone left)'), + overrideConsent: z.boolean().optional(), + deviceId: z.string().max(200).optional().describe('This scanner, so its own offline lock doesn\'t block it'), + }), + response: single(z.object({ + outcome: z.enum(OUTCOMES), + message: z.string(), + ticket: ticketInfo.nullable(), + checkedIn: z.number().int().describe('People checked in by this request (0 unless checked_in)'), + remaining: z.number().int().nullable().describe('Still to check in afterwards'), + session: sessionRef.nullable(), + consentStatus: z.string().nullable(), + canOverride: z.boolean().describe('consent_required: whether you may override'), + })), + async handler({ params, body, user, req }) { + await assertTicketCampus(req, params.qrCode); + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + const r = await scanTicket(params.qrCode, user!, { + eventId: body.eventId, sectionId: body.sectionId, sessionId: body.sessionId, deviceId: body.deviceId, + qty: body.people ?? null, overrideConsent: body.overrideConsent, + }, getClientIp(req)); + const base = { outcome: r.outcome, message: r.message, ticket: 'ticket' in r ? toTicketInfo(r.ticket) : null, checkedIn: 0, remaining: null as number | null, session: null as { id: string; label: string } | null, consentStatus: null as string | null, canOverride: false }; + if (r.outcome === 'checked_in') return { data: { ...base, checkedIn: r.qtyRedeemed, remaining: r.remaining, session: r.session } }; + if (r.outcome === 'already_used') return { data: { ...base, remaining: 0 } }; + if (r.outcome === 'consent_required') return { data: { ...base, consentStatus: r.consentStatus, canOverride: r.canOverride } }; + return { data: base }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/corrections.ts b/apps/events/backend/src/v2/resources/corrections.ts new file mode 100644 index 0000000..e1be559 --- /dev/null +++ b/apps/events/backend/src/v2/resources/corrections.ts @@ -0,0 +1,114 @@ +/** + * Corrections (1.52.0): see services/corrections.ts. Admins only, except "Fill in later" for + * staff at the door and in Manual registrations. + */ +import { z } from 'zod'; +import type { Request } from 'express'; +import { defineRoute, type ApiUser } from '../route'; +import { single } from '../paging'; +import { id, idParams } from '../schemas'; +import * as corrections from '../../services/corrections'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- campus scope middleware is JavaScript */ +const campusScope = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string }): any; +}; + +const audit = (req: Request, user: ApiUser | null) => { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { actor: { id: user!.id, role: user!.role }, ip: getClientIp(req) }; +}; + +const reason = z.string().trim().max(500).nullish().describe('Why — kept in the audit log'); +const send = z.boolean().optional().describe('Send the new tickets to the attendee (off by default)'); + +const ticketRow = z.object({ + id, + qrCode: z.string(), + label: z.string().describe('Ticket option, variant and (a picked session) the session'), + isMainTicket: z.boolean(), + name: z.string().describe('Who it\'s for'), + quantity: z.number().int(), + sessionIds: z.array(z.string()).describe(`The sessions it covers (\`${corrections.WHOLE_EVENT}\` on a single-date event)`), + checkedIn: z.record(z.string(), z.number().int()).describe('People checked in, per session'), +}); +const registrationRow = z.object({ + id, + status: z.string(), + createdAt: z.coerce.date(), + user: z.object({ id, name: z.string(), email: z.string().nullable(), phoneNumber: z.string().nullable() }), + totalDue: z.number(), + paid: z.number(), + balance: z.number(), + places: z.number().int().describe('Places booked (every line)'), + ticketPlaces: z.number().int().describe('Places with a ticket'), + missingTickets: z.boolean().describe('Paid (or released unpaid) but not every place has a ticket'), + formsNeeded: z.number().int().describe('Attendee forms still holding the tickets back'), + formWaived: z.boolean().describe('The form was left for later'), + ticketsReleased: z.boolean().describe('Tickets issued before it was paid'), + complimentary: z.number().describe('Balance written off'), + tickets: z.array(ticketRow), +}); + +export const eventCorrections = defineRoute({ + method: 'get', path: '/corrections/events/:id', tag: 'Corrections', summary: 'An event\'s registrations, with what needs putting right', + description: 'Every registration that isn\'t cancelled — closed and past events too — with its balance, forms still to fill in, tickets and check-ins.', + access: 'admin', params: idParams, + response: single(z.object({ + event: z.object({ + id, title: z.string(), startDate: z.coerce.date(), endDate: z.coerce.date(), closed: z.boolean(), + formRequired: z.boolean(), sessions: z.array(z.object({ id, label: z.string(), startsAt: z.coerce.date() })), + }), + registrations: z.array(registrationRow), + })), + async handler({ params }) { return { data: await corrections.eventCorrections(params.id) }; }, +}); + +export const issueMissing = defineRoute({ + method: 'post', path: '/corrections/events/:id/issue-missing', tag: 'Corrections', summary: 'Issue every missing ticket at an event', + description: 'For each paid registration (or one released unpaid) without all its tickets. Attendee forms still outstanding are left for later.', + access: 'admin', params: idParams, body: z.object({ send }), + response: single(z.object({ registrations: z.number().int(), tickets: z.number().int(), failed: z.array(z.object({ id, name: z.string(), message: z.string() })) })), + async handler({ params, body, user, req }) { return { data: await corrections.issueMissingTickets(params.id, audit(req, user), body) }; }, +}); + +export const issueTickets = defineRoute({ + method: 'post', path: '/corrections/registrations/:id/tickets', tag: 'Corrections', summary: 'Issue a registration\'s tickets now', + description: '`skipForm` leaves the attendee form for later; `payLater` issues them before it\'s paid (the balance is still owed).', + access: 'admin', params: idParams, + body: z.object({ skipForm: z.boolean().optional(), payLater: z.boolean().optional(), send, reason }), + response: single(z.object({ ticketsIssued: z.number().int(), registration: registrationRow })), + async handler({ params, body, user, req }) { return { data: await corrections.issueTickets(params.id, audit(req, user), body) }; }, +}); + +export const complimentary = defineRoute({ + method: 'post', path: '/corrections/registrations/:id/complimentary', tag: 'Corrections', summary: 'Make it free', + description: 'What\'s still owed is written off as a complimentary discount (income stays what was really paid), it\'s marked paid and its tickets are issued. Not on a closed event.', + access: 'admin', params: idParams, + body: z.object({ skipForm: z.boolean().optional(), send, reason }), + response: single(z.object({ amount: z.number(), ticketsIssued: z.number().int(), registration: registrationRow })), + async handler({ params, body, user, req }) { return { data: await corrections.makeComplimentary(params.id, audit(req, user), body) }; }, +}); + +export const checkIn = defineRoute({ + method: 'post', path: '/corrections/tickets/:id/check-in', tag: 'Corrections', summary: 'Check a ticket in (or undo it) after the fact', + description: 'Any time — after the event or session, or once the event is closed. `present: false` undoes the check-in for that session. Recorded as a manual check-in; no message is sent.', + access: 'admin', params: idParams, + body: z.object({ + sessionId: id.nullish().describe('Multi-day events: the session'), + people: z.number().int().min(1).max(1000).nullish().describe('How many (default: everyone left on the ticket)'), + present: z.boolean().optional().describe('false undoes it'), + reason, + }), + response: single(z.object({ checkedIn: z.number().int(), quantity: z.number().int() })), + async handler({ params, body, user, req }) { return { data: await corrections.correctCheckIn(params.id, audit(req, user), body) }; }, +}); + +export const formLater = defineRoute({ + method: 'post', path: '/registrations/:id/form-later', tag: 'Registrations', summary: 'Fill in the attendee form later', + description: 'At the door: the tickets stop waiting for the required attendee form (issued now if it\'s paid) and the payer is sent a link to fill it in (`notify: false` to not).', + access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, + body: z.object({ notify: z.boolean().optional() }), + response: single(z.object({ ticketsIssued: z.number().int(), sentTo: z.array(z.string()) })), + async handler({ params, body, user, req }) { return { data: await corrections.leaveFormForLater(params.id, audit(req, user), body) }; }, +}); diff --git a/apps/events/backend/src/v2/resources/eventDetails.ts b/apps/events/backend/src/v2/resources/eventDetails.ts new file mode 100644 index 0000000..cb2bf77 --- /dev/null +++ b/apps/events/backend/src/v2/resources/eventDetails.ts @@ -0,0 +1,282 @@ +import { z } from 'zod'; +import type { Request } from 'express'; +import { defineRoute, fileResponse, type ApiUser } from '../route'; +import { ApiError } from '../errors'; +import { single } from '../paging'; +import { absoluteUrl, id, idParams, isoDate } from '../schemas'; +import * as details from '../../services/eventDetails'; +import { managedEvent } from './eventsManage'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */ +const campusScope = require('../../utils/campusScope') as { + scopeFor(req: unknown): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; +}; +// The same multer step as v1 (field "file"; PDFs, Office files, text, CSV, ZIP; 20 MB). +const { receiveAttachment } = require('../../controllers/eventController') as { receiveAttachment: any }; + +const urlOf = (req: Request) => (u: string | null | undefined) => absoluteUrl(req, u); +const plain = (v: T): any => JSON.parse(JSON.stringify(v)); +const viewerOf = async (req: Request, user: ApiUser | null) => ({ staff: !!user && ['admin', 'supervisor', 'staff'].includes(user.role), scope: await campusScope.scopeFor(req) }); + +// ─── The event in full, calendar file, short link ────────────────────────────── + +export const full = defineRoute({ + method: 'get', + path: '/events/:id/full', + tag: 'Events', + summary: 'One event in full', + description: [ + 'What the registration page and the set-up screens need: ticket options with what\'s left (per variant, and per session for "pick sessions" tickets), early-bird tiers, sessions with bookings, the attendee form, attachments, bundle deals on sale and the next event in its series.', + 'Staff (of a campus they work with) also get inactive and not-yet-live events, who created it, who gets its emails, and the kids/volunteer tickets. Everyone else gets NOT_FOUND for events that aren\'t public.', + ].join('\n\n'), + access: 'optional', + params: idParams, + response: single(managedEvent.extend({ + form: z.looseObject({ id, isRequired: z.boolean(), fields: z.array(z.looseObject({ id, type: z.string(), label: z.string() })) }).nullable(), + attachments: z.array(z.looseObject({ id, originalName: z.string(), url: z.string().nullable() })), + })), + async handler({ params, user, req }) { + return { data: plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req))) }; + }, +}); + +export const calendar = defineRoute({ + method: 'get', + path: '/events/:id/calendar.ics', + tag: 'Events', + summary: 'The event as a calendar file', + description: 'An .ics file (each session for a multi-day event). Same visibility as the event.', + access: 'optional', + file: { contentType: 'text/calendar' }, + params: idParams, + response: fileResponse, + async handler({ params, user, req }) { + const { filename, ics } = await details.eventCalendar(params.id, await viewerOf(req, user)); + return { data: { contentType: 'text/calendar; charset=utf-8', filename, body: ics } }; + }, +}); + +export const byAlias = defineRoute({ + method: 'get', + path: '/events/by-alias/:alias', + tag: 'Events', + summary: 'An event by its short link', + description: 'The part after the site address (`/camp2026`), any letter case. Active events only.', + access: 'public', + params: z.object({ alias: z.string().min(1).max(100).describe('The short link, e.g. camp2026') }), + response: single(z.object({ + id, title: z.string(), description: z.string().nullable(), startDate: isoDate, endDate: isoDate, registrationDeadline: isoDate.nullable(), + goLiveAt: isoDate.nullable(), price: z.number(), picture: z.string().nullable(), redirectUrl: z.string().nullable(), + isLive: z.boolean().describe('Not over yet'), + })), + async handler({ params, req }) { + const ev = plain(await details.eventByAlias(params.alias)); + return { data: { ...ev, picture: absoluteUrl(req, ev.picture) } }; + }, +}); + +// ─── Ticket options and variants ───────────────────────────────────────────── + +const variant = z.looseObject({ id, name: z.string(), price: z.number().nullable(), stockLimit: z.number().int(), staffPrice: z.number().nullable(), order: z.number().int() }); +const tier = z.looseObject({ id, deadline: isoDate, price: z.number(), stockLimit: z.number().int(), variantId: id.nullable() }); +const ticketOption = z.looseObject({ + id, eventId: id, name: z.string(), price: z.number(), isMainTicket: z.boolean(), stockLimit: z.number().int(), staffPrice: z.number().nullable(), + sessionMode: z.enum(['all', 'pick']), earlyBirdTiers: z.array(tier).optional(), variants: z.array(variant).optional(), +}); +const money = z.union([z.number(), z.string().max(20)]); +const optionBody = z.object({ + name: z.string().trim().min(1).max(120), + price: money, + isMainTicket: z.boolean().optional(), + stockLimit: z.union([z.number().int().min(0), z.string().max(10)]).optional().describe('0 = no limit'), + staffPrice: money.nullable().optional().describe('What staff pay (empty = the normal price)'), + sessionMode: z.enum(['all', 'pick']).optional().describe('"pick" = buyers choose sessions (multi-day events)'), +}); +const variantBody = z.object({ + name: z.string().trim().min(1).max(120), + price: money.nullable().optional().describe('Empty = the option\'s price'), + stockLimit: z.union([z.number().int().min(0), z.string().max(10)]).optional(), + staffPrice: money.nullable().optional(), + order: z.union([z.number().int(), z.string().max(10)]).optional(), +}); + +export const createOption = defineRoute({ + method: 'post', + path: '/events/:id/ticket-options', + tag: 'Events (staff)', + summary: 'Add a ticket option', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' })], + status: 201, + params: idParams, + body: optionBody, + response: single(ticketOption), + async handler({ params, body }) { + return { data: plain(await details.createOption(params.id, body)) }; + }, +}); + +export const updateOption = defineRoute({ + method: 'patch', + path: '/ticket-options/:id', + tag: 'Events (staff)', + summary: 'Change a ticket option', + description: 'Only what\'s sent changes. `earlyBirdTiers` and `variants`, when sent, are the full lists: kept by id, added without one, and ones left out removed when nothing was bought under them.', + access: 'supervisor', + campusScope: 'scopeEvent(eventOption, manage)', + middleware: [campusScope.scopeEvent({ resolve: 'eventOption', need: 'manage' })], + params: idParams, + body: optionBody.partial().extend({ + earlyBirdTiers: z.array(z.looseObject({ id: id.optional(), deadline: z.string().max(40), price: money, stockLimit: z.union([z.number(), z.string()]).optional(), variantId: id.nullable().optional() })).max(50).optional(), + variants: z.array(variantBody.extend({ id: id.optional() })).max(100).optional(), + }), + response: single(ticketOption), + async handler({ params, body }) { + return { data: plain(await details.updateOption(params.id, body)) }; + }, +}); + +export const deleteOption = defineRoute({ + method: 'delete', + path: '/ticket-options/:id', + tag: 'Events (staff)', + summary: 'Remove a ticket option', + description: 'Admins only. Not one anybody has bought, and never the event\'s only main ticket.', + access: 'admin', + params: idParams, + response: single(z.object({ id, deleted: z.literal(true) })), + async handler({ params }) { + await details.deleteOption(params.id); + return { data: { id: params.id, deleted: true as const } }; + }, +}); + +export const createVariant = defineRoute({ + method: 'post', + path: '/ticket-options/:id/variants', + tag: 'Events (staff)', + summary: 'Add a variant (e.g. a T-shirt size)', + access: 'supervisor', + campusScope: 'scopeEvent(eventOption, manage)', + middleware: [campusScope.scopeEvent({ resolve: 'eventOption', need: 'manage' })], + status: 201, + params: idParams, + body: variantBody, + response: single(variant), + async handler({ params, body }) { + return { data: plain(await details.createVariant(params.id, body)) }; + }, +}); + +export const updateVariant = defineRoute({ + method: 'patch', + path: '/variants/:id', + tag: 'Events (staff)', + summary: 'Change a variant', + access: 'supervisor', + campusScope: 'scopeEvent(optionVariant, manage)', + middleware: [campusScope.scopeEvent({ resolve: 'optionVariant', need: 'manage' })], + params: idParams, + body: variantBody.partial(), + response: single(variant), + async handler({ params, body }) { + return { data: plain(await details.updateVariant(params.id, body)) }; + }, +}); + +export const deleteVariant = defineRoute({ + method: 'delete', + path: '/variants/:id', + tag: 'Events (staff)', + summary: 'Remove a variant', + description: 'Admins only, and not one anybody has bought.', + access: 'admin', + params: idParams, + response: single(z.object({ id, deleted: z.literal(true) })), + async handler({ params }) { + await details.deleteVariant(params.id); + return { data: { id: params.id, deleted: true as const } }; + }, +}); + +// ─── Attachments ───────────────────────────────────────────────────────────── + +const attachment = z.object({ id, eventId: id, originalName: z.string(), filename: z.string(), mimeType: z.string(), size: z.number().int(), url: z.string().nullable(), createdAt: isoDate }); + +export const listAttachments = defineRoute({ + method: 'get', + path: '/events/:id/attachments', + tag: 'Events', + summary: 'An event\'s attachments', + description: 'Files for attendees (programmes, packing lists…), newest first.', + access: 'public', + params: idParams, + response: z.object({ data: z.array(attachment) }), + async handler({ params, req }) { + return { data: plain(await details.listAttachments(params.id, urlOf(req))) }; + }, +}); + +export const uploadAttachment = defineRoute({ + method: 'post', + path: '/events/:id/attachments', + tag: 'Events (staff)', + summary: 'Attach a file to an event', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' }), receiveAttachment], + upload: { field: 'file', description: 'PDF, Word, Excel, PowerPoint, text, CSV or ZIP, up to 20 MB' }, + status: 201, + params: idParams, + response: single(attachment), + async handler({ params, req }) { + const r = req as Request & { multerError?: Error; file?: { originalname: string; filename: string; mimetype: string; size: number } }; + if (r.multerError) throw new ApiError('VALIDATION_FAILED', r.multerError.message, { file: r.multerError.message }); + if (!r.file) throw new ApiError('VALIDATION_FAILED', 'No file uploaded', { file: 'Choose a file' }); + return { data: plain(await details.recordAttachment(params.id, r.file, urlOf(req))) }; + }, +}); + +export const deleteAttachment = defineRoute({ + method: 'delete', + path: '/events/:id/attachments/:attachmentId', + tag: 'Events (staff)', + summary: 'Remove an attachment', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' })], + params: z.object({ id, attachmentId: id }), + response: single(z.object({ id, deleted: z.literal(true) })), + async handler({ params }) { + await details.deleteAttachment(params.id, params.attachmentId); + return { data: { id: params.attachmentId, deleted: true as const } }; + }, +}); + +export const attachmentsStatus = defineRoute({ + method: 'get', + path: '/attachments/status', + tag: 'Admin', + summary: 'Attachments diagnostics', + access: 'admin', + response: single(z.looseObject({ databaseTableQueryable: z.boolean(), probeError: z.string().nullable() })), + async handler() { + return { data: plain(await details.attachmentsStatus()) }; + }, +}); + +export const attachmentsSync = defineRoute({ + method: 'post', + path: '/attachments/sync', + tag: 'Admin', + summary: 'Import attachments from old manifests', + description: 'Attachments recorded in JSON files on disk by very old versions go into the database. `dryRun` only reports; `remove` deletes each manifest once imported.', + access: 'admin', + body: z.object({ dryRun: z.boolean().default(false), remove: z.boolean().default(false) }), + response: single(z.looseObject({ dryRun: z.boolean(), remove: z.boolean() })), + async handler({ body }) { + return { data: plain(await details.syncAttachmentManifests(body)) }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/events.ts b/apps/events/backend/src/v2/resources/events.ts new file mode 100644 index 0000000..4b05c2b --- /dev/null +++ b/apps/events/backend/src/v2/resources/events.ts @@ -0,0 +1,130 @@ +import { z } from 'zod'; +import { defineRoute } from '../route'; +import { notFound } from '../errors'; +import { pageQuery, paged, single, skipTake, pageOf } from '../paging'; +import { absoluteUrl, campusRef, id, idParams, iso, isoDate, seriesRef } from '../schemas'; +import { prisma, campusesEnabled, campusWhere, resolveCampusFilter, publicEventWhere, publicOptions, getEffectiveUnitPrice } from '../legacy'; + +const eventSummary = z.object({ + id, + title: z.string(), + startDate: isoDate, + endDate: isoDate, + location: z.string().nullable(), + price: z.number().describe('The headline price in rand (0 = free)'), + pictureUrl: z.string().nullable(), + requiresRegistration: z.boolean(), + scheduleType: z.enum(['single', 'sessions']), + campus: campusRef.nullable().describe('null = for all campuses (or campuses are off)'), + series: seriesRef.nullable(), +}); + +const ticketOption = z.object({ + id, + name: z.string(), + price: z.number().describe('The normal price in rand'), + currentPrice: z.number().describe('What it costs now (an early-bird price while one runs)'), + isMainTicket: z.boolean(), + sessionMode: z.enum(['all', 'pick']).describe('"pick" = the buyer chooses sessions'), +}); + +const session = z.object({ + id, + label: z.string().nullable(), + startsAt: isoDate, + endsAt: isoDate, + location: z.string().nullable(), + cancelled: z.boolean(), +}); + +const eventDetail = eventSummary.extend({ + description: z.string().nullable(), + registrationDeadline: isoDate.nullable(), + ticketOptions: z.array(ticketOption), + sessions: z.array(session).describe('Multi-day events only; empty otherwise'), +}); + +const SUMMARY_SELECT = { + id: true, title: true, startDate: true, endDate: true, location: true, price: true, picture: true, + requiresRegistration: true, scheduleType: true, + campus: { select: { id: true, name: true, slug: true } }, + series: { select: { id: true, name: true, slug: true } }, +} as const; + +type SummaryRow = { + id: string; title: string; startDate: Date; endDate: Date; location: string | null; price: number; picture: string | null; + requiresRegistration: boolean; scheduleType: 'single' | 'sessions'; + campus: { id: string; name: string; slug: string } | null; series: { id: string; name: string; slug: string } | null; +}; + +const toSummary = (req: Parameters[0], e: SummaryRow): z.input => ({ + id: e.id, title: e.title, startDate: iso(e.startDate), endDate: iso(e.endDate), location: e.location ?? null, + price: e.price, pictureUrl: absoluteUrl(req, e.picture), requiresRegistration: e.requiresRegistration, + scheduleType: e.scheduleType, campus: e.campus ?? null, series: e.series ?? null, +}); + +export const listEvents = defineRoute({ + method: 'get', + path: '/events', + tag: 'Events', + summary: 'Upcoming public events', + description: 'Events anyone can see (active, not hidden, live) that have not ended, soonest first.', + access: 'public', + query: pageQuery.extend({ + q: z.string().trim().max(100).optional().describe('Search the title'), + campus: z.string().max(64).optional().describe("A campus id or slug (its events plus church-wide ones), or 'all' for church-wide events only"), + series: z.string().max(120).optional().describe('A series slug'), + }), + response: paged(eventSummary), + async handler({ query, req }) { + const now = new Date(); + const enabled = await campusesEnabled(); + const and: object[] = [publicEventWhere(now), { endDate: { gte: now } }]; + if (query.campus) and.push(campusWhere(await resolveCampusFilter(query.campus), { enabled, withAllCampuses: true })); + if (query.series) and.push({ series: { slug: query.series } }); + if (query.q) and.push({ title: { contains: query.q, mode: 'insensitive' } }); + const where = { AND: and }; + const [rows, total] = await Promise.all([ + prisma.event.findMany({ where, select: SUMMARY_SELECT, orderBy: [{ startDate: 'asc' }, { id: 'asc' }], ...skipTake(query) }), + prisma.event.count({ where }), + ]); + return pageOf((rows as SummaryRow[]).map(e => toSummary(req, e)), total, query); + }, +}); + +export const getEvent = defineRoute({ + method: 'get', + path: '/events/:id', + tag: 'Events', + summary: 'One public event', + description: 'With its ticket options (internal kids check-in and volunteer tickets left out) and sessions. Hidden events can be fetched by id (they are unlisted, not private).', + access: 'public', + params: idParams, + response: single(eventDetail), + async handler({ params, req }) { + const now = new Date(); + const { isHidden: _hiddenOk, ...visible } = publicEventWhere(now); + const e = await prisma.event.findFirst({ + where: { id: params.id, ...visible }, + select: { + ...SUMMARY_SELECT, description: true, registrationDeadline: true, kidsOptionId: true, volunteerOptionId: true, + eventOptions: { include: { earlyBirdTiers: true }, orderBy: [{ isMainTicket: 'desc' }, { name: 'asc' }] }, + sessions: { orderBy: { startsAt: 'asc' } }, + }, + }); + if (!e) throw notFound('That event'); + const options = publicOptions(e); + return { + data: { + ...toSummary(req, e as unknown as SummaryRow), + description: e.description ?? null, + registrationDeadline: iso(e.registrationDeadline), + ticketOptions: options.map(o => ({ + id: o.id, name: o.name, price: o.price, currentPrice: getEffectiveUnitPrice(o, null, now), + isMainTicket: o.isMainTicket, sessionMode: o.sessionMode, + })), + sessions: e.sessions.map(s => ({ id: s.id, label: s.label, startsAt: iso(s.startsAt), endsAt: iso(s.endsAt), location: s.location, cancelled: !!s.cancelledAt })), + }, + }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/eventsManage.ts b/apps/events/backend/src/v2/resources/eventsManage.ts new file mode 100644 index 0000000..5f045b6 --- /dev/null +++ b/apps/events/backend/src/v2/resources/eventsManage.ts @@ -0,0 +1,192 @@ +import { z } from 'zod'; +import * as D from '../docs'; +import type { Request } from 'express'; +import { defineRoute, type ApiUser } from '../route'; +import { single } from '../paging'; +import { absoluteUrl, id, idParams, isoDate } from '../schemas'; +import { + createEvent, updateEvent, deactivateEvent, listManagedEvents, getNotifyRecipients, setNotifyRecipients, copySetupFrom, +} from '../../services/events'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- event records are passed through as stored */ +const campusScope = require('../../utils/campusScope') as { + scopeFor(req: unknown): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; + scopeBody(targets: [string, string][], opts?: object): any; +}; + +/** + * Staff and supervisor views of events (1.51.7). Event records are large (ticket options with + * tiers and variants, the attendee form, sessions…) and grow with features, so the schema types + * the core fields and lets the rest through as stored (`looseObject`); dates come back as ISO + * strings. Registered before resources/events.ts so /events/manage isn't read as an event id. + */ +const option = z.looseObject({ id, name: z.string(), price: z.number(), isMainTicket: z.boolean(), stockLimit: z.number().int() }); +const session = z.looseObject({ id, label: z.string().nullable(), startsAt: isoDate, endsAt: isoDate, cancelled: z.boolean() }); +export const managedEvent = z.looseObject({ + id, + title: z.string(), + description: z.string().nullable(), + startDate: isoDate, + endDate: isoDate, + isActive: z.boolean(), + isHidden: z.boolean(), + requiresRegistration: z.boolean(), + scheduleType: z.enum(['single', 'sessions']), + attendanceMode: z.enum(['whole', 'pick']), + cashupStatus: z.enum(['open', 'closed']), + campusId: id.nullable(), + seriesId: id.nullable(), + picture: z.string().nullable(), + eventOptions: z.array(option).optional(), + sessions: z.array(session).optional(), +}); + +/** A stored record as JSON (dates → ISO strings), with the picture as an absolute URL. */ +const toJson = (req: Request, ev: any) => { + const plain = JSON.parse(JSON.stringify(ev)); + if ('picture' in plain) plain.picture = absoluteUrl(req, plain.picture); + return plain; +}; + +const ctxOf = async (req: Request) => { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { scope: await campusScope.scopeFor(req), ip: getClientIp(req) }; +}; +const actorOf = (user: ApiUser | null) => ({ id: user!.id, role: user!.role }); + +// The event wizard's fields. Only these are named here; the rest of the wizard's fields (consent, +// waitlist, sponsorship, sessions, late joining, certificates, form…) pass through as sent. +const eventBody = z.looseObject({ + title: z.string().trim().min(1).max(200).optional(), + description: z.string().max(20000).nullable().optional(), + startDate: z.string().max(40).optional(), + endDate: z.string().max(40).optional(), + price: z.union([z.number(), z.string().max(20)]).optional(), + campusId: id.nullable().optional(), + seriesId: id.nullable().optional(), + scheduleType: z.enum(['single', 'sessions']).optional(), + sessions: z.array(z.looseObject({})).max(200).optional(), +}); + +export const listManaged = defineRoute({ + method: 'get', + path: '/events/manage', + tag: 'Events (staff)', + summary: 'Every event staff can see', + description: 'Hidden ones too. Upcoming by default; `past`, `inactive` and `closed` (cashed-up) widen it. Campus-scoped staff see their campuses\' events and church-wide ones. Not paged — it\'s what the event pickers search.', + access: 'staff', + campusScope: 'scopeList (in listManagedEvents)', + query: z.object({ + past: z.enum(['true', 'false']).default('false').transform(v => v === 'true').describe('Include events that have ended'), + inactive: z.enum(['true', 'false']).default('false').transform(v => v === 'true').describe('Include deactivated events'), + closed: z.enum(['true', 'false']).default('true').transform(v => v === 'true').describe('Include cashed-up events (default true)'), + campus: z.string().max(64).optional().describe("A campus id or slug, or 'all' for church-wide events only"), + }), + response: z.object({ data: z.array(managedEvent) }), + async handler({ query, req }) { + const events = await listManagedEvents({ includePast: query.past, includeInactive: query.inactive, excludeClosed: !query.closed, campus: query.campus }, await ctxOf(req)); + return { data: events.map(ev => toJson(req, ev)) }; + }, +}); + +export const create = defineRoute({ + method: 'post', + path: '/events', + tag: 'Events (staff)', + summary: 'Create an event', + description: 'Gets a "Main Ticket" at the event price (unless registration is off). A campus-scoped supervisor must choose one of their campuses.', + access: 'supervisor', + campusScope: 'campus checked in createEvent (assertCampusAllowed)', + status: 201, + body: eventBody.extend({ title: z.string().trim().min(1).max(200), startDate: z.string().max(40), endDate: z.string().max(40) }), + response: single(managedEvent), + async handler({ body, user, req }) { + return { data: toJson(req, await createEvent(body, actorOf(user), await ctxOf(req))) }; + }, +}); + +export const update = defineRoute({ + method: 'patch', + path: '/events/:id', + tag: 'Events (staff)', + summary: 'Change an event', + description: 'Only the fields sent change. Sessions save with the event (a refused schedule change saves nothing). A cashed-up event can\'t change until an admin reopens it. The answer includes `sessionChanges` (added, moved, cancelled… counts) when sessions were sent.', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' })], + params: idParams, + body: eventBody, + response: single(managedEvent.extend({ sessionChanges: z.record(z.string(), z.number()).nullable() })), + async handler({ params, body, user, req }) { + return { data: toJson(req, await updateEvent(params.id, body, actorOf(user), await ctxOf(req))) }; + }, +}); + +export const remove = defineRoute({ + method: 'delete', + path: '/events/:id', + tag: 'Events (staff)', + summary: 'Deactivate an event', + description: 'Admins only. The event is deactivated, not deleted: registrations, payments and tickets stay.', + access: 'admin', + params: idParams, + response: single(z.object({ id, isActive: z.literal(false) })), + async handler({ params, user, req }) { + const ev = await deactivateEvent(params.id, actorOf(user), await ctxOf(req)); + return { data: { id: ev.id, isActive: false as const } }; + }, +}); + +export const copyFrom = defineRoute({ + method: 'post', + path: '/events/:id/copy-from', + tag: 'Events (staff)', + summary: 'Copy set-up from another event', + description: 'Allocation groups, and planned costs for admins — used right after copying an event.', + access: 'supervisor', + campusScope: 'scopeEvent(manage) + scopeBody(fromEventId)', + middleware: [campusScope.scopeEvent({ need: 'manage' }), campusScope.scopeBody([['fromEventId', 'event']])], + params: idParams, + body: z.object({ fromEventId: id }), + documented: { response: D.obj({ sets: D.num.describe('Allocation sets copied'), groups: D.num.describe('Groups copied'), costs: D.num.describe('Costs copied (admins)') }) }, + response: single(z.looseObject({})), + async handler({ params, body, user }) { + return { data: JSON.parse(JSON.stringify(await copySetupFrom(params.id, body.fromEventId, actorOf(user)) ?? {})) }; + }, +}); + +const recipient = z.object({ id, name: z.string(), email: z.string(), role: z.enum(['admin', 'supervisor', 'staff', 'user']) }); + +export const listRecipients = defineRoute({ + method: 'get', + path: '/events/:id/notify-recipients', + tag: 'Events (staff)', + summary: 'Who gets this event\'s emails', + description: 'Registration, payment and daily-summary emails.', + access: 'supervisor', + campusScope: 'scopeEvent(view)', + middleware: [campusScope.scopeEvent()], + params: idParams, + response: z.object({ data: z.array(recipient) }), + async handler({ params }) { + return { data: await getNotifyRecipients(params.id) }; + }, +}); + +export const setRecipients = defineRoute({ + method: 'put', + path: '/events/:id/notify-recipients', + tag: 'Events (staff)', + summary: 'Set who gets this event\'s emails', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' })], + params: idParams, + body: z.object({ userIds: z.array(id).max(200) }), + response: z.object({ data: z.array(recipient) }), + async handler({ params, body }) { + return { data: await setNotifyRecipients(params.id, body.userIds) }; + }, +}); + diff --git a/apps/events/backend/src/v2/resources/feedback.ts b/apps/events/backend/src/v2/resources/feedback.ts new file mode 100644 index 0000000..1aa2af3 --- /dev/null +++ b/apps/events/backend/src/v2/resources/feedback.ts @@ -0,0 +1,85 @@ +/** + * The Feedback page (2.1.0): see services/feedback.ts. Supervisors and admins; campus-scoped + * supervisors see their campuses' events. Setting a form up, "Send now" and the summary report + * stay in money.ts. + */ +import { z } from 'zod'; +import { defineRoute } from '../route'; +import { single } from '../paging'; +import { id, idParams } from '../schemas'; +import * as feedback from '../../services/feedback'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- campus scope and the access log are JavaScript */ +const cs = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage' }): any; + scopeList: any; + listWhere(req: unknown, path?: string): Promise; +}; +const { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; what?: string; eventId?: string; records?: number }): Promise }; + +const event = z.object({ id, title: z.string(), startDate: z.coerce.date(), endDate: z.coerce.date() }); +const status = z.enum(['sent', 'scheduled', 'not_scheduled']).describe('sent, scheduled (a send time is set) or not_scheduled'); +const when = z.coerce.date().nullable(); +const count = z.object({ label: z.string(), value: z.number().int() }); + +export const overview = defineRoute({ + method: 'get', path: '/feedback', tag: 'Feedback', summary: 'Every event with a feedback form', + description: 'Newest event first, with how many were asked and answered, and the average star rating.', + access: 'supervisor', campusScope: 'scopeList (the handler filters by listWhere)', middleware: [cs.scopeList], + response: single(z.array(z.object({ + event, status, sendAt: when, sentAt: when, anonymous: z.boolean(), + invited: z.number().int(), answered: z.number().int(), responseRate: z.number().nullable().describe('%'), + averageRating: z.number().nullable().describe('Every star rating on the form, 1–5'), lastReminderAt: when, + }))), + async handler({ req }) { return { data: await feedback.feedbackOverview(await cs.listWhere(req, 'event')) }; }, +}); + +export const results = defineRoute({ + method: 'get', path: '/events/:id/feedback/results', tag: 'Feedback', summary: 'An event\'s feedback: results, responses and who was asked', + description: 'On an anonymous form, responses have no name and `people` is null. Opening a named form\'s answers is recorded in the access log.', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, + response: single(z.object({ + event, + form: z.object({ + status, sendAt: when, sentAt: when, audience: z.enum(['checked_in', 'all']), anonymous: z.boolean(), intro: z.string().nullable(), + autoReminderAt: when.describe('When the automatic reminder goes (3 days after sending)'), autoReminderSent: z.boolean(), + }), + counts: z.object({ + invited: z.number().int(), answered: z.number().int(), notAnswered: z.number().int(), responseRate: z.number().nullable(), + canRemind: z.number().int().describe('Not answered, and not sent the form or a reminder in the last 24 hours'), + remindedRecently: z.number().int(), + waiting: z.number().int().describe('Would get the form but haven\'t been sent it yet (e.g. checked in after it went out)'), + }), + averageRating: z.number().nullable(), + questions: z.array(z.object({ + fieldId: id, type: z.string(), label: z.string(), answered: z.number().int(), + average: z.number().nullable().optional(), distribution: z.array(count).optional(), counts: z.array(count).optional(), + texts: z.array(z.object({ value: z.string(), name: z.string().optional() })).optional(), + })), + fields: z.array(z.object({ id, type: z.string(), label: z.string() })), + responses: z.array(z.object({ id, createdAt: z.coerce.date(), name: z.string().nullable(), answers: z.record(z.string(), z.string()).describe('Question id → answer') })), + people: z.array(z.object({ + userId: id, name: z.string(), email: z.string().nullable(), phoneNumber: z.string().nullable(), + sentAt: z.coerce.date(), remindedAt: when, reminderCount: z.number().int(), respondedAt: when, canRemind: z.boolean(), + })).nullable(), + })), + async handler({ params, req }) { + const data = await feedback.eventFeedback(params.id); + if (!data.form.anonymous && data.responses.length) { + await logDataAccess(req, { action: 'feedback_responses', what: `Feedback answers: ${data.event.title}`, eventId: data.event.id, records: data.responses.length }); + } + return { data }; + }, +}); + +export const remind = defineRoute({ + method: 'post', path: '/events/:id/feedback/remind', tag: 'Feedback', summary: 'Remind people who haven\'t answered', + description: 'A fresh link to everyone who hasn\'t answered, or to `userIds` (named forms only). Nobody is sent the form or a reminder twice within 24 hours. Without `userIds` it also sends the form to anyone who has become eligible since it went out. Answers straight away; the emails go out in the background.', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, + body: z.object({ userIds: z.array(id).max(1000).nullish().describe('Only these people (named forms)') }), + response: single(z.object({ reminded: z.number().int().describe('Being reminded'), newlyInvited: z.number().int().describe('Being sent the form for the first time'), skipped: z.number().int(), queued: z.boolean().describe('Emails are going out in the background'), message: z.string() })), + async handler({ params, body }) { + const { title: _title, ...data } = await feedback.remindFeedback(params.id, { userIds: body.userIds }); + return { data }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/kidsVolunteers.ts b/apps/events/backend/src/v2/resources/kidsVolunteers.ts new file mode 100644 index 0000000..e54953f --- /dev/null +++ b/apps/events/backend/src/v2/resources/kidsVolunteers.ts @@ -0,0 +1,141 @@ +/** + * Kids check-in and volunteer rosters on v2 (1.51.13). Each route runs the v1 handler + * (viaV1.ts) behind the same access and campus checks as v1. + */ +import { z } from 'zod'; +import { id, idParams } from '../schemas'; +import { v1Route } from '../viaV1'; +import * as D from '../docs'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- v1 handlers and middleware are JavaScript */ +const cs = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; + scopeList: any; +}; +const kids = require('../../controllers/kidsController'); +const vol = require('../../controllers/volunteerController'); + +const loose = z.looseObject({}); +const filters = (...names: string[]) => z.looseObject(Object.fromEntries(names.map(n => [n, z.string().max(4000).optional()]))); +/** v2 `:id` is the event; v1 called it `:eventId` (other params keep their names). */ +const asEvent = (ctx: any) => ({ params: { ...ctx.req.params, eventId: ctx.params.id } }); +const SCOPE_LIST = 'scopeList (the handler filters by listWhere)'; +const view = { campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()] }; +const manage = { campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })] }; + +// ─── Documented shapes (docs.ts) ───────────────────────────────────────────── + +const child = D.obj({ + id: D.str, firstName: D.str, lastName: D.str, name: D.str, dateOfBirth: D.optDate, age: D.optNum, gender: D.optStr, + allergies: D.optStr, hasMedical: D.bool, hasCustody: D.bool.describe('There are custody notes'), + medicalNotes: D.optStr.describe('Only where notes may be shown'), custodyNotes: D.optStr, lastCheckInAt: D.optDate, +}); +const childInput = D.obj({ + firstName: D.str, lastName: D.optStr, dateOfBirth: D.optDate, gender: D.optStr.describe('male or female (anything else: not given)'), + allergies: D.optStr, medicalNotes: D.optStr, custodyNotes: D.optStr.describe('Kept encrypted, like the medical notes'), +}); +const adultInput = D.obj({ name: D.str, phone: D.optStr, relationship: D.optStr }); +const adult = adultInput.extend({ id: D.str }); +const family = D.obj({ + id: D.str, name: D.str, + parents: z.array(D.obj({ userId: D.str, name: D.str, phone: D.optStr, email: D.optStr })), + children: z.array(child), adults: z.array(adult).describe('Others who may collect the children'), +}); +const myFamily = D.obj({ + family: family.nullable(), qrToken: D.optStr.describe('The family QR code (shown at the desk)'), + codes: z.array(D.anyObj).describe('Collection codes for children checked in now'), pages: z.array(D.anyObj).describe('Recent "come to the room" messages'), +}); +const parentInput = D.obj({ name: D.str, email: D.optStr, phone: D.optStr.describe('Email or phone needed: the collection code is sent there') }); +const room = D.obj({ id: D.str, name: D.str, minAge: D.optNum, maxAge: D.optNum, capacity: D.optNum, ratio: D.optNum, order: D.optNum, leaderNames: z.array(D.str).optional(), leaderIds: D.ids.optional() }); +const board = D.obj({ + event: D.anyObj, occasion: D.str.describe('The day or session it\'s for'), sessionId: D.optStr, sessionLabel: D.optStr, + rooms: z.array(room), checkIns: z.array(D.anyObj).describe('Children checked in, with room and code'), +}); +const roleShift = D.obj({ startsAt: D.date, endsAt: D.date, text: D.str, hours: D.num }); +const role = D.obj({ + id: D.str, eventId: D.str, sessionId: D.optStr, sessionLabel: D.optStr, name: D.str, description: D.str, + startsAt: D.optDate, endsAt: D.optDate, shift: roleShift, kidsRoom: D.anyObj.nullish(), order: D.num, past: D.bool, + needed: D.optNum, filled: D.optNum, + mine: D.obj({ slotId: D.str, checkedInAt: D.optDate, swapId: D.optStr }).nullable().describe('My place in it'), + coverNeeded: z.array(D.obj({ swapId: D.str, note: D.str })), + volunteers: z.array(D.obj({ slotId: D.str, userId: D.str, name: D.str, phone: D.optStr, email: D.optStr, assignedBy: D.optStr, checkedInAt: D.optDate, checkedInBy: D.optStr, checkInMethod: D.optStr, swapOpen: D.bool, hasTicket: D.bool })).optional().describe('Staff only'), +}); +const roster = D.obj({ + event: D.anyObj, sessions: z.array(D.obj({ id: D.str, label: D.str, startsAt: D.date, endsAt: D.date })), roles: z.array(role), + totals: D.obj({ needed: D.optNum, filled: D.optNum, fillRate: D.optNum.describe('%') }), +}); +const roleInput = D.obj({ + name: D.str, description: D.optStr, sessionId: D.optStr.describe('A multi-day event: the session'), startsAt: D.optDate, endsAt: D.optDate.describe('Default: the event\'s or session\'s times'), + needed: D.numeric.nullish().describe('How many people'), kidsRoomId: D.optStr.describe('Serving in a kids room: counts as a leader on duty'), order: D.numeric.optional(), +}); +const roleRecord = D.obj({ id: D.str, eventId: D.str, name: D.str, description: D.optStr, sessionId: D.optStr, startsAt: D.optDate, endsAt: D.optDate, needed: D.optNum, kidsRoomId: D.optStr, order: D.num }); +const signedUp = D.obj({ slotId: D.str, ticket: D.bool.describe('A free volunteer ticket was issued') }); + +// ─── Kids: my family ───────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/me/family', tag: 'Kids', summary: 'My family', description: 'Children, the adults who may collect them, and the family QR code.', access: 'user', documented: { response: myFamily }, v1: kids.getMine }); +v1Route({ method: 'post', path: '/me/family', tag: 'Kids', summary: 'Start my family', access: 'user', status: 201, body: loose, documented: { body: D.obj({ name: D.optStr }), response: myFamily }, v1: kids.createMine }); +v1Route({ method: 'patch', path: '/me/family', tag: 'Kids', summary: 'Rename my family', access: 'user', body: loose, documented: { body: D.obj({ name: D.str }), response: family }, v1: kids.renameMine }); +v1Route({ method: 'delete', path: '/me/family', tag: 'Kids', summary: 'Leave my family', access: 'user', documented: { response: D.anyObj.describe('What happened: left, or the family was deleted as the last parent') }, v1: kids.leaveMine }); +v1Route({ method: 'post', path: '/me/family/children', tag: 'Kids', summary: 'Add a child', access: 'user', status: 201, body: loose, documented: { body: childInput, response: child }, v1: kids.saveMyChild }); +v1Route({ method: 'put', path: '/me/family/children/:id', tag: 'Kids', summary: 'Change a child', access: 'user', params: idParams, body: loose, documented: { body: childInput.partial(), response: child }, v1: kids.saveMyChild }); +v1Route({ method: 'delete', path: '/me/family/children/:id', tag: 'Kids', summary: 'Remove a child', access: 'user', params: idParams, documented: { response: D.message }, v1: kids.deleteMyChild }); +v1Route({ method: 'post', path: '/me/family/adults', tag: 'Kids', summary: 'Add an adult who may collect', access: 'user', status: 201, body: loose, documented: { body: adultInput, response: adult }, v1: kids.saveMyAdult }); +v1Route({ method: 'put', path: '/me/family/adults/:id', tag: 'Kids', summary: 'Change an adult', access: 'user', params: idParams, body: loose, documented: { body: adultInput, response: adult }, v1: kids.saveMyAdult }); +v1Route({ method: 'delete', path: '/me/family/adults/:id', tag: 'Kids', summary: 'Remove an adult', access: 'user', params: idParams, documented: { response: D.message }, v1: kids.deleteMyAdult }); + +// ─── Kids: set-up and the check-in desk ────────────────────────────────────── + +v1Route({ method: 'get', path: '/kids/setup-events', tag: 'Kids', summary: 'Events that can have kids check-in', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], documented: { response: z.array(D.event.partial().extend({ kidsCheckIn: D.optBool })) }, v1: kids.setupEvents }); +v1Route({ method: 'get', path: '/kids/events', tag: 'Kids', summary: 'Events with kids check-in', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], documented: { response: z.array(D.event.partial()) }, v1: kids.listEvents }); +v1Route({ method: 'get', path: '/events/:id/kids/settings', tag: 'Kids', summary: 'An event\'s kids check-in set-up', access: 'supervisor', ...view, params: idParams, map: asEvent, documented: { response: D.obj({ event: D.obj({ id: D.str, title: D.str, scheduleType: D.optStr, kidsCheckIn: D.bool, kidsOptionId: D.optStr, kidsRoomSetId: D.optStr }), options: z.array(D.eventOption.partial()), sets: z.array(D.anyObj).describe('Allocation sets that can be the rooms') }) }, v1: kids.getSettings }); +v1Route({ method: 'put', path: '/events/:id/kids/settings', tag: 'Kids', summary: 'Set up kids check-in', access: 'supervisor', ...manage, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ enabled: D.optBool, optionId: D.optStr.describe('The kids ticket (`new` makes a free one; null: none)'), roomSetId: D.optStr.describe('The allocation set used as rooms') }).describe('Only what changes'), response: D.anyObj.describe('The saved set-up, as GET answers') }, v1: kids.saveSettings }); +v1Route({ method: 'get', path: '/events/:id/kids/board', tag: 'Kids', summary: 'Who is checked in, by room', access: 'staff', ...view, params: idParams, query: filters('sessionId', 'log'), map: asEvent, documented: { response: board }, v1: kids.getBoard }); +v1Route({ method: 'get', path: '/events/:id/kids/families', tag: 'Kids', summary: 'Find a family', access: 'staff', ...view, params: idParams, query: filters('q', 'sessionId'), map: asEvent, documented: { response: z.array(family) }, v1: kids.searchFamilies }); +v1Route({ method: 'post', path: '/events/:id/kids/families', tag: 'Kids', summary: 'Register a family at the desk', access: 'staff', ...view, status: 201, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ name: D.optStr, parent: parentInput, children: z.array(childInput).max(12).optional() }), response: family }, v1: kids.createFamilyAtDesk }); +v1Route({ method: 'get', path: '/events/:id/kids/families/qr/:token', tag: 'Kids', summary: 'The family for a QR code', access: 'staff', ...view, params: z.object({ id, token: z.string().min(1).max(200) }), map: asEvent, documented: { response: family }, v1: kids.familyByQr }); +const familyParams = z.object({ id, familyId: id }); +v1Route({ method: 'get', path: '/events/:id/kids/families/:familyId', tag: 'Kids', summary: 'One family', access: 'staff', ...view, params: familyParams, map: asEvent, documented: { response: family }, v1: kids.getFamily }); +v1Route({ method: 'post', path: '/events/:id/kids/families/:familyId/parents', tag: 'Kids', summary: 'Add a parent at the desk', access: 'staff', ...view, status: 201, params: familyParams, body: loose, map: asEvent, documented: { body: parentInput, response: family }, v1: kids.addParentAtDesk }); +v1Route({ method: 'post', path: '/events/:id/kids/families/:familyId/children', tag: 'Kids', summary: 'Add a child at the desk', access: 'staff', ...view, status: 201, params: familyParams, body: loose, map: asEvent, documented: { body: childInput, response: child }, v1: kids.saveChildAtDesk }); +v1Route({ method: 'put', path: '/events/:id/kids/families/:familyId/children/:childId', tag: 'Kids', summary: 'Change a child at the desk', access: 'staff', ...view, params: z.object({ id, familyId: id, childId: id }), body: loose, map: asEvent, documented: { body: childInput.partial(), response: child }, v1: kids.saveChildAtDesk }); +v1Route({ method: 'post', path: '/events/:id/kids/families/:familyId/adults', tag: 'Kids', summary: 'Add an adult at the desk', access: 'staff', ...view, status: 201, params: familyParams, body: loose, map: asEvent, documented: { body: adultInput, response: family }, v1: kids.addAdultAtDesk }); +v1Route({ method: 'post', path: '/events/:id/kids/check-in', tag: 'Kids', summary: 'Check children in', description: 'Answers the collection code and labels to print.', access: 'staff', ...view, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ familyId: D.str, sessionId: D.optStr, children: z.array(D.obj({ childId: D.str, roomId: D.optStr })).describe('Who, and into which room (default: by age)'), sendToAdultId: D.optStr.describe('Send the code to this adult too') }), response: D.obj({ code: D.str.describe('The collection code'), qr: D.str, occasion: D.str, family: D.obj({ id: D.str, name: D.str }), checkIns: z.array(D.obj({ id: D.str, name: D.str, firstName: D.str, room: D.anyObj.nullish(), already: D.bool, sticker: D.optStr.describe('Write this on the sticker') })) }) }, v1: kids.checkIn }); +v1Route({ method: 'post', path: '/events/:id/kids/check-out', tag: 'Kids', summary: 'Check children out', description: 'With the collection code; refused for someone not allowed to collect.', access: 'staff', ...view, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ code: D.str, checkInIds: D.ids.optional().describe('Just these children (default: all on the code)'), collectedBy: D.optStr.describe('Who collected them'), roomId: D.optStr, sessionId: D.optStr }), response: D.obj({ checkedOut: z.array(D.obj({ id: D.str, name: D.str, room: D.optStr })) }) }, v1: kids.checkOut }); +v1Route({ method: 'get', path: '/events/:id/kids/code/:code', tag: 'Kids', summary: 'Who a collection code is for', access: 'staff', ...view, params: z.object({ id, code: z.string().min(1).max(40) }), query: filters('sessionId'), map: asEvent, documented: { response: D.obj({ code: D.str, found: D.bool, family: D.anyObj.nullish(), children: z.array(D.obj({ id: D.str, name: D.str, room: D.anyObj.nullish(), checkedOutAt: D.optDate, collectedBy: D.optStr })) }) }, v1: kids.lookupCode }); +v1Route({ method: 'post', path: '/events/:id/kids/duty', tag: 'Kids', summary: 'Say which room I\'m on', access: 'staff', ...view, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ roomId: D.str, sessionId: D.optStr, on: D.optBool.describe('false: off duty') }), response: D.obj({ roomId: D.str, on: D.bool }) }, v1: kids.setDuty }); +v1Route({ method: 'get', path: '/events/:id/kids/offline', tag: 'Kids', summary: 'Everything the desk needs offline', access: 'staff', ...view, params: idParams, query: filters('deviceId', 'sessionId'), map: asEvent, documented: { response: board.extend({ families: z.array(family), codes: z.array(D.anyObj).describe('Codes reserved for this device'), downloadedAt: D.date }) }, v1: kids.offlineSnapshot }); +v1Route({ method: 'post', path: '/events/:id/kids/sync', tag: 'Kids', summary: 'Upload check-ins made offline', access: 'staff', ...view, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ deviceId: D.str, sessionId: D.optStr, checkIns: z.array(D.anyObj).optional(), checkOuts: z.array(D.anyObj).optional() }), response: D.obj({ checkedIn: D.num, checkedOut: D.num, conflicts: z.array(D.anyObj) }) }, v1: kids.syncOffline }); +const checkInScope = { campusScope: 'scopeEvent(kidsCheckIn)', middleware: [cs.scopeEvent({ resolve: 'kidsCheckIn' })] }; +v1Route({ method: 'post', path: '/kids/check-ins/:id/override', tag: 'Kids', summary: 'Let someone not on the list collect', description: 'Logged, with the reason.', access: 'staff', ...checkInScope, params: idParams, body: loose, documented: { body: D.obj({ reason: D.str, collectedBy: D.str }), response: D.obj({ id: D.str, checkedOutAt: D.date }) }, v1: kids.overrideCheckOut }); +v1Route({ method: 'post', path: '/kids/check-ins/:id/page', tag: 'Kids', summary: 'Page a child\'s parent', access: 'staff', ...checkInScope, params: idParams, body: loose, documented: { body: D.obj({ message: D.optStr }), response: D.obj({ sent: z.array(D.str).describe('Channels used'), text: D.str }) }, v1: kids.pageParent }); +v1Route({ method: 'put', path: '/kids/check-ins/:id/room', tag: 'Kids', summary: 'Move a child to another room', access: 'staff', ...checkInScope, params: idParams, body: loose, documented: { body: D.obj({ roomId: D.str }), response: D.obj({ id: D.str, roomId: D.str }) }, v1: kids.moveRoom }); +v1Route({ method: 'post', path: '/kids/alerts/:id/resolve', tag: 'Kids', summary: 'Resolve an alert', access: 'staff', campusScope: 'scopeEvent(kidsAlert)', middleware: [cs.scopeEvent({ resolve: 'kidsAlert' })], params: idParams, body: loose, documented: { response: D.obj({ resolved: D.num }) }, v1: kids.resolveAlert }); + +// ─── Volunteering: mine ────────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/me/volunteering', tag: 'Volunteers', summary: 'Where I\'m serving', access: 'user', documented: { response: D.obj({ slots: z.array(D.obj({ slotId: D.str, role: D.anyObj, event: D.anyObj, shift: roleShift, checkedInAt: D.optDate, canCheckIn: D.bool, past: D.bool, swapId: D.optStr, hasTicket: D.bool })), cover: z.array(D.anyObj).describe('Slots others want covered'), events: z.array(D.obj({ id: D.str, title: D.str, startDate: D.date, endDate: D.date, location: D.optStr, roles: D.num })) }) }, v1: vol.getMine }); +v1Route({ method: 'get', path: '/events/:id/volunteer-roles', tag: 'Volunteers', summary: 'Roles I can serve in at an event', access: 'user', params: idParams, map: asEvent, documented: { response: roster }, v1: vol.getEventRoles }); +v1Route({ method: 'post', path: '/volunteer-roles/:id/sign-up', tag: 'Volunteers', summary: 'Sign up to serve', access: 'user', status: 201, params: idParams, body: loose, documented: { response: signedUp }, v1: vol.signUp }); +v1Route({ method: 'delete', path: '/volunteer-slots/:id', tag: 'Volunteers', summary: 'Stop serving in a slot', access: 'user', params: idParams, documented: { response: D.message }, v1: vol.withdraw }); +v1Route({ method: 'post', path: '/volunteer-slots/:id/swap', tag: 'Volunteers', summary: 'Ask someone to take my slot', access: 'user', params: idParams, body: loose, documented: { body: D.obj({ note: D.optStr }), response: D.obj({ swapId: D.str }) }, v1: vol.requestSwap }); +v1Route({ method: 'delete', path: '/volunteer-swaps/:id', tag: 'Volunteers', summary: 'Cancel a swap request', access: 'user', params: idParams, documented: { response: D.obj({ cancelled: z.literal(true) }) }, v1: vol.cancelSwap }); +v1Route({ method: 'post', path: '/volunteer-swaps/:id/accept', tag: 'Volunteers', summary: 'Take someone\'s slot', access: 'user', params: idParams, body: loose, documented: { response: D.obj({ slotId: D.str, role: D.str, event: D.str }) }, v1: vol.acceptSwap }); +v1Route({ method: 'post', path: '/volunteering/check-in', tag: 'Volunteers', summary: 'Check myself in (the event\'s QR code)', access: 'user', body: loose, documented: { body: D.obj({ qr: D.str.describe('What the QR code holds') }), response: D.obj({ event: D.obj({ id: D.str, title: D.str }), checkedIn: z.array(D.obj({ role: D.str, kidsRoom: D.optStr })), already: z.array(D.str) }) }, v1: vol.checkIn }); + +// ─── Volunteering: rosters ─────────────────────────────────────────────────── + +v1Route({ method: 'get', path: '/volunteering/events', tag: 'Volunteers', summary: 'Events with volunteer roles', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('all'), documented: { response: z.array(D.obj({ id: D.str, title: D.str, startDate: D.date, endDate: D.date, scheduleType: D.optStr, campusId: D.optStr, roles: D.num })) }, v1: vol.listEvents }); +v1Route({ method: 'get', path: '/volunteering/hours', tag: 'Volunteers', summary: 'Hours served', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('from', 'to', 'eventId'), documented: { response: z.array(D.obj({ userId: D.str.optional(), name: D.str, hours: D.num, shifts: D.optNum })) }, v1: vol.hours }); +v1Route({ method: 'get', path: '/events/:id/volunteers', tag: 'Volunteers', summary: 'An event\'s roster', access: 'staff', ...view, params: idParams, query: filters('log'), map: asEvent, documented: { response: roster }, v1: vol.getRoster }); +v1Route({ method: 'get', path: '/events/:id/volunteers/qr', tag: 'Volunteers', summary: 'The self check-in QR code', access: 'staff', ...view, params: idParams, map: asEvent, documented: { response: D.obj({ token: D.str, qr: D.str.describe('Put this in the QR code') }) }, v1: vol.getQr }); +v1Route({ method: 'get', path: '/events/:id/volunteers/settings', tag: 'Volunteers', summary: 'Volunteer set-up', access: 'supervisor', ...view, params: idParams, map: asEvent, documented: { response: D.obj({ event: D.obj({ id: D.str, title: D.str, volunteerOptionId: D.optStr }), options: z.array(D.eventOption.partial()), kidsRooms: z.array(D.anyObj) }) }, v1: vol.getSettings }); +v1Route({ method: 'put', path: '/events/:id/volunteers/settings', tag: 'Volunteers', summary: 'Set up volunteering', access: 'supervisor', ...manage, params: idParams, body: loose, map: asEvent, documented: { body: D.obj({ optionId: D.optStr.describe('The free volunteer ticket (null: none)') }), response: D.anyObj.describe('The saved set-up, as GET answers') }, v1: vol.saveSettings }); +v1Route({ method: 'post', path: '/events/:id/volunteer-roles', tag: 'Volunteers', summary: 'Add a role', access: 'supervisor', ...manage, status: 201, params: idParams, body: loose, map: asEvent, documented: { body: roleInput, response: roleRecord }, v1: vol.createRole }); +const roleManage = { campusScope: 'scopeEvent(servingRole, manage)', middleware: [cs.scopeEvent({ resolve: 'servingRole', need: 'manage' })] }; +v1Route({ method: 'patch', path: '/volunteer-roles/:id', tag: 'Volunteers', summary: 'Change a role', access: 'supervisor', ...roleManage, params: idParams, body: loose, documented: { body: roleInput.partial(), response: roleRecord }, v1: vol.updateRole }); +v1Route({ method: 'delete', path: '/volunteer-roles/:id', tag: 'Volunteers', summary: 'Delete a role', access: 'supervisor', ...roleManage, params: idParams, documented: { response: D.obj({ message: D.str, volunteers: D.num.describe('People who were in it (told by message)') }) }, v1: vol.deleteRole }); +v1Route({ method: 'post', path: '/volunteer-roles/:id/assign', tag: 'Volunteers', summary: 'Put someone in a role', access: 'supervisor', campusScope: 'scopeEvent(servingRole)', middleware: [cs.scopeEvent({ resolve: 'servingRole' })], params: idParams, body: loose, documented: { body: D.obj({ userId: D.str }), response: signedUp }, v1: vol.assign }); +const slotScope = { campusScope: 'scopeEvent(volunteerSlot)', middleware: [cs.scopeEvent({ resolve: 'volunteerSlot' })] }; +v1Route({ method: 'post', path: '/volunteer-slots/:id/check-in', tag: 'Volunteers', summary: 'Check a volunteer in', access: 'staff', ...slotScope, params: idParams, body: loose, documented: { body: D.obj({ undo: D.optBool }), response: D.obj({ slotId: D.str, changed: D.bool }) }, v1: vol.checkInManual }); +v1Route({ method: 'post', path: '/volunteer-slots/:id/remove', tag: 'Volunteers', summary: 'Take someone off a slot', access: 'supervisor', ...slotScope, params: idParams, body: loose, documented: { response: D.message }, v1: vol.remove }); diff --git a/apps/events/backend/src/v2/resources/me.ts b/apps/events/backend/src/v2/resources/me.ts new file mode 100644 index 0000000..9b98a2f --- /dev/null +++ b/apps/events/backend/src/v2/resources/me.ts @@ -0,0 +1,111 @@ +import { z } from 'zod'; +import { defineRoute } from '../route'; +import { ApiError } from '../errors'; +import { pageQuery, paged, single, skipTake, pageOf } from '../paging'; +import { id, iso, isoDate } from '../schemas'; +import { prisma } from '../legacy'; +import { registrationSummary, SUMMARY_INCLUDE, toSummary } from './registrations'; +import { updateProfile } from '../../services/auth'; + +const me = z.object({ + id, + name: z.string(), + email: z.string(), + phone: z.string().nullable(), + role: z.enum(['admin', 'supervisor', 'staff', 'user']), + twoFactorEnabled: z.boolean(), + notificationPreference: z.enum(['email', 'whatsapp', 'both']), + homeCampusId: id.nullable(), + createdAt: isoDate, +}); + +type MeRow = { id: string; name: string; email: string; phoneNumber: string | null; role: 'admin' | 'supervisor' | 'staff' | 'user'; twoFactorEnabled: boolean | null; notificationPreference: 'email' | 'whatsapp' | 'both'; homeCampusId: string | null; createdAt: Date }; +const toMe = (u: MeRow): z.input => ({ + id: u.id, name: u.name, email: u.email, phone: u.phoneNumber ?? null, role: u.role, twoFactorEnabled: !!u.twoFactorEnabled, + notificationPreference: u.notificationPreference, homeCampusId: u.homeCampusId ?? null, createdAt: iso(u.createdAt), +}); + +/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */ +const { requiresTwoFactor } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean }; +const privacyNotice = require('../../utils/privacyNotice') as { noticePromptPending(u: { noticeVersionAccepted: unknown }): Promise }; +const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise<{ campusIds: string[] | null } | null> }; + +export const getMe = defineRoute({ + method: 'get', + path: '/me', + tag: 'Me', + summary: 'The signed-in person', + description: 'With what the app asks after sign-in (`newsPromptPending`, `noticePromptPending`), whether two-step sign-in is required for their role, and the campuses they\'re limited to (`campusScope`, null = every campus). Viewing as someone else never prompts.', + access: 'user', + response: single(me.extend({ + twoFactorRequired: z.boolean().describe('Their role must use two-step sign-in'), + newsPromptPending: z.boolean(), + noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]), + campusScope: z.array(id).nullable(), + })), + async handler({ user, req }) { + const u = await prisma.user.findUnique({ + where: { id: user!.id }, + select: { id: true, name: true, email: true, phoneNumber: true, role: true, twoFactorEnabled: true, twoFactorMethod: true, notificationPreference: true, homeCampusId: true, createdAt: true, newsAskedAt: true, noticeVersionAccepted: true }, + }); + if (!u) throw new ApiError('UNAUTHENTICATED', 'User not found'); + const impersonating = !!(req as any).impersonation; + return { + data: { + ...toMe(u), + twoFactorRequired: requiresTwoFactor(u), + newsPromptPending: !u.newsAskedAt && !impersonating, + noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }), + campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null, + }, + }; + }, +}); + +export const updateMe = defineRoute({ + method: 'patch', + path: '/me', + tag: 'Me', + summary: 'Change my details', + description: 'Only what is sent changes. A new `password` needs `currentPassword`; it sends a security notice and stops other devices skipping the 2FA code. The answer has a fresh `token` (the old one keeps working).', + access: 'user', + body: z.object({ + name: z.string().trim().min(1).max(200).optional(), + email: z.email().max(200).optional(), + phone: z.string().trim().max(40).nullable().optional().describe('null or empty removes it'), + notificationPreference: z.enum(['email', 'whatsapp', 'both']).optional(), + homeCampusId: id.nullable().optional().describe('While campuses are on'), + password: z.string().min(8).max(200).optional(), + currentPassword: z.string().max(200).optional(), + }), + response: single(me).extend({ token: z.string() }), + async handler({ body, user, req }) { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + const { user: u, token } = await updateProfile(user!.id, { ...body, phoneNumber: body.phone }, { ip: getClientIp(req), userAgent: req.headers['user-agent'] }); + return { data: toMe(u), token }; + }, +}); + +export const listMyRegistrations = defineRoute({ + method: 'get', + path: '/me/registrations', + tag: 'Me', + summary: 'My registrations', + description: 'Newest first. By default only ones for events that have not ended, and not cancelled; `past=true` lists everything.', + access: 'user', + query: pageQuery.extend({ + past: z.enum(['true', 'false']).default('false').transform(v => v === 'true').describe('Include past and cancelled registrations'), + }), + response: paged(registrationSummary), + async handler({ query, user }) { + const now = new Date(); + const where = query.past + ? { userId: user!.id } + : { userId: user!.id, status: { not: 'cancelled' as const }, event: { endDate: { gte: now } } }; + const [rows, total] = await Promise.all([ + prisma.registration.findMany({ where, include: SUMMARY_INCLUDE, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], ...skipTake(query) }), + prisma.registration.count({ where }), + ]); + return pageOf(rows.map(r => toSummary(r, now)), total, query); + }, +}); diff --git a/apps/events/backend/src/v2/resources/money.ts b/apps/events/backend/src/v2/resources/money.ts new file mode 100644 index 0000000..1696941 --- /dev/null +++ b/apps/events/backend/src/v2/resources/money.ts @@ -0,0 +1,366 @@ +/** + * Money on v2 (1.51.11): payments and refunds, payment links and providers, cash-ups, provider + * transactions, the waitlist, sponsorship, consent, attendee form answers and feedback. Each + * route runs the v1 handler (viaV1.ts) behind the same access and campus checks as v1. + */ +import { z } from 'zod'; +import { id, idParams } from '../schemas'; +import { listData, v1Route } from '../viaV1'; +import * as D from '../docs'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- v1 handlers and middleware are JavaScript */ +const rateLimit = require('express-rate-limit') as (opts: object) => any; +const cs = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown; ownerOk?: boolean }): any; + scopeBody(targets: [string, string][], opts?: { need?: 'view' | 'manage'; orphan?: 'pass' | 'deny' }): any; + scopeList: any; + unscopedOnly: any; +}; +const pay = require('../../controllers/paymentController'); +const providers = require('../../controllers/paymentProvidersController'); +const cashup = require('../../controllers/cashupController'); +const ptx = require('../../controllers/providerTransactionsController'); +const waitlist = require('../../controllers/waitlistController'); +const sponsor = require('../../controllers/sponsorshipController'); +const consent = require('../../controllers/consentController'); +const forms = require('../../controllers/formController'); +const feedback = require('../../controllers/feedbackController'); + +/** Optional text filters, passed to v1 as they come. */ +const filters = (...names: string[]) => z.looseObject(Object.fromEntries(names.map(n => [n, z.string().max(4000).optional()]))); +const paymentFilters = filters('page', 'limit', 'userId', 'from', 'donations', 'method', 'kind', 'startDate', 'endDate'); +const tokenParams = z.object({ token: z.string().min(1).max(200) }); +const asEvent = (ctx: any) => ({ params: { ...ctx.req.params, eventId: ctx.params.id } }); +// Links in messages are credentials, so guessing stays slow (as on v1). +const linkLimiter = () => rateLimit({ windowMs: 60 * 1000, max: 30, message: { message: 'Too many attempts. Please try again in a minute.' } }); +const SCOPE_LIST = 'scopeList (the handler filters by listWhere)'; + +// ─── Documented shapes (docs.ts) ───────────────────────────────────────────── + +const providerRow = D.obj({ id: D.str.describe('yoco, payfast'), label: D.str }); +const providerSettings = D.obj({ + id: D.str, label: D.str, enabled: D.bool, configured: D.bool.describe('Its keys are set up'), + capabilities: D.anyObj.describe('What the provider can do, e.g. look payments up'), +}); +const openCheckout = D.obj({ + id: D.str, provider: D.str, providerLabel: D.str, canCheck: D.bool.describe('The provider can be asked whether it was paid'), + amount: D.rand, description: D.str, type: D.optStr.describe('registration, donation, sponsorship, season_pass…'), + registrationId: D.optStr, payer: D.optStr, createdAt: D.date, +}); +const payPage = D.obj({ + id: D.str, status: z.enum(['open', 'paid']), amount: D.rand, description: D.str, + provider: D.optStr.describe('The provider already chosen, if any'), providers: z.array(providerRow), cancelUrl: D.optStr, + redirectUrl: D.optStr, form: D.anyObj.nullish().describe('A signed form to post (PayFast)'), +}); +const paymentFull = D.payment.extend({ + registration: D.registration.nullish(), + generatedTickets: z.array(D.ticket).optional().describe('Tickets issued because this paid it in full'), + formsNeeded: D.optNum.describe('Attendee forms still holding the tickets back (1.52.0)'), + donationSplit: D.payment.optional().describe('What was paid over the balance, kept as a donation'), +}); +const cashupLineInput = D.obj({ + method: D.str.describe('cash, card, eft…'), + bankAmount: D.optRand, onHandAmount: D.optRand.describe('Cash only'), pendingAmount: D.optRand.describe('Not cash'), pendingReference: D.optStr, + writeOffs: z.array(D.obj({ category: D.str, amount: D.optRand, reason: D.optStr })).optional(), notes: D.optStr, +}); +const cashupRecord = D.obj({ id: D.str, eventId: D.str, action: D.optStr.describe('close, quick_close, reopen'), notes: D.optStr, createdAt: D.date, performedBy: D.userRef.nullish() }); +const providerTransaction = D.obj({ + id: D.str, provider: D.str, providerLabel: D.str, externalId: D.str.describe('The provider\'s id'), + amount: D.optNum.describe('Cents'), currency: D.optStr, createdDate: D.optDate, checkoutId: D.optStr, methodType: D.optStr, + reconciled: D.bool, ignored: D.bool, paymentId: D.optStr, note: D.optStr.describe('Why it needs a look'), metadata: D.anyObj.nullish(), +}); +const txAnswer = (data: T) => D.obj({ success: D.bool, data, message: D.optStr }); +const waitlistEntry = D.obj({ + id: D.str, eventId: D.str, eventOptionId: D.str, variantId: D.optStr, sessionId: D.optStr, userId: D.str, + quantity: D.num, position: D.num.describe('Place in the queue'), status: D.str.describe('waiting, offered, claimed, expired, removed, left'), + offeredQuantity: D.optNum, offeredAt: D.optDate, offerExpiresAt: D.optDate, claimedAt: D.optDate, registrationId: D.optStr, createdAt: D.date, +}); +const consentRow = D.obj({ + name: D.str.describe('The young person'), status: D.str.describe('not_requested, pending, given, declined'), + parentName: D.optStr, parentEmail: D.optStr, parentPhone: D.optStr, request: D.anyObj.nullish(), +}); +const feedbackField = D.obj({ id: D.str.optional(), type: D.str.describe('rating, multiple_choice, text, yes_no…'), label: D.str, isRequired: D.optBool, helpText: D.optStr, options: z.array(D.str).nullish() }); +const feedbackForm = D.obj({ + id: D.str, eventId: D.str, sendAt: D.optDate, sentAt: D.optDate, audience: D.str.describe('checked_in or everyone'), anonymous: D.bool, intro: D.optStr, + fields: z.array(feedbackField), invited: D.optNum, responses: z.unknown().optional().describe('Answers per question'), +}).nullable().describe('null when the event has no feedback form'); +const UNSCOPED = 'unscopedOnly (admins and unscoped supervisors)'; + +// ─── Payments ──────────────────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/payments/providers', tag: 'Payments', summary: 'The payment providers switched on', + access: 'public', documented: { response: D.obj({ providers: z.array(providerRow), minimumAmount: D.rand.describe('Smallest online payment') }) }, v1: providers.listPaymentProviders, +}); +v1Route({ + method: 'get', path: '/payments/providers/settings', tag: 'Payments', summary: 'Payment provider settings', + description: 'Admins. Keys are masked.', access: 'admin', documented: { response: D.obj({ providers: z.array(providerSettings), minimumAmount: D.rand }) }, v1: providers.getPaymentProviderSettings, +}); +v1Route({ + method: 'put', path: '/payments/providers/settings', tag: 'Payments', summary: 'Change payment provider settings', + access: 'admin', body: z.looseObject({}), documented: { body: D.obj({ providers: z.array(D.obj({ id: D.str, enabled: D.bool })).min(1).describe('Every provider, in the order to offer them') }), response: D.obj({ message: D.str, providers: z.array(providerSettings) }) }, v1: providers.updatePaymentProviderSettings, +}); +v1Route({ + method: 'get', path: '/payments/open-checkouts', tag: 'Payments', summary: 'Checkouts started but not finished', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], documented: { response: D.obj({ checkouts: z.array(openCheckout), days: D.num.describe('How far back it looks') }) }, v1: providers.listOpenCheckouts, +}); +v1Route({ + method: 'post', path: '/payments/open-checkouts/check', tag: 'Payments', summary: 'Ask the provider about open checkouts', + description: 'Records any that were paid (for when a webhook was missed).', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], body: z.looseObject({}), documented: { body: D.obj({ ids: D.ids.optional().describe('Checkouts to ask about (default: every open one), at most 200') }), response: D.obj({ results: z.array(D.anyObj), recorded: D.num.describe('Payments found and recorded'), message: D.str }) }, v1: providers.checkCheckoutStatus, +}); +v1Route({ + method: 'get', path: '/payments/stats', tag: 'Payments', summary: 'Payment totals', access: 'admin', query: paymentFilters, documented: { response: D.obj({ totalToday: D.rand, totalWeek: D.rand, totalMonth: D.rand }) }, v1: pay.getPaymentStats, +}); +v1Route({ + method: 'get', path: '/payments', tag: 'Payments', summary: 'Every payment', + description: 'For the events you may see. `page` and `limit` page it (otherwise everything); see v1 for the filters it takes.', + access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: paymentFilters, documented: { response: D.v1Page(D.payment.extend({ registration: D.registration.nullish() })) }, v1: pay.getPayments, +}); +v1Route({ + method: 'post', path: '/payments', tag: 'Payments', summary: 'Record a payment', + description: 'Cash, card, EFT or other, against a registration or (a donation) an event. Paid in full issues and sends the tickets.', + access: 'supervisor', campusScope: 'scopeBody(registrationId, eventId; deny orphans)', status: 201, + middleware: [cs.scopeBody([['registrationId', 'registration'], ['eventId', 'event']], { orphan: 'deny' })], + body: z.looseObject({ registrationId: id.nullish(), eventId: id.nullish(), amount: z.union([z.number(), z.string()]), method: z.string().max(20).optional() }), + documented: { body: D.obj({ registrationId: D.optStr, eventId: D.optStr.describe('A donation: the event'), amount: D.numeric, method: D.str.describe('cash, card, eft or other'), isDonation: D.optBool, paidAt: D.optDate.describe('Backdate it'), userId: D.optStr.describe('A donation: who gave it') }), response: paymentFull }, v1: pay.createPayment, +}); +v1Route({ + method: 'post', path: '/payments/refunds', tag: 'Payments', summary: 'Refund a payment', + access: 'supervisor', campusScope: 'scopeBody(paymentId, registrationId; manage, deny orphans)', status: 201, + middleware: [cs.scopeBody([['paymentId', 'payment'], ['registrationId', 'registration']], { need: 'manage', orphan: 'deny' })], + body: z.looseObject({ paymentId: id.optional(), registrationId: id.optional() }), documented: { body: D.obj({ paymentId: D.optStr.describe('The payment refunded (or registrationId)'), registrationId: D.optStr, userId: D.str, amount: D.numeric.describe('Positive; stored as a negative payment'), method: D.str, reason: D.optStr }), response: D.payment }, v1: pay.createRefund, +}); +v1Route({ + method: 'post', path: '/payments/donations/assign', tag: 'Payments', summary: 'Put a donation towards a registration', + access: 'supervisor', campusScope: 'scopeBody(paymentId deny orphans; registrationId)', + middleware: [cs.scopeBody([['paymentId', 'payment']], { orphan: 'deny' }), cs.scopeBody([['registrationId', 'registration']])], + body: z.looseObject({ paymentId: id, registrationId: id }), documented: { body: D.obj({ paymentId: D.str.describe('The donation'), registrationId: D.str, amount: D.numeric.optional().describe('Default: as much as both allow') }), response: D.obj({ message: D.optStr, updatedRegistration: D.registration.optional(), generatedTickets: z.array(D.ticket).optional() }) }, v1: pay.assignDonationToRegistration, +}); +v1Route({ + method: 'post', path: '/payments/donations/unassign', tag: 'Payments', summary: 'Take a donation back off a registration', + access: 'supervisor', campusScope: 'scopeBody(legId; deny orphans)', middleware: [cs.scopeBody([['legId', 'payment']], { orphan: 'deny' })], + body: z.looseObject({ legId: id }), documented: { response: D.obj({ message: D.str, updatedRegistration: D.registration, donationId: D.str }) }, v1: pay.unassignDonationFromRegistration, +}); +v1Route({ + method: 'post', path: '/donations/checkout', tag: 'Payments', summary: 'Give to an event', + description: 'Starts a checkout for a donation of `amount` to `eventId`; answers where to send the person (`redirectUrl`).', + access: 'user', body: z.looseObject({ eventId: id, amount: z.union([z.number(), z.string()]) }), documented: { body: D.obj({ eventId: D.str, amount: D.numeric, provider: D.optStr, successUrl: D.optStr, cancelUrl: D.optStr, failureUrl: D.optStr }), response: D.checkout.extend({ amount: D.rand, event: D.eventRef.partial() }) }, v1: pay.createCheckout, +}); +v1Route({ + method: 'get', path: '/me/payments', tag: 'Me', summary: 'My payments', access: 'user', query: paymentFilters, documented: { response: D.v1Page(D.payment.extend({ registration: D.registration.nullish() })) }, v1: pay.getUserPayments, +}); +v1Route({ + method: 'get', path: '/payments/:id', tag: 'Payments', summary: 'One payment', + access: 'user', campusScope: 'scopeEvent(payment, owner-ok)', middleware: [cs.scopeEvent({ resolve: 'payment', ownerOk: true })], params: idParams, documented: { response: D.payment.extend({ registration: D.registration.nullish() }) }, v1: pay.getPaymentById, +}); +v1Route({ + method: 'post', path: '/payments/:id/receipt', tag: 'Payments', summary: 'Send the receipt again', + access: 'user', campusScope: 'scopeEvent(payment, owner-ok)', middleware: [cs.scopeEvent({ resolve: 'payment', ownerOk: true })], params: idParams, + body: z.looseObject({ channel: z.string().max(20).optional() }), documented: { response: D.message }, v1: pay.sendReceipt, +}); +v1Route({ + method: 'get', path: '/registrations/:id/payments', tag: 'Payments', summary: 'A registration\'s payments', + access: 'user', campusScope: 'scopeEvent(registration, owner-ok)', middleware: [cs.scopeEvent({ resolve: 'registration', ownerOk: true })], params: idParams, + response: listData, documented: { response: z.array(D.payment) }, map: ctx => ({ params: { registrationId: ctx.params.id } }), v1: pay.getPaymentsByRegistration, +}); +v1Route({ + method: 'post', path: '/registrations/:id/payment-link', tag: 'Payments', summary: 'Make a link to pay', + description: 'Supervisors: a checkout for `amount` (part of what\'s owed) for someone else to pay. Answers `redirectUrl` (the link) — or `priceUpdated` when an early-bird price ran out.', + access: 'supervisor', campusScope: 'scopeEvent(registration)', middleware: [cs.scopeEvent({ resolve: 'registration' })], params: idParams, + body: z.looseObject({ amount: z.union([z.number(), z.string()]).optional() }), map: ctx => ({ body: { ...(ctx.req.body || {}), registrationId: ctx.params.id } }), documented: { body: D.obj({ amount: D.numeric.optional(), donationAmount: D.numeric.optional(), provider: D.optStr, successUrl: D.optStr, cancelUrl: D.optStr, failureUrl: D.optStr }), response: D.checkout.extend({ priceUpdated: D.optBool, newTotal: D.optRand }) }, v1: pay.createCheckout, +}); +v1Route({ + method: 'post', path: '/registrations/:id/payment-link/send', tag: 'Payments', summary: 'Send someone a link to pay', + description: 'By email and/or WhatsApp, for what\'s still owing.', + access: 'supervisor', campusScope: 'scopeEvent(registration)', middleware: [cs.scopeEvent({ resolve: 'registration' })], params: idParams, + body: z.looseObject({}), map: ctx => ({ body: { ...(ctx.req.body || {}), registrationId: ctx.params.id } }), documented: { body: D.obj({ redirectUrl: D.str.describe('The link to send'), channel: z.enum(['email', 'whatsapp']) }), response: D.obj({ sent: z.literal(true), channel: D.str }) }, v1: pay.sendPaymentLink, +}); +v1Route({ + method: 'get', path: '/events/:id/payments', tag: 'Payments', summary: 'An event\'s payments', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: z.array(D.payment) }, v1: pay.getPaymentsByEvent, +}); +v1Route({ + method: 'get', path: '/payment-links/:id', tag: 'Payments', summary: 'A pay page', + description: 'What a payment link shows: what\'s owed and the providers to pay with. The id in the link is the credential.', + access: 'public', params: idParams, documented: { response: payPage }, v1: providers.getPayPage, +}); +v1Route({ + method: 'post', path: '/payment-links/:id', tag: 'Payments', summary: 'Pay from a pay page', + description: 'Starts a checkout with the chosen provider; answers where to send the person.', + access: 'public', params: idParams, body: z.looseObject({ provider: z.string().max(40).optional() }), documented: { response: D.obj({ provider: D.str, redirectUrl: D.optStr, form: D.anyObj.nullish() }) }, v1: providers.choosePayProvider, +}); + +// ─── Cash-ups ──────────────────────────────────────────────────────────────── + +const cashupBase = '/events/:id/cashup'; +v1Route({ + method: 'get', path: '/cashups/audit', tag: 'Cash-ups', summary: 'Cash-up history', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventId', 'from', 'to'), documented: { response: z.array(cashupRecord) }, v1: cashup.getCashupAudit, +}); +v1Route({ + method: 'get', path: cashupBase, tag: 'Cash-ups', summary: 'An event\'s cash-up', + description: 'Income by method, costs, what each drawer should hold, and the saved draft.', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, map: asEvent, documented: { response: D.obj({ event: D.anyObj, paymentsByMethod: D.anyObj.describe('Income per method'), totalRevenue: D.rand, costs: z.array(D.anyObj), totalCosts: D.rand, expectedCashByMethod: D.anyObj, reconciled: D.anyObj.nullish().describe('The last close, line by line'), netProfit: D.rand, totalDonations: D.rand, unallocatedDonationsTotal: D.rand, discountsTotal: D.optRand, salesByOption: z.array(D.anyObj).optional() }) }, v1: cashup.getEventCashup, +}); +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: 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', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: z.object({ id, userId: id }), + body: z.looseObject({}), map: ctx => ({ params: { eventId: ctx.params.id, userId: ctx.params.userId } }), documented: { body: D.obj({ denominations: z.array(D.obj({ value: D.num.describe('The note or coin, in rand'), count: D.num })), notes: D.optStr }), response: D.anyObj.describe('The saved count') }, v1: cashup.savePersonCash, +}); +v1Route({ + method: 'put', path: `${cashupBase}/draft`, tag: 'Cash-ups', summary: 'Save the cash-up as a draft', + access: 'admin', params: idParams, body: z.looseObject({}), map: asEvent, documented: { body: D.obj({ lines: z.array(cashupLineInput), notes: D.optStr }), response: D.message }, v1: cashup.saveEventCashupDraft, +}); +v1Route({ + method: 'post', path: `${cashupBase}/close`, tag: 'Cash-ups', summary: 'Close the event', + description: 'Admins. Nothing about the event\'s money can change until it\'s reopened.', + access: 'admin', params: idParams, body: z.looseObject({}), map: asEvent, documented: { body: D.obj({ lines: z.array(cashupLineInput).optional().describe('Per payment method: in the bank, on hand, pending, write-offs (leave out for a quick close)'), notes: D.optStr }), response: cashupRecord }, v1: cashup.closeEvent, +}); +v1Route({ + method: 'post', path: `${cashupBase}/reopen`, tag: 'Cash-ups', summary: 'Reopen a closed event', + access: 'admin', params: idParams, body: z.looseObject({}), map: asEvent, documented: { body: D.obj({ notes: D.optStr.describe('Why') }), response: cashupRecord }, v1: cashup.reopenEvent, +}); +v1Route({ + method: 'post', path: '/cashup-lines/:id/pending', tag: 'Cash-ups', summary: 'Settle a pending cash-up line', + access: 'admin', params: idParams, body: z.looseObject({}), map: ctx => ({ params: { lineId: ctx.params.id } }), documented: { body: D.obj({ outcome: z.enum(['received', 'written_off']), amount: D.numeric, category: D.optStr.describe('A write-off: what it was for'), notes: D.optStr }), response: D.anyObj.describe('The settlement recorded') }, v1: cashup.resolvePending, +}); + +// ─── Provider transactions ─────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/provider-transactions', tag: 'Payments', summary: 'Transactions from Yoco and PayFast', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], query: filters('provider'), documented: { response: txAnswer(z.array(providerTransaction)) }, v1: ptx.getAllProviderTransactions, +}); +v1Route({ + method: 'get', path: '/provider-transactions/unreconciled', tag: 'Payments', summary: 'Provider transactions not matched yet', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], documented: { response: txAnswer(z.array(providerTransaction)) }, v1: ptx.getUnreconciledProviderTransactions, +}); +v1Route({ + method: 'post', path: '/provider-transactions/:id/reconcile', tag: 'Payments', summary: 'Match a provider transaction to a registration', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], params: idParams, body: z.looseObject({}), documented: { body: D.obj({ registrationId: D.optStr, eventId: D.optStr.describe('As a donation to this event instead'), userId: D.optStr }), response: txAnswer(D.obj({ transaction: providerTransaction, payment: D.payment, generatedTickets: z.array(D.ticket).optional() })) }, v1: ptx.reconcileProviderTransaction, +}); +v1Route({ + method: 'post', path: '/provider-transactions/:id/ignore', tag: 'Payments', summary: 'Ignore a provider transaction', + access: 'supervisor', campusScope: UNSCOPED, middleware: [cs.unscopedOnly], params: idParams, body: z.looseObject({}), documented: { response: txAnswer(providerTransaction) }, v1: ptx.ignoreProviderTransaction, +}); + +// ─── Waitlist ──────────────────────────────────────────────────────────────── + +v1Route({ + method: 'post', path: '/waitlist', tag: 'Waitlist', summary: 'Join a sold-out event\'s waitlist', + description: 'Signed in, or with a name and email or phone. When places free up, people are offered them in order.', + access: 'optional', status: 201, body: z.looseObject({ eventId: id }), documented: { body: D.obj({ eventId: D.str, eventOptionId: D.str, variantId: D.optStr, sessionId: D.optStr.describe('Per-session tickets: the session'), quantity: D.numeric, guestName: D.optStr.describe('Not signed in'), guestEmail: D.optStr, guestPhone: D.optStr }), response: waitlistEntry.extend({ ahead: D.num.describe('People ahead'), message: D.str }) }, v1: waitlist.joinWaitlist, +}); +v1Route({ method: 'get', path: '/me/waitlist', tag: 'Me', summary: 'Waitlists I\'m on', access: 'user', documented: { response: z.array(waitlistEntry) }, v1: waitlist.myWaitlist }); +v1Route({ + method: 'get', path: '/waitlist/claims/:token', tag: 'Waitlist', summary: 'A waitlist offer', + description: 'What an offer link shows (the token is the credential). Register with `waitlistToken` to take it.', + access: 'public', middleware: [linkLimiter()], params: tokenParams, documented: { response: D.obj({ eventId: D.optStr, eventTitle: D.optStr, eventStart: D.optDate, eventOptionId: D.str, optionName: D.str, variantId: D.optStr, variantName: D.optStr, sessionId: D.optStr, sessionName: D.optStr, sessionStart: D.optDate, lineName: D.str, quantity: D.optNum.describe('Places offered'), requested: D.num, expiresAt: D.optDate, name: D.optStr }) }, v1: waitlist.claimInfo, +}); +v1Route({ + method: 'get', path: '/events/:id/waitlist', tag: 'Waitlist', summary: 'An event\'s waitlist', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, query: filters('all'), map: asEvent, documented: { response: z.array(waitlistEntry.extend({ user: D.userSummary.nullish() })) }, v1: waitlist.eventWaitlist, +}); +for (const [action, summary, handler] of [['offer', 'Offer someone their places now', waitlist.offerManually], ['move', 'Move someone up or down the waitlist', waitlist.moveEntry], ['remove', 'Take someone off the waitlist', waitlist.removeEntry]] as const) { + v1Route({ + method: 'post', path: `/waitlist/:id/${action}`, tag: 'Waitlist', summary, + access: 'supervisor', campusScope: 'scopeEvent(waitlistEntry)', middleware: [cs.scopeEvent({ resolve: 'waitlistEntry' })], params: idParams, body: z.looseObject({}), v1: handler, + documented: { + body: action === 'offer' ? D.obj({ quantity: D.numeric.optional().describe('Places to offer (default: all they asked for)') }) + : action === 'move' ? D.obj({ direction: z.enum(['up', 'down']) }) : D.anyObj, + response: D.message, + }, + }); +} +v1Route({ method: 'delete', path: '/waitlist/:id', tag: 'Waitlist', summary: 'Leave a waitlist', access: 'user', params: idParams, documented: { response: D.message }, v1: waitlist.leaveWaitlist }); + +// ─── Sponsorship ───────────────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/events/:id/sponsorship', tag: 'Sponsorship', summary: 'Sponsoring places at an event', + description: 'Whether it\'s on, and the suggested amounts.', access: 'public', params: idParams, map: asEvent, documented: { response: D.obj({ enabled: D.bool, open: D.optBool, spotPrice: D.optRand, showProgress: D.optBool, goalSpots: D.optNum, spotsFunded: D.optNum, sponsors: z.unknown().optional() }) }, v1: sponsor.getEventSponsorship, +}); +v1Route({ + method: 'get', path: '/events/:id/sponsorship/pool', tag: 'Sponsorship', summary: 'The sponsorship pool', + description: 'What\'s been given and what\'s been used.', access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: D.obj({ eventId: D.str, spotPrice: D.rand, goalSpots: D.optNum }).describe('Plus the pool: given, used and places funded') }, v1: sponsor.getPool, +}); +v1Route({ + method: 'post', path: '/sponsorships/checkout', tag: 'Sponsorship', summary: 'Give towards places', + description: 'Starts a checkout; answers where to send the person.', access: 'optional', body: z.looseObject({ eventId: id }), documented: { body: D.obj({ eventId: D.str, spots: D.numeric.optional().describe('Places to fund (or amount)'), amount: D.numeric.optional(), anonymous: D.optBool, sponsorName: D.optStr, message: D.optStr, name: D.optStr.describe('Not signed in'), email: D.optStr, phone: D.optStr, provider: D.optStr }), response: D.checkout.extend({ amount: D.rand }) }, v1: sponsor.createSponsorCheckout, +}); + +// ─── Consent ───────────────────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/events/:id/consent', tag: 'Consent', summary: 'Parental consent for an event', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: D.obj({ event: D.anyObj, counts: z.record(z.string(), z.number()).describe('Status → how many'), rows: z.array(consentRow) }) }, v1: consent.listEventConsent, +}); +v1Route({ + method: 'get', path: '/events/:id/consent/medical', tag: 'Consent', summary: 'Medical notes from consent forms', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: D.obj({ event: D.eventRef.partial(), rows: z.array(D.obj({ name: D.str, dateOfBirth: D.optDate, parentName: D.optStr, parentPhone: D.optStr, parentEmail: D.optStr, medical: D.anyObj.nullish(), emergency: D.anyObj.nullish(), photoConsent: D.optBool, purged: D.bool.describe('Medical details removed after the event') })) }) }, v1: consent.medicalList, +}); +v1Route({ + method: 'post', path: '/events/:id/consent/resend-pending', tag: 'Consent', summary: 'Remind everyone who hasn\'t answered', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, body: z.looseObject({}), map: asEvent, documented: { response: D.obj({ message: D.str, sent: D.num, pending: D.num }) }, v1: consent.resendPending, +}); +v1Route({ + method: 'post', path: '/events/:id/consent/rerequest', tag: 'Consent', summary: 'Ask for consent again', + description: 'After the consent wording changed.', access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, + body: z.looseObject({}), map: ctx => ({ params: { eventId: ctx.params.id }, body: ctx.req.body }), documented: { response: D.obj({ message: D.str, created: D.num }) }, v1: consent.rerequestConsent, +}); +v1Route({ + method: 'post', path: '/consent-requests/:id/resend', tag: 'Consent', summary: 'Send a consent request again', + access: 'user', campusScope: 'scopeEvent(consentRequest, owner-ok)', middleware: [cs.scopeEvent({ resolve: 'consentRequest', ownerOk: true })], params: idParams, + body: z.looseObject({}), documented: { response: D.message }, v1: consent.resendRequest, +}); +v1Route({ + method: 'get', path: '/consent/:token', tag: 'Consent', summary: 'A consent form', + description: 'What the link in a consent request shows (the token is the parent\'s credential).', + access: 'public', middleware: [linkLimiter()], params: tokenParams, documented: { response: D.obj({ status: D.str, superseded: D.bool, expired: D.bool, respondedAt: D.optDate, attendeeName: D.str, parentName: D.optStr, consentText: D.str, textVersion: D.optNum, event: D.obj({ title: D.str, startDate: D.date, endDate: D.date, location: D.optStr }), collect: D.obj({ medical: D.bool, emergency: D.bool, photo: D.bool }).describe('What the form asks for') }) }, v1: consent.getConsent, +}); +v1Route({ + method: 'post', path: '/consent/:token', tag: 'Consent', summary: 'Answer a consent form', + access: 'public', middleware: [linkLimiter()], params: tokenParams, body: z.looseObject({}), documented: { body: D.obj({ decision: z.enum(['give', 'decline']), signedName: D.str, isGuardian: D.bool.describe('Must be true'), medical: D.obj({ allergies: D.optStr, medication: D.optStr, conditions: D.optStr, medicalAid: D.optStr }).optional(), emergency: D.obj({ name: D.str, phone: D.str, relationship: D.optStr }).optional(), photoConsent: D.optBool }), response: D.obj({ message: D.str, status: z.enum(['given', 'declined']) }) }, v1: consent.answerConsent, +}); + +// ─── Attendee form answers ─────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/form-responses', tag: 'Registrations', summary: 'Attendee form answers', + description: 'For an event (`eventId`) or a registration (`registrationId`), for events you may see.', + access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventId', 'registrationId', 'userId', 'cursor'), documented: { response: D.obj({ items: z.array(D.obj({ id: D.str, registrationId: D.str, attendeeId: D.optStr, createdAt: D.date, answers: z.array(D.obj({ fieldId: D.str, value: D.str })).optional() })), nextCursor: D.optStr.describe('Pass as `cursor` for the next page') }) }, v1: forms.listFormResponses, +}); + +// ─── Feedback ──────────────────────────────────────────────────────────────── + +v1Route({ + method: 'get', path: '/feedback/summary', tag: 'Feedback', summary: 'Feedback across events', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventIds'), documented: { response: z.array(D.obj({ eventId: D.str, title: D.str, startDate: D.date, anonymous: D.bool, sentAt: D.optDate, invited: D.num, responses: D.num, responseRate: D.optNum.describe('%'), questions: z.array(D.anyObj).describe('Each question with its answers summarised') })) }, v1: feedback.getSummary, +}); +v1Route({ + method: 'get', path: '/feedback-forms/:token', tag: 'Feedback', summary: 'A feedback form', + description: 'What the link sent after an event shows (the token is the credential).', access: 'public', params: tokenParams, documented: { response: D.obj({ event: D.anyObj, name: D.str, intro: D.optStr, anonymous: D.bool, responded: D.bool, fields: z.array(feedbackField) }) }, v1: feedback.getPublicForm, +}); +v1Route({ + method: 'post', path: '/feedback-forms/:token', tag: 'Feedback', summary: 'Answer a feedback form', + access: 'public', params: tokenParams, body: z.looseObject({}), documented: { body: D.obj({ answers: z.record(z.string(), z.unknown()).describe('Field id → answer') }), response: D.message }, v1: feedback.submitPublicForm, +}); +v1Route({ + method: 'get', path: '/events/:id/feedback', tag: 'Feedback', summary: 'An event\'s feedback set-up and answers', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams, map: asEvent, documented: { response: feedbackForm }, v1: feedback.getEventFeedback, +}); +v1Route({ + method: 'put', path: '/events/:id/feedback', tag: 'Feedback', summary: 'Set up an event\'s feedback form', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, body: z.looseObject({}), map: asEvent, documented: { body: D.obj({ sendAt: D.optDate, audience: D.optStr.describe('checked_in or everyone'), anonymous: D.optBool, intro: D.optStr, fields: z.array(feedbackField) }), response: feedbackForm }, v1: feedback.saveEventFeedback, +}); +v1Route({ + method: 'delete', path: '/events/:id/feedback', tag: 'Feedback', summary: 'Remove an event\'s feedback form', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, map: asEvent, documented: { response: D.message }, v1: feedback.deleteEventFeedback, +}); +v1Route({ + method: 'post', path: '/events/:id/feedback/send-now', tag: 'Feedback', summary: 'Send the feedback form now', description: 'Answers straight away: `invited` is how many it is going to; the emails go out in the background.', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams, body: z.looseObject({}), map: asEvent, documented: { response: D.obj({ invited: D.num, message: D.str }) }, v1: feedback.sendNow, +}); diff --git a/apps/events/backend/src/v2/resources/peopleMessaging.ts b/apps/events/backend/src/v2/resources/peopleMessaging.ts new file mode 100644 index 0000000..732618f --- /dev/null +++ b/apps/events/backend/src/v2/resources/peopleMessaging.ts @@ -0,0 +1,187 @@ +/** + * People and messaging on v2 (1.51.14): the rest of accounts (password reset, activation, + * two-step sign-in, sessions, closing an account), messaging attendees, email and WhatsApp + * broadcasts, scheduled messages, automations, the site banner, saved filters, the dashboards, + * stats, analytics and report files. Each route runs the v1 handler (viaV1.ts) behind the same + * access and campus checks as v1. + */ +import { z } from 'zod'; +import type { Request } from 'express'; +import { id, idParams } from '../schemas'; +import { v1Route } from '../viaV1'; +import * as D from '../docs'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- v1 handlers and middleware are JavaScript */ +const rateLimit = require('express-rate-limit') as (opts: object) => any; +const { loginLimiter } = require('../../middleware/authMiddleware') as { loginLimiter: any }; +const cs = require('../../utils/campusScope') as { + scopeEvent(opts?: { need?: 'view' | 'manage'; from?: (req: any) => unknown }): any; + scopeBroadcast(opts: { freeformField: string }): any; + scopeList: any; + unscopedOnly: any; + campusIndependent(reason: string): any; +}; +const users = require('../../controllers/userController'); +const events = require('../../controllers/eventController'); +const wa = require('../../controllers/whatsappController'); +const bc = require('../../controllers/broadcastController'); +const wbc = require('../../controllers/whatsappBroadcastController'); +const sched = require('../../controllers/scheduledEmailsController'); +const auto = require('../../controllers/automationController'); +const banner = require('../../controllers/bannerController'); +const stats = require('../../controllers/statsController'); +const analytics = require('../../controllers/analyticsController'); +const reports = require('../../controllers/reportController'); +// These two keep their handlers in the route file; v2 runs the v1 router with the v1 path. +const savedFilterRouter = require('../../routes/savedFilterRoutes'); +const dashboardRouter = require('../../routes/dashboardRoutes'); + +const loose = z.looseObject({}); +const filters = (...names: string[]) => z.looseObject(Object.fromEntries(names.map(n => [n, z.string().max(4000).optional()]))); +const SCOPE_LIST = 'scopeList (the handler filters by listWhere)'; + +// ─── Documented shapes (docs.ts) ───────────────────────────────────────────── + +const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp']), destination: D.str.describe('Where the code went, partly hidden') }); +const signedIn = D.obj({ message: D.optStr, id: D.str, name: D.str, email: D.str, role: D.str, token: D.str.describe('A new sign-in token') }); +const kind = z.enum(['update', 'news']).describe('update: about something they booked (always sent). news: needs their news consent'); +const attendeeFilter = D.obj({ + status: D.optStr.describe('any, paid, unpaid, checked_in, not_checked_in…'), attendeeIds: D.ids.optional(), registrationIds: D.ids.optional(), + allocationGroupId: D.optStr.describe('People in one room or group'), name: D.optStr, email: D.optStr, phone: D.optStr, + audience: z.enum(['sponsors']).optional().describe('Sponsors of the event instead'), +}); +const emailAttendees = D.obj({ + subject: D.optStr, html: D.optStr, text: D.optStr.describe('subject and html or text, unless template is tickets'), + template: z.enum(['custom', 'tickets', 'payment_reminder', 'event_reminder']).optional().describe('tickets: send everyone their tickets; the reminders fill in a standard message'), filter: attendeeFilter.optional(), + dryRun: D.optBool.describe('Only say who it would reach'), kind: kind.optional(), promoEventId: D.optStr.describe('Promote another event (news)'), +}); +const whatsappAttendees = D.obj({ + message: D.optStr.describe('Required unless template is tickets'), template: z.enum(['custom', 'tickets', 'payment_reminder', 'event_reminder']).optional(), filter: attendeeFilter.optional(), + dryRun: D.optBool, kind: kind.optional(), promoEventId: D.optStr, +}); +const reach = D.obj({ eventId: D.optStr, kind: D.optStr, matched: D.num, skipped: D.optNum.describe('Left out: no news consent'), recipients: z.array(D.anyObj).optional().describe('The first 20'), queued: D.optNum, template: D.optStr, sent: D.optNum }); +const scheduledJob = D.obj({ + id: D.str, kind: D.str.describe('broadcast or attendees'), eventId: D.optStr, broadcast: D.bool, channel: z.enum(['email', 'whatsapp']).or(D.str), + recipient: D.optStr, scheduledAt: D.date, createdAt: D.date, status: D.str.describe('queued, sent, failed, cancelled'), attempts: D.num, + sentAt: D.optDate, lastError: D.optStr, subject: D.str, html: D.str, text: D.str, message: D.str, hasHtml: D.bool, hasText: D.bool, +}); +const scheduled = D.obj({ message: D.str, job: D.anyObj }); +const bannerShape = D.obj({ message: D.str, type: D.str.describe('info, warning, success, error'), liveFrom: D.optDate, liveTill: D.optDate }); +const savedFilter = D.obj({ id: D.str, page: D.str.describe('The list page it belongs to'), name: D.str, params: D.anyObj.describe('The filters'), isDefault: D.bool, updatedAt: D.date }); +const scanStats = D.obj({ totalToday: D.num, myToday: D.num, lastHour: D.num, byStaff: z.array(D.anyObj) }).partial(); +const monthly = D.obj({ thisMonth: D.num, lastMonth: D.num, pctChange: D.optNum }); +const reportBody = D.obj({ + title: D.str, subtitle: D.optStr, kind: z.enum(['table', 'layered']), + table: D.obj({ columns: z.array(D.str), rows: z.array(z.array(z.unknown())) }).optional().describe('kind table'), + layered: D.obj({ header: D.optStr, sections: z.array(D.anyObj) }).optional().describe('kind layered: titled sections, each with its rows'), + orientation: z.enum(['portrait', 'landscape']).optional(), stats: z.array(D.anyObj).optional().describe('Figures shown above the table'), + chart: D.anyObj.optional(), note: D.optStr, extraTables: z.array(D.anyObj).optional(), +}); +/** The query string of the v2 request, for a v1 router's URL. */ +const qs = (req: Request) => (req.originalUrl.includes('?') ? req.originalUrl.slice(req.originalUrl.indexOf('?')) : ''); + +// ─── Accounts ──────────────────────────────────────────────────────────────── + +v1Route({ method: 'post', path: '/auth/login/code/resend', tag: 'Accounts', summary: 'Send the sign-in code again', access: 'public', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str }), response: challenge }, v1: users.resendLoginTwoFactor }); +v1Route({ method: 'post', path: '/auth/password/forgot', tag: 'Accounts', summary: 'Email me a link to reset my password', description: 'Always the same answer, so it doesn\'t say whether an account has that email. Rate-limited like sign-in.', access: 'public', middleware: [loginLimiter], body: z.looseObject({ email: z.string().max(200) }), documented: { response: D.message }, v1: users.requestPasswordReset }); +v1Route({ method: 'post', path: '/auth/password/reset', tag: 'Accounts', summary: 'Set a new password with a reset link', access: 'public', body: loose, documented: { body: D.obj({ token: D.str.describe('From the link'), password: D.str }), response: D.message }, v1: users.resetPassword }); +v1Route({ method: 'post', path: '/auth/activate', tag: 'Accounts', summary: 'Activate an account with its link', access: 'public', body: loose, documented: { body: D.obj({ token: D.str.describe('From the link'), password: D.str.describe('At least 8 characters'), acceptTerms: D.optBool }), response: signedIn }, v1: users.activateAccount }); +v1Route({ method: 'post', path: '/me/sessions/revoke', tag: 'Me', summary: 'Sign out everywhere else', access: 'user', body: loose, documented: { response: D.obj({ message: D.str, token: D.str.describe('A new token for this device (the old one stops working)') }) }, v1: users.revokeMySession }); +v1Route({ method: 'post', path: '/me/close', tag: 'Me', summary: 'Close my account', description: 'Needs the password. Personal details are removed; payment records stay, anonymised.', access: 'user', body: loose, documented: { body: D.obj({ password: D.str, deleteData: D.optBool.describe('Also ask for my personal information to be deleted') }), response: D.message }, v1: users.closeAccount }); +v1Route({ method: 'get', path: '/me/activity', tag: 'Me', summary: 'Recent sign-ins and changes to my account', access: 'user', documented: { response: z.array(D.obj({ id: D.str, type: D.str.describe('login, password_changed, two_factor_enabled…'), device: D.optStr, createdAt: D.date })) }, v1: users.getMyActivity }); +v1Route({ method: 'post', path: '/me/verify-password', tag: 'Me', summary: 'Check my password (before a sensitive change)', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.ok }, v1: users.verifyPassword }); +v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp']), password: D.str }), response: challenge }, v1: users.startEnableTwoFactor }); +v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str }) }, v1: users.confirmEnableTwoFactor }); +v1Route({ method: 'post', path: '/me/two-factor/disable', tag: 'Me', summary: 'Turn off two-step sign-in', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ twoFactorEnabled: z.literal(false), twoFactorMethod: z.null() }) }, v1: users.disableTwoFactor }); +v1Route({ + method: 'get', path: '/users/exists', tag: 'Accounts', summary: 'Is there an account with this email or phone?', + access: 'supervisor', campusScope: 'campusIndependent (accounts are shared across campuses)', middleware: [cs.campusIndependent('accounts are shared across campuses')], + query: filters('email', 'phone', 'phoneNumber'), documented: { response: D.obj({ exists: D.bool, hasEmail: D.optBool, hasPhone: D.optBool, user: D.obj({ id: D.str, name: D.str, email: D.optStr, phoneNumber: D.optStr, notificationPreference: D.optStr }).nullish() }) }, v1: users.checkUserExists, +}); +v1Route({ + method: 'get', path: '/users', tag: 'Accounts', summary: 'Every account', + description: 'Paged (`page`, `limit`) and searchable (`q`, `role`, `campus`, …) — see v1 for every filter.', + access: 'supervisor', campusScope: 'campusIndependent (accounts are shared across campuses)', middleware: [cs.campusIndependent('accounts are shared across campuses')], + query: filters('page', 'limit', 'search', 'role', 'isActive', 'campus'), documented: { response: D.v1Page(D.user) }, v1: users.getUsers, +}); +v1Route({ method: 'get', path: '/users/:id', tag: 'Accounts', summary: 'One account', access: 'admin', params: idParams, documented: { response: D.user.extend({ scopedCampusIds: D.ids.optional().describe('Campuses they\'re limited to') }) }, v1: users.getUserById }); +v1Route({ method: 'patch', path: '/users/:id', tag: 'Accounts', summary: 'Change an account', description: 'Name, contact details, role, campus limits, active.', access: 'admin', params: idParams, body: loose, documented: { body: D.obj({ name: D.optStr, email: D.optStr, phoneNumber: D.optStr, role: D.optStr.describe('admin, supervisor, staff or user'), isActive: D.optBool, password: D.optStr.describe('Set a new password'), notificationPreference: D.optStr.describe('email, whatsapp or both'), twoFactorEnabled: D.optBool.describe('Only to turn it off'), scopedCampusIds: D.ids.optional().describe('Limit staff to these campuses (empty: all)') }), response: D.user }, v1: users.updateUser }); +v1Route({ method: 'delete', path: '/users/:id', tag: 'Accounts', summary: 'Delete an account', access: 'admin', params: idParams, documented: { response: D.message }, v1: users.deleteUser }); +v1Route({ method: 'post', path: '/users/:id/sessions/revoke', tag: 'Accounts', summary: 'Sign someone out everywhere', access: 'admin', params: idParams, body: loose, documented: { response: D.message }, v1: users.adminRevokeUserSessions }); +v1Route({ method: 'post', path: '/users/:id/anonymize', tag: 'Accounts', summary: 'Anonymise an account', description: 'Admins. Personal details are removed for good; payment records stay.', access: 'admin', params: idParams, body: loose, documented: { response: D.message }, v1: users.anonymizeUser }); + +// ─── Messaging an event's people ───────────────────────────────────────────── + +const toEvent = { campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()] }; +v1Route({ + method: 'get', path: '/event-listing', tag: 'Events', summary: 'Upcoming public events in full', + description: 'What the site\'s event lists show (ticket options, prices, early-bird tiers), not paged. `campus` (id or slug) and `series` (slug) narrow it. For a paged, slimmer list use GET /events.', + access: 'public', query: filters('campus', 'series'), documented: { response: z.array(D.event.extend({ eventOptions: z.array(D.eventOption).optional(), isSoldOut: D.optBool })) }, v1: events.getEvents, +}); +v1Route({ method: 'get', path: '/admin/events', tag: 'Events (staff)', summary: 'Every event, including deactivated ones', access: 'admin', documented: { response: z.array(D.event) }, v1: events.getAllEvents }); +v1Route({ method: 'post', path: '/events/:id/email-attendees', tag: 'Messaging', summary: 'Email an event\'s people', description: 'Filtered by status or chosen people; news consent is checked.', access: 'supervisor', ...toEvent, params: idParams, body: loose, documented: { body: emailAttendees, response: reach }, v1: events.emailEventAttendees }); +v1Route({ method: 'post', path: '/events/:id/email-attendees/schedule', tag: 'Messaging', summary: 'Schedule an email to an event\'s people', access: 'supervisor', ...toEvent, params: idParams, body: loose, documented: { body: emailAttendees.extend({ scheduledAt: D.date }), response: scheduled }, v1: events.scheduleEmailEventAttendees }); +v1Route({ method: 'post', path: '/events/:id/whatsapp-attendees', tag: 'Messaging', summary: 'WhatsApp an event\'s people', access: 'supervisor', ...toEvent, params: idParams, body: loose, documented: { body: whatsappAttendees, response: reach }, v1: events.whatsappEventAttendees }); +v1Route({ method: 'post', path: '/events/:id/whatsapp-attendees/schedule', tag: 'Messaging', summary: 'Schedule a WhatsApp to an event\'s people', access: 'supervisor', ...toEvent, params: idParams, body: loose, documented: { body: whatsappAttendees.extend({ scheduledAt: D.date }), response: scheduled }, v1: events.scheduleWhatsappEventAttendees }); + +for (const [channel, field, ctrl] of [['email', 'emails', bc], ['whatsapp', 'phones', wbc]] as const) { + const scope = { campusScope: `scopeBroadcast(freeform ${field})`, middleware: [cs.scopeBroadcast({ freeformField: field })] }; + const [preview, send, schedule] = channel === 'email' ? [ctrl.previewBroadcast, ctrl.sendBroadcast, ctrl.scheduleBroadcast] : [ctrl.previewWhatsAppBroadcast, ctrl.sendWhatsAppBroadcast, ctrl.scheduleWhatsAppBroadcast]; + const name = channel === 'email' ? 'an email' : 'a WhatsApp'; + const who = D.obj({ + userIds: D.ids.optional().describe('Chosen accounts'), + ...(channel === 'email' ? { emails: D.optStr.describe('Typed-in addresses, separated by commas or new lines') } : { phones: D.optStr.describe('Typed-in numbers, separated by commas or new lines') }), + eventId: D.optStr.describe('Everyone registered for this event'), kind: kind.optional().describe('Default news'), + }); + const content = channel === 'email' ? { subject: D.str, html: D.optStr, text: D.optStr } : { message: D.str }; + v1Route({ method: 'post', path: `/broadcasts/${channel}/preview`, tag: 'Messaging', summary: `Who ${name} broadcast would reach`, access: 'supervisor', ...scope, body: loose, documented: { body: who, response: reach.extend({ event: D.anyObj.nullish(), placeholders: z.array(D.str).optional() }) }, v1: preview }); + v1Route({ method: 'post', path: `/broadcasts/${channel}/send`, tag: 'Messaging', summary: `Send ${name} broadcast`, description: 'To campuses, events, roles or listed people; news consent is checked.', access: 'supervisor', ...scope, body: loose, documented: { body: who.extend(content), response: reach }, v1: send }); + v1Route({ method: 'post', path: `/broadcasts/${channel}/schedule`, tag: 'Messaging', summary: `Schedule ${name} broadcast`, access: 'supervisor', ...scope, body: loose, documented: { body: who.extend(content).extend({ scheduledAt: D.date }), response: scheduled }, v1: schedule }); +} +v1Route({ method: 'get', path: '/scheduled-messages', tag: 'Messaging', summary: 'Scheduled emails and WhatsApps', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('status', 'eventId', 'channel'), documented: { response: D.obj({ jobs: z.array(scheduledJob) }) }, v1: sched.listScheduledEmails }); +v1Route({ method: 'patch', path: '/scheduled-messages/:id', tag: 'Messaging', summary: 'Change a scheduled message', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], params: idParams, body: loose, documented: { body: D.obj({ scheduledAt: D.optDate, subject: D.optStr, html: D.optStr, text: D.optStr, message: D.optStr.describe('WhatsApp') }), response: D.obj({ message: D.str, job: scheduledJob }) }, v1: sched.updateScheduledEmail }); +v1Route({ method: 'delete', path: '/scheduled-messages/:id', tag: 'Messaging', summary: 'Cancel a scheduled message', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], params: idParams, documented: { response: D.message }, v1: sched.deleteScheduledEmail }); +v1Route({ + method: 'post', path: '/automations/schedule', tag: 'Messaging', summary: 'Schedule an event\'s reminder messages', + access: 'supervisor', campusScope: 'scopeEvent(body.eventId)', middleware: [cs.scopeEvent({ from: (req: any) => req.body?.eventId })], body: z.looseObject({ eventId: id }), documented: { body: D.obj({ eventId: D.str, jobs: z.array(D.obj({ scheduledAt: D.date, subject: D.str, html: D.optStr, text: D.optStr, audience: z.enum(['sponsors']).optional(), promoEventId: D.optStr })).min(1) }), response: D.obj({ message: D.str, jobs: z.array(D.anyObj) }) }, v1: auto.scheduleAutomations, +}); + +// ─── WhatsApp connection (admins) ──────────────────────────────────────────── + +v1Route({ method: 'get', path: '/whatsapp/config', tag: 'WhatsApp', summary: 'The WhatsApp connection settings', access: 'admin', documented: { response: D.obj({ tokenMasked: D.str, instanceId: D.str, hasToken: D.bool, hasInstance: D.bool, configured: D.bool, webhookUrl: D.optStr }) }, v1: wa.getConfigHandler }); +v1Route({ method: 'put', path: '/whatsapp/config', tag: 'WhatsApp', summary: 'Change the WhatsApp connection settings', access: 'admin', body: loose, documented: { body: D.obj({ token: D.optStr, instanceId: D.optStr }), response: D.message }, v1: wa.saveConfigHandler }); +v1Route({ method: 'post', path: '/whatsapp/instance', tag: 'WhatsApp', summary: 'Create the WhatsApp instance', access: 'admin', body: loose, documented: { body: D.obj({ name: D.optStr }), response: D.obj({ message: D.str }).describe('Plus what the WhatsApp service answered') }, v1: wa.createInstanceHandler }); +v1Route({ method: 'delete', path: '/whatsapp/instance', tag: 'WhatsApp', summary: 'Delete the WhatsApp instance', access: 'admin', documented: { response: D.obj({ message: D.str }).describe('Plus what the WhatsApp service answered') }, v1: wa.deleteInstanceHandler }); +v1Route({ method: 'get', path: '/whatsapp/status', tag: 'WhatsApp', summary: 'Is WhatsApp connected?', access: 'admin', documented: { response: D.anyObj.describe('The WhatsApp service\'s status answer') }, v1: wa.getStatusHandler }); +v1Route({ method: 'get', path: '/whatsapp/qr', tag: 'WhatsApp', summary: 'The QR code to link a phone', access: 'admin', documented: { response: D.anyObj.describe('The WhatsApp service\'s answer, with the QR code image') }, v1: wa.getQrHandler }); +for (const [action, summary, handler] of [['request-code', 'Link a phone with a code instead', wa.requestCodeHandler], ['logout', 'Unlink the phone', wa.logoutHandler], ['start', 'Start the WhatsApp session', wa.startHandler], ['restart', 'Restart the WhatsApp session', wa.restartHandler]] as const) { + v1Route({ + method: 'post', path: `/whatsapp/${action}`, tag: 'WhatsApp', summary, access: 'admin', body: loose, + documented: { body: action === 'request-code' ? D.obj({ phoneNumber: D.str }) : D.anyObj, response: D.anyObj.describe('The WhatsApp service\'s answer') }, + v1: handler, + }); +} + +// ─── Banner, saved filters, dashboards, stats, analytics, reports ──────────── + +v1Route({ method: 'get', path: '/banner', tag: 'Site', summary: 'The site-wide banner', access: 'public', documented: { response: bannerShape }, v1: banner.getBanner }); +v1Route({ method: 'put', path: '/banner', tag: 'Site', summary: 'Set the site-wide banner', access: 'supervisor', campusScope: 'unscopedOnly (admins and unscoped supervisors)', middleware: [cs.unscopedOnly], body: loose, documented: { body: bannerShape.partial().describe('An empty message takes the banner down'), response: bannerShape }, v1: banner.setBanner }); + +const OWN = 'campusIndependent (a person\'s own saved filters)'; +v1Route({ method: 'get', path: '/saved-filters', tag: 'Me', summary: 'My saved filters', description: 'For one list page (`page`).', access: 'staff', campusScope: OWN, query: filters('page'), documented: { response: z.array(savedFilter) }, v1: savedFilterRouter, map: ctx => ({ url: `/${qs(ctx.req)}` }) }); +v1Route({ method: 'post', path: '/saved-filters', tag: 'Me', summary: 'Save a filter', description: 'By name (replaces one with the same name); up to 30 per page.', access: 'staff', campusScope: OWN, body: loose, documented: { body: D.obj({ page: D.str, name: D.str, params: D.anyObj, isDefault: D.optBool }), response: savedFilter }, v1: savedFilterRouter, map: () => ({ url: '/' }) }); +v1Route({ method: 'put', path: '/saved-filters/:id', tag: 'Me', summary: 'Change a saved filter', access: 'staff', campusScope: OWN, params: idParams, body: loose, documented: { body: D.obj({ name: D.optStr, params: D.anyObj.optional(), isDefault: D.optBool }), response: savedFilter }, v1: savedFilterRouter, map: ctx => ({ url: `/${encodeURIComponent(ctx.params.id)}` }) }); +v1Route({ method: 'delete', path: '/saved-filters/:id', tag: 'Me', summary: 'Delete a saved filter', access: 'staff', campusScope: OWN, params: idParams, documented: { response: D.ok }, v1: savedFilterRouter, map: ctx => ({ url: `/${encodeURIComponent(ctx.params.id)}` }) }); +v1Route({ method: 'get', path: '/dashboard/today', tag: 'Dashboard', summary: 'Today at a glance', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], documented: { response: D.obj({ events: z.array(D.obj({ id: D.str, title: D.str, startsAt: D.date, endsAt: D.date, sessionLabel: D.optStr, places: D.num, checkedIn: D.num })).describe('Today\'s events with places and check-ins'), money: D.obj({ today: D.rand, todayCount: D.num, week: D.rand }).nullish(), pending: z.array(D.obj({ key: D.str, label: D.str, count: D.num, href: D.str, tone: D.optStr })).describe('What\'s waiting for you') }) }, v1: dashboardRouter, map: ctx => ({ url: `/today${qs(ctx.req)}` }) }); +v1Route({ method: 'get', path: '/dashboard/search', tag: 'Dashboard', summary: 'Search people, registrations and events', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('q'), documented: { response: D.obj({ results: z.array(D.obj({ type: D.str.describe('event, payment, person, registration'), id: D.str, title: D.str, subtitle: D.optStr, href: D.optStr })) }) }, v1: dashboardRouter, map: ctx => ({ url: `/search${qs(ctx.req)}` }) }); +v1Route({ method: 'get', path: '/stats/staff', tag: 'Dashboard', summary: 'Staff dashboard numbers', access: 'staff', campusScope: SCOPE_LIST, middleware: [cs.scopeList], documented: { response: D.obj({ scanStats, recentScans: z.array(D.anyObj) }) }, v1: stats.getStaffDashboardStats }); +v1Route({ method: 'get', path: '/stats/supervisor', tag: 'Dashboard', summary: 'Supervisor dashboard numbers', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], documented: { response: D.obj({ scanStats, recentScans: z.array(D.anyObj), paymentStats: D.anyObj, activeEventsCount: D.num }) }, v1: stats.getSupervisorDashboardStats }); +v1Route({ method: 'get', path: '/stats/admin', tag: 'Dashboard', summary: 'Admin dashboard numbers', access: 'admin', documented: { response: D.obj({ scanStats, recentScans: z.array(D.anyObj), paymentStats: D.anyObj, activeEventsCount: D.num }) }, v1: stats.getAdminDashboardStats }); +v1Route({ method: 'get', path: '/stats/overview', tag: 'Dashboard', summary: 'Overview numbers', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('from', 'to', 'campus'), documented: { response: D.obj({ funnel: D.anyObj.nullish(), activeEvents: D.num, registrations: monthly, ticketsSold: monthly, revenue: monthly, donations: monthly, trend: z.array(D.obj({ date: D.str, revenue: D.rand })), topEvents: z.array(D.obj({ eventId: D.str, title: D.str, revenue: D.rand, registrations: D.num, ticketsSold: D.num })) }) }, v1: stats.getOverviewStats }); +const trackLimiter = rateLimit({ windowMs: 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false }); +v1Route({ method: 'post', path: '/analytics/track', tag: 'Dashboard', summary: 'Record a step on the way to registering', access: 'public', middleware: [trackLimiter], body: loose, documented: { body: D.obj({ sessionId: D.str.describe('The browser\'s analytics id'), eventId: D.str, stage: z.enum(['view', 'start', 'submit', 'paid']), source: D.optStr.describe('Where they came from') }), response: z.null().describe('Always 204, no content') }, v1: analytics.trackStage }); +v1Route({ method: 'get', path: '/analytics/funnel', tag: 'Dashboard', summary: 'How many get from viewing to paying', access: 'supervisor', campusScope: SCOPE_LIST, middleware: [cs.scopeList], query: filters('eventIds', 'eventId', 'from', 'to'), documented: { response: D.obj({ perEvent: z.array(D.anyObj).describe('The same for each event') }).describe('Counts per stage (view, start, submit, paid), sources and devices, and per ticket') }, v1: analytics.getFunnel }); +v1Route({ method: 'post', path: '/reports/pdf', tag: 'Reports', summary: 'A report as a PDF', description: 'The report\'s rows and columns in the body.', access: 'user', body: loose, file: { contentType: 'application/pdf' }, documented: { body: reportBody }, v1: reports.generatePdf }); +v1Route({ method: 'post', path: '/reports/excel', tag: 'Reports', summary: 'A report as an Excel file', access: 'user', body: loose, file: { contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }, documented: { body: reportBody }, v1: reports.generateExcel }); +v1Route({ method: 'post', path: '/reports/email', tag: 'Reports', summary: 'Email a report as a PDF', access: 'user', body: loose, documented: { body: reportBody.extend({ subject: D.optStr, body: D.optStr.describe('Text of the email') }), response: D.message }, v1: reports.emailPdf }); +v1Route({ method: 'post', path: '/reports/whatsapp', tag: 'Reports', summary: 'WhatsApp a report as a PDF', access: 'user', body: loose, documented: { body: reportBody.extend({ caption: D.optStr }), response: D.message }, v1: reports.whatsappPdf }); diff --git a/apps/events/backend/src/v2/resources/registrations.ts b/apps/events/backend/src/v2/resources/registrations.ts new file mode 100644 index 0000000..e2124c4 --- /dev/null +++ b/apps/events/backend/src/v2/resources/registrations.ts @@ -0,0 +1,187 @@ +import { z } from 'zod'; +import { defineRoute, type ApiUser } from '../route'; +import { ApiError, notFound } from '../errors'; +import { single } from '../paging'; +import { eventRef, id, idParams, iso, isoDate } from '../schemas'; +import { prisma, computeRegistrationTotalDue } from '../legacy'; +import { createRegistration, cancelRegistration } from '../../services/registrations'; +import { startRegistrationCheckout } from '../../services/payments'; + +const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const; + +/** A registration as v2 shows it to its owner. Also used by GET /me/registrations. */ +export const registrationSummary = z.object({ + id, + status: z.enum(STATUSES), + createdAt: isoDate, + event: eventRef, + items: z.array(z.object({ + ticket: z.string(), + variant: z.string().nullable(), + quantity: z.number().int(), + unitPrice: z.number(), + })), + totalDue: z.number().describe('In rand, after discounts'), + amountPaid: z.number().describe('In rand (refunds subtracted)'), + balance: z.number().describe('totalDue − amountPaid; 0 or less = nothing owing'), +}); + +const r2 = (n: number) => Math.round(n * 100) / 100; + +export const SUMMARY_INCLUDE = { + event: { select: { id: true, title: true, startDate: true, endDate: true } }, + registrationOptions: { include: { eventOption: { include: { earlyBirdTiers: true } }, variant: { select: { name: true, price: true } }, tranches: true } }, + payments: { select: { amount: true, createdAt: true } }, +} as const; + +type SummaryRow = { + id: string; status: (typeof STATUSES)[number]; createdAt: Date; + event: { id: string; title: string; startDate: Date; endDate: Date }; + registrationOptions: { quantity: number; priceSnapshot: number | null; eventOption: { name: string; price: number } | null; variant: { name: string } | null }[]; + payments: { amount: number }[]; +}; + +export function toSummary(r: SummaryRow, now = new Date()): z.input { + const totalDue = r2(computeRegistrationTotalDue(r, now)); + const amountPaid = r2(r.payments.reduce((s, p) => s + p.amount, 0)); + return { + id: r.id, + status: r.status, + createdAt: iso(r.createdAt), + event: { id: r.event.id, title: r.event.title, startDate: iso(r.event.startDate), endDate: iso(r.event.endDate) }, + items: r.registrationOptions.map(o => ({ ticket: o.eventOption?.name ?? '', variant: o.variant?.name ?? null, quantity: o.quantity, unitPrice: o.priceSnapshot ?? o.eventOption?.price ?? 0 })), + totalDue, + amountPaid, + balance: r2(totalDue - amountPaid), + }; +} + +/** The owner's registration (admins may see anyone's); others get NOT_FOUND, not a hint it exists. */ +async function ownRegistration(registrationId: string, user: ApiUser) { + const r = await prisma.registration.findUnique({ where: { id: registrationId }, include: SUMMARY_INCLUDE }); + if (!r || (r.userId !== user.id && user.role !== 'admin')) throw notFound('That registration'); + return r; +} + +const attendee = z.object({ + eventOptionId: id, + variantId: id.nullish(), + name: z.string().trim().min(1).max(200), + email: z.string().trim().max(200).nullish(), + phone: z.string().trim().max(40).nullish(), + dateOfBirth: z.string().max(40).nullish().describe('YYYY-MM-DD (youth events)'), + gender: z.string().max(20).nullish(), + parentName: z.string().max(200).nullish(), + parentEmail: z.string().max(200).nullish(), + parentPhone: z.string().max(40).nullish(), +}); + +export const register = defineRoute({ + method: 'post', + path: '/registrations', + tag: 'Registrations', + summary: 'Register for an event', + description: [ + 'Signed in, or as a guest for a free event that allows it (`guest` then required), or with a waitlist link (`waitlistToken`).', + 'Registering again for the same event adds to the existing registration. When nothing is owed it is marked paid and tickets are issued; otherwise pay with `POST /registrations/{id}/checkout`.', + 'A coupon that was valid when checked but used up a moment later is reported in `couponError`; the registration is still made.', + ].join('\n\n'), + access: 'optional', + status: 201, + body: z.object({ + eventId: id, + options: z.array(z.object({ + eventOptionId: id, + quantity: z.number().int().min(1).max(1000), + variantId: id.nullish(), + sessionIds: z.array(id).max(200).optional().describe('"Pick sessions" tickets: the sessions chosen'), + })).min(1).max(50), + guest: z.object({ name: z.string().trim().min(1).max(200), email: z.email().max(200), phone: z.string().trim().max(40).optional() }).optional(), + couponCode: z.string().trim().max(60).optional(), + attendees: z.array(attendee).max(500).optional().describe('Names for the places (events that collect them)'), + ticketDelivery: z.enum(['payer', 'each']).optional().describe('With attendees: tickets to the payer, or to each attendee'), + waitlistToken: z.string().max(200).optional(), + analyticsSessionId: z.string().max(100).optional(), + }), + response: single(registrationSummary.extend({ + isNew: z.boolean().describe('false = added to an existing registration'), + couponError: z.string().nullable(), + })), + async handler({ body, user }) { + const { registration, isNew, couponError } = await createRegistration({ + eventId: body.eventId, + options: body.options.map(o => ({ ...o, variantId: o.variantId ?? null })), + guestName: body.guest?.name, + guestEmail: body.guest?.email, + guestPhone: body.guest?.phone, + couponCode: body.couponCode, + attendees: body.attendees, + ticketDelivery: body.ticketDelivery, + waitlistToken: body.waitlistToken, + analyticsSessionId: body.analyticsSessionId, + }, user ? { id: user.id, role: user.role, email: user.email } : null); + const fresh = await prisma.registration.findUniqueOrThrow({ where: { id: registration.id }, include: SUMMARY_INCLUDE }); + return { data: { ...toSummary(fresh), isNew, couponError } }; + }, +}); + +export const getRegistration = defineRoute({ + method: 'get', + path: '/registrations/:id', + tag: 'Registrations', + summary: 'One of my registrations', + access: 'user', + params: idParams, + response: single(registrationSummary), + async handler({ params, user }) { + return { data: toSummary(await ownRegistration(params.id, user!)) }; + }, +}); + +export const cancel = defineRoute({ + method: 'post', + path: '/registrations/:id/cancel', + tag: 'Registrations', + summary: 'Cancel my registration', + description: 'Not after the event has ended, and not once anything has been paid (the church can do that). Its places go to the waitlist.', + access: 'user', + params: idParams, + response: single(registrationSummary), + async handler({ params, user, req }) { + await ownRegistration(params.id, user!); + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + await cancelRegistration(params.id, user!, getClientIp(req)); + return { data: toSummary(await ownRegistration(params.id, user!)) }; + }, +}); + +export const checkout = defineRoute({ + method: 'post', + path: '/registrations/:id/checkout', + tag: 'Registrations', + summary: 'Pay what I owe online', + description: [ + 'Starts a payment with the church\'s provider (Yoco or PayFast) and returns where to send the person (`redirectUrl`).', + 'If an early-bird price ran out since the registration was made, nothing is started: `priceUpdated` is true with the new amount owing — show it, then call again.', + ].join('\n\n'), + access: 'user', + params: idParams, + body: z.object({ + donationAmount: z.number().min(0).max(100000).optional().describe('An optional donation added on top, in rand'), + provider: z.string().max(40).optional().describe('yoco or payfast (default: the first one switched on)'), + successUrl: z.url().max(2000).optional(), + cancelUrl: z.url().max(2000).optional(), + failureUrl: z.url().max(2000).optional(), + }), + response: single(z.discriminatedUnion('priceUpdated', [ + z.object({ priceUpdated: z.literal(true), newBalance: z.number(), message: z.string() }), + z.object({ priceUpdated: z.literal(false), checkoutId: z.string(), redirectUrl: z.string(), provider: z.string(), amount: z.number().describe('Charged now, in rand (with any donation)') }), + ])), + async handler({ params, body, user }) { + await ownRegistration(params.id, user!); + const result = await startRegistrationCheckout(params.id, user!, body); + if (result.priceUpdated) return { data: { priceUpdated: true as const, newBalance: result.newTotal, message: result.message } }; + if (!result.redirectUrl) throw new ApiError('INTERNAL', 'The payment provider did not return a payment page.'); + return { data: { priceUpdated: false as const, checkoutId: result.checkoutId, redirectUrl: result.redirectUrl, provider: result.provider, amount: result.amount } }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/registrationsManage.ts b/apps/events/backend/src/v2/resources/registrationsManage.ts new file mode 100644 index 0000000..6f731f8 --- /dev/null +++ b/apps/events/backend/src/v2/resources/registrationsManage.ts @@ -0,0 +1,225 @@ +import { z } from 'zod'; +import * as D from '../docs'; +import type { Request } from 'express'; +import { defineRoute, type ApiUser } from '../route'; +import { pageOf, single } from '../paging'; +import { id, idParams } from '../schemas'; +import * as admin from '../../services/registrationAdmin'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- registrations are passed through with their includes */ +const campusScope = require('../../utils/campusScope') as { + listWhere(req: unknown, path?: string): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown; ownerOk?: boolean }): any; + scopeBody(targets: [string, string][], opts?: { need?: 'view' | 'manage'; orphan?: 'pass' | 'deny' }): any; +}; +const { notOnSeasonPass } = require('../../utils/seasonPass') as { notOnSeasonPass: any }; +const plain = (v: T): any => JSON.parse(JSON.stringify(v)); + +/** The v2 request as the registration service's Call. */ +function callFrom(req: Request, user: ApiUser | null, parts: { params?: object; body?: object; query?: object }): admin.Call { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { + actor: user ? { id: user.id, role: user.role, email: user.email } : null, + params: (parts.params ?? {}) as Record, + body: parts.body ?? {}, + query: parts.query ?? {}, + readOnly: !!(req as any).readOnly, + ip: getClientIp(req), + listWhere: () => campusScope.listWhere(req, 'event'), + }; +} + +const OWNER_OR_STAFF = 'scopeEvent(registration, owner-ok)'; +const ownerOrStaff = campusScope.scopeEvent({ resolve: 'registration', ownerOk: true }); +const STATUSES = ['pending', 'confirmed', 'partial_paid', 'paid', 'cancelled'] as const; + +/** A registration with everything the dashboards show: items and their prices, payments, attendees, coupons, `totalDueComputed`. */ +const fullRegistration = z.looseObject({ id, status: z.enum(STATUSES), eventId: id, userId: id, totalDueComputed: z.number().optional() }); +const message = single(z.looseObject({ message: z.string() })); +const lineBody = z.object({ eventOptionId: id, variantId: id.nullish(), quantity: z.number().int().min(1).max(1000), sessionIds: z.array(id).max(200).optional() }); +const attendeeBody = z.looseObject({ id: id.optional().describe('An attendee already on it (left out = removed)'), eventOptionId: id, variantId: id.nullish(), name: z.string().max(200) }); +const responsesBody = z.object({ + responses: z.array(z.object({ + attendeeId: id.nullish().describe('The named attendee this form is for'), + answers: z.record(z.string(), z.unknown()).describe('Field id → answer (stored as text)'), + })).max(500), +}); + +// ─── Owner (or staff) ──────────────────────────────────────────────────────── + +export const fullOne = defineRoute({ + method: 'get', path: '/registrations/:id/full', tag: 'Registrations', summary: 'A registration with everything on it', + description: [ + 'Items and prices, payments, coupons and bundles, named attendees, form answers and the total due.', + 'The owner, a named attendee or staff — or anyone with the link when not signed in (registration ids can\'t be guessed). Attendees\' contact details are only shown to the payer and staff.', + ].join('\n\n'), + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, response: single(fullRegistration), + async handler({ params, user, req }) { return { data: plain(await admin.getRegistrationById(callFrom(req, user, { params }))) }; }, +}); + +export const myFull = defineRoute({ + method: 'get', path: '/me/registrations/full', tag: 'Me', summary: 'My registrations with everything on them', + description: 'What the dashboard shows: as `/registrations/{id}/full`, newest first, with the event and its form. Only upcoming ones unless `past=true`.', + access: 'user', + query: z.object({ past: z.enum(['true', 'false']).default('false') }), + response: z.object({ data: z.array(fullRegistration) }), + async handler({ query, user, req }) { return { data: plain(await admin.getUserRegistrations(callFrom(req, user, { query: { showPast: query.past } }))) }; }, +}); + +export const changeItems = defineRoute({ + method: 'put', path: '/registrations/:id/items', tag: 'Registrations', summary: 'Change the tickets on a registration', + description: [ + 'The whole list of items it should have. Added places need stock and are priced now; places already paid for keep their price, and nothing goes below tickets already issued or the amount paid.', + 'Not for registrations made with a season pass, nor once the event has ended or is closed. Staff can add kids and volunteer places; owners can only keep or lower them.', + ].join('\n\n'), + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, + body: z.object({ options: z.array(lineBody.omit({ sessionIds: true })).min(1).max(100) }), response: single(fullRegistration), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationOptions(callFrom(req, user, { params, body }))) }; }, +}); + +export const sendInvoice = defineRoute({ + method: 'post', path: '/registrations/:id/invoice', tag: 'Registrations', summary: 'Send me the invoice again', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ channel: z.enum(['email', 'whatsapp']).default('email') }), response: message, + async handler({ params, body, user, req }) { return { data: await admin.sendInvoice(callFrom(req, user, { params, body })) }; }, +}); + +export const applyCoupon = defineRoute({ + method: 'post', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Apply a coupon code', + description: 'By the owner, or by staff on their behalf (logged). Not on season pass registrations.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff, notOnSeasonPass], params: idParams, + body: z.object({ code: z.string().trim().min(1).max(40) }), response: single(fullRegistration.extend({ message: z.string() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.applyCoupon(callFrom(req, user, { params, body }))) }; }, +}); + +export const removeCoupon = defineRoute({ + method: 'delete', path: '/registrations/:id/coupon', tag: 'Registrations', summary: 'Take a coupon code off', + description: 'Staff. Its use is freed. Not once a ticket on it has been scanned; unused tickets are withdrawn if it\'s no longer paid.', + access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, response: message, + async handler({ params, user, req }) { return { data: await admin.removeCoupon(callFrom(req, user, { params })) }; }, +}); + +export const setAttendees = defineRoute({ + method: 'put', path: '/registrations/:id/attendees', tag: 'Registrations', summary: 'Name the people on a registration', + description: 'The whole list: attendees left out are removed (not once their ticket has been scanned). `ticketDelivery` says who gets the tickets.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ attendees: z.array(attendeeBody).max(1000), ticketDelivery: z.enum(['payer', 'each']).optional() }), + response: single(z.looseObject({ id, ticketDelivery: z.string().nullable(), attendees: z.array(z.looseObject({ id, name: z.string() })) })), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateAttendees(callFrom(req, user, { params, body }))) }; }, +}); + +export const sendFormLink = defineRoute({ + method: 'post', path: '/registrations/:id/attendees/:attendeeId/form-link', tag: 'Registrations', summary: 'Send an attendee their form', + description: 'A link to fill in their own attendee form, by email and/or WhatsApp.', + access: 'user', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: z.object({ id, attendeeId: id }), response: message, + async handler({ params, user, req }) { return { data: await admin.sendAttendeeFormLink(callFrom(req, user, { params })) }; }, +}); + +export const getDraft = defineRoute({ + method: 'get', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Attendee forms saved part-way', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + response: single(z.object({ data: z.record(z.string(), z.unknown()), updatedAt: z.string().nullable() })), + async handler({ params, user, req }) { return { data: plain(await admin.getFormDraft(callFrom(req, user, { params }))) }; }, +}); + +export const saveDraft = defineRoute({ + method: 'put', path: '/registrations/:id/form-draft', tag: 'Registrations', summary: 'Save attendee forms part-way', + description: 'Kept for the registration\'s owner (also when staff save it), until the forms are submitted.', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, + body: z.object({ data: z.record(z.string(), z.unknown()) }), response: single(z.object({ message: z.string(), updatedAt: z.string() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.saveFormDraft(callFrom(req, user, { params, body }))) }; }, +}); + +export const submitForms = defineRoute({ + method: 'post', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Submit attendee forms', + description: 'One response per main ticket at most; each named attendee answers once. Tickets are issued once it\'s paid and the forms are in.', + access: 'optional', campusScope: OWNER_OR_STAFF, middleware: [ownerOrStaff], params: idParams, body: responsesBody, + response: single(z.looseObject({ message: z.string(), count: z.number().int().optional() })), + async handler({ params, body, user, req }) { return { data: plain(await admin.submitFormResponses(callFrom(req, user, { params, body }))) }; }, +}); + +export const replaceForms = defineRoute({ + method: 'put', path: '/registrations/:id/form-responses', tag: 'Registrations', summary: 'Replace the attendee forms', + description: 'Supervisors: every response on the registration is replaced by these.', + access: 'supervisor', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, body: responsesBody, response: message, + async handler({ params, body, user, req }) { return { data: await admin.replaceFormResponses(callFrom(req, user, { params, body })) }; }, +}); + +// ─── Staff ─────────────────────────────────────────────────────────────────── + +export const list = defineRoute({ + method: 'get', path: '/registrations', tag: 'Registrations', summary: 'Every registration (staff)', + description: 'Newest first, for the events you may see. `unpaid=true` for ones still owing; `userId` for one person\'s.', + access: 'staff', campusScope: 'scopeList (listWhere)', + query: z.object({ + page: z.coerce.number().int().min(1).default(1), + limit: z.coerce.number().int().min(1).max(200).default(100).describe('At most 200'), + unpaid: z.enum(['true', 'false']).default('false'), + userId: id.optional(), + }), + response: z.object({ data: z.array(fullRegistration), meta: z.object({ page: z.number().int(), limit: z.number().int(), total: z.number().int(), pages: z.number().int() }) }), + async handler({ query, user, req }) { + const out = await admin.getRegistrations(callFrom(req, user, { query: { page: String(query.page), limit: String(query.limit), unpaid: query.unpaid === 'true' ? '1' : '', userId: query.userId } })); + return pageOf(plain(out.data), out.total, { page: out.page, limit: out.limit }); + }, +}); + +export const forEvent = defineRoute({ + method: 'get', path: '/events/:id/registrations', tag: 'Registrations', summary: 'An event\'s registrations', + description: 'Oldest first, with tickets, payments and attendees. `search` matches the name, email or phone.', + access: 'staff', campusScope: 'scopeEvent(view)', middleware: [campusScope.scopeEvent()], params: idParams, + query: z.object({ search: z.string().max(200).optional() }), + response: z.object({ data: z.array(fullRegistration) }), + async handler({ params, query, user, req }) { return { data: plain(await admin.getRegistrationsByEvent(callFrom(req, user, { params: { eventId: params.id }, query }))) }; }, +}); + +export const setStatus = defineRoute({ + method: 'patch', path: '/registrations/:id/status', tag: 'Registrations', summary: 'Set a registration\'s status', + description: 'Staff. `paid` issues and sends the tickets; leaving `paid` withdraws unused tickets (refused once one has been scanned); `cancelled` frees its places for the waitlist.', + access: 'staff', campusScope: 'scopeEvent(registration)', middleware: [campusScope.scopeEvent({ resolve: 'registration' })], params: idParams, + body: z.object({ status: z.enum(STATUSES) }), response: single(fullRegistration), + async handler({ params, body, user, req }) { return { data: plain(await admin.updateRegistrationStatus(callFrom(req, user, { params, body }))) }; }, +}); + +export const manual = defineRoute({ + method: 'post', path: '/registrations/manual', tag: 'Registrations', summary: 'Register someone (at the door, by phone)', + description: [ + 'Supervisors. Finds the person by email or phone (refused when those are two different accounts) or makes an account and sends them an activation link (`skipActivationNotice` to not).', + 'Added to their existing registration for the event if they have one. Free ones are marked paid and get their tickets; otherwise they\'re sent a link to pay.', + ].join('\n\n'), + access: 'supervisor', campusScope: 'scopeEvent(body.eventId)', middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId })], status: 201, + body: z.looseObject({ + eventId: id, + options: z.array(lineBody).min(1).max(100), + user: z.looseObject({ name: z.string().trim().min(1).max(200), email: z.string().max(200).nullish(), phoneNumber: z.string().max(40).nullish(), password: z.string().max(200).optional().describe('Self-service kiosk: the visitor sets it, and the account is active at once') }), + notificationPreference: z.string().max(20).nullish().describe('email, whatsapp or both (anything else: worked out from the contact details given)'), + skipActivationNotice: z.boolean().optional(), + couponCode: z.string().max(40).nullish(), + attendees: z.array(attendeeBody).max(1000).optional(), + ticketDelivery: z.enum(['payer', 'each']).optional(), + }), + response: single(fullRegistration.extend({ couponError: z.string().optional() })), + async handler({ body, user, req }) { return { data: plain(await admin.createManualRegistration(callFrom(req, user, { body }))) }; }, +}); + +export const bulk = defineRoute({ + method: 'post', path: '/registrations/bulk', tag: 'Registrations', summary: 'Do one thing to many registrations', + description: '`markPaid`, `cancel`, `moveOption`, `allocate` or `message`, for up to 500 you may manage. Each is done on its own: the answer lists what worked and what didn\'t.', + access: 'supervisor', campusScope: 'scopeBody(registrationIds, deny orphans)', middleware: [campusScope.scopeBody([['registrationIds', 'registration']], { orphan: 'deny' })], + body: z.looseObject({ action: z.enum(['markPaid', 'cancel', 'moveOption', 'allocate', 'message']), registrationIds: z.array(id).min(1).max(500) }), + response: single(z.looseObject({})), + documented: { + body: D.obj({ + action: z.enum(['markPaid', 'cancel', 'moveOption', 'allocate', 'message']), registrationIds: z.array(id).min(1).max(500), + method: D.optStr.describe('markPaid: cash, eft, card or other'), paidAt: D.optDate.describe('markPaid'), + fromOptionId: D.optStr.describe('moveOption'), toOptionId: D.optStr.describe('moveOption'), + setId: D.optStr.describe('allocate'), groupId: D.optStr.describe('allocate'), + channel: z.enum(['email', 'whatsapp']).optional().describe('message'), subject: D.optStr.describe('message (email)'), text: D.optStr.describe('message'), + }), + response: D.obj({ action: D.str, done: D.num, skipped: D.num, failed: D.num, results: z.array(D.obj({ id: D.str, ok: D.bool, skipped: D.optBool, message: D.optStr })) }), + }, + async handler({ body, req }) { + const { runBulk } = require('../../utils/bulkRegistrations') as { runBulk(req: unknown, body: object): Promise }; + return { data: plain(await runBulk(req, body)) }; + }, +}); diff --git a/apps/events/backend/src/v2/resources/seriesDeals.ts b/apps/events/backend/src/v2/resources/seriesDeals.ts new file mode 100644 index 0000000..7f639a2 --- /dev/null +++ b/apps/events/backend/src/v2/resources/seriesDeals.ts @@ -0,0 +1,369 @@ +import { z } from 'zod'; +import * as D from '../docs'; +import type { Request } from 'express'; +import { defineRoute, type ApiUser } from '../route'; +import { single } from '../paging'; +import { absoluteUrl, id, idParams, isoDate } from '../schemas'; +import * as series from '../../services/series'; +import * as deals from '../../services/deals'; +import * as campuses from '../../services/campuses'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */ +const campusScope = require('../../utils/campusScope') as { + scopeFor(req: unknown): Promise; + listWhere(req: unknown, path?: string): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; +}; +const plain = (v: T): any => JSON.parse(JSON.stringify(v)); +const ctxOf = async (req: Request) => { + const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; + return { scope: await campusScope.scopeFor(req), ip: getClientIp(req) }; +}; +const actorOf = (user: ApiUser | null) => ({ id: user!.id, role: user!.role, email: user!.email }); +const deleted = single(z.object({ id, deleted: z.literal(true) })); +const SPANS = 'campusIndependent (a series spans campuses; events are checked when they join it)'; + +// ─── Series ────────────────────────────────────────────────────────────────── + +const seriesRecord = z.looseObject({ id, name: z.string(), slug: z.string(), description: z.string().nullable(), picture: z.string().nullable() }); +const seriesBody = z.object({ + name: z.string().trim().min(1).max(120), + slug: z.string().trim().max(80).optional().describe('The web address part (/series/); made from the name when left out'), + description: z.string().max(5000).nullable().optional(), + picture: z.string().max(500).nullable().optional(), +}); + +export const listSeries = defineRoute({ + method: 'get', path: '/series', tag: 'Series', summary: 'Every series', + description: 'With its events (the ones you may see — a series spans campuses), followers and event count.', + access: 'supervisor', campusScope: 'filters each series\' events by campus (listSeries)', + response: z.object({ data: z.array(seriesRecord.extend({ followers: z.number().int(), eventCount: z.number().int(), events: z.array(z.looseObject({ id, title: z.string(), startDate: isoDate })) })) }), + async handler({ req }) { return { data: plain(await series.listSeries(await ctxOf(req))) }; }, +}); + +export const createSeries = defineRoute({ + method: 'post', path: '/series', tag: 'Series', summary: 'Create a series', + access: 'supervisor', campusScope: SPANS, status: 201, body: seriesBody, response: single(seriesRecord), + async handler({ body, user, req }) { return { data: plain(await series.createSeries(body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const updateSeries = defineRoute({ + method: 'patch', path: '/series/:id', tag: 'Series', summary: 'Change a series', + access: 'supervisor', campusScope: SPANS, params: idParams, body: seriesBody.partial(), response: single(seriesRecord), + async handler({ params, body, user, req }) { return { data: plain(await series.updateSeries(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const deleteSeries = defineRoute({ + method: 'delete', path: '/series/:id', tag: 'Series', summary: 'Delete a series', + description: 'Admins. Its events stay (without a series) and followers are dropped. Not once season passes have been sold.', + access: 'admin', params: idParams, response: deleted, + async handler({ params, user, req }) { await series.deleteSeries(params.id, actorOf(user), await ctxOf(req)); return { data: { id: params.id, deleted: true as const } }; }, +}); + +export const seriesPage = defineRoute({ + method: 'get', path: '/series/by-slug/:slug', tag: 'Series', summary: 'A series\' public page', + description: 'Upcoming and past public events, season passes on sale, and whether you follow it.', + access: 'optional', params: z.object({ slug: z.string().min(1).max(80) }), + response: single(seriesRecord.extend({ upcoming: z.array(z.looseObject({ id })), past: z.array(z.looseObject({ id })), following: z.boolean(), passes: z.array(z.looseObject({ id, name: z.string(), price: z.number() })) })), + async handler({ params, user, req }) { + const page = plain(await series.seriesPage(params.slug, user?.id ?? null)); + return { data: { ...page, picture: absoluteUrl(req, page.picture) } }; + }, +}); + +export const compareSeries = defineRoute({ + method: 'get', path: '/series/:id/compare', tag: 'Series', summary: 'Year on year', + description: 'Registrations, tickets, income and attendance for each event in the series that you may see, oldest first.', + access: 'supervisor', campusScope: 'scopeList (eventWhere in compareSeries)', params: idParams, response: single(z.looseObject({})), + documented: { response: D.obj({ series: D.anyObj, events: z.array(D.obj({ eventId: D.str, title: D.str, startDate: D.date, endDate: D.date, campus: D.anyObj.nullish(), isActive: D.bool, sessions: D.optNum, registrations: D.num, tickets: D.num, income: D.rand, checkedIn: D.num, attendanceRate: D.optNum.describe('%'), change: D.obj({ registrations: D.optNum.describe('% change from the year before'), tickets: D.optNum.describe('% change from the year before'), income: D.optNum.describe('% change from the year before'), checkedIn: D.optNum.describe('% change from the year before') }).nullable() })) }) }, + async handler({ params, req }) { return { data: plain(await series.compareSeries(params.id, await ctxOf(req))) }; }, +}); + +export const follow = defineRoute({ + method: 'put', path: '/series/:id/follow', tag: 'Series', summary: 'Follow a series', + description: 'Hear about new events in it (News & announcements).', + access: 'user', params: idParams, response: single(z.object({ following: z.boolean() })), + async handler({ params, user }) { return { data: await series.setFollowing(params.id, user!.id, true) }; }, +}); + +export const unfollow = defineRoute({ + method: 'delete', path: '/series/:id/follow', tag: 'Series', summary: 'Stop following a series', + access: 'user', params: idParams, response: single(z.object({ following: z.boolean() })), + async handler({ params, user }) { return { data: await series.setFollowing(params.id, user!.id, false) }; }, +}); + +// ─── Season passes ─────────────────────────────────────────────────────────── + +const pass = z.looseObject({ id, seriesId: id, name: z.string(), price: z.number(), isActive: z.boolean(), items: z.array(z.looseObject({ eventId: id })) }); +const passBody = z.looseObject({ + seriesId: id, + name: z.string().trim().min(1).max(120), + description: z.string().max(5000).nullable().optional(), + price: z.union([z.number().min(0), z.string().max(20)]), + saleEndsAt: z.string().max(40).nullable().optional(), + isActive: z.boolean().optional(), + items: z.array(z.object({ eventId: id, eventOptionId: id, variantId: id.nullable().optional() })).min(1).max(100), +}); + +export const listPasses = defineRoute({ + method: 'get', path: '/season-passes', tag: 'Series', summary: 'Season passes', + description: 'With their events, how the price is shared between them, and how many were sold or are unpaid.', + access: 'supervisor', campusScope: SPANS, query: z.object({ seriesId: id.optional() }), + response: z.object({ data: z.array(pass.extend({ sold: z.number().int(), unpaid: z.number().int() })) }), + async handler({ query }) { return { data: plain(await series.listPasses(query.seriesId)) }; }, +}); + +export const createPass = defineRoute({ + method: 'post', path: '/season-passes', tag: 'Series', summary: 'Create a season pass', + description: 'One price for several events in a series. Campus-scoped supervisors can only include their own campuses\' events.', + access: 'supervisor', campusScope: 'checked in createPass (its events\' campuses)', status: 201, body: passBody, response: single(pass), + async handler({ body, user, req }) { return { data: plain(await series.createPass(body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const updatePass = defineRoute({ + method: 'patch', path: '/season-passes/:id', tag: 'Series', summary: 'Change a season pass', + description: 'Its events and price can\'t change once somebody has bought it (switch it off and make a new one).', + access: 'supervisor', campusScope: 'checked in updatePass (its events\' campuses)', params: idParams, body: passBody.partial(), response: single(pass), + async handler({ params, body, user, req }) { return { data: plain(await series.updatePass(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const deletePass = defineRoute({ + method: 'delete', path: '/season-passes/:id', tag: 'Series', summary: 'Delete a season pass', + description: 'Only one nobody has bought — otherwise switch it off.', + access: 'supervisor', campusScope: 'checked in deletePass (its events\' campuses)', params: idParams, response: deleted, + async handler({ params, user, req }) { await series.deletePass(params.id, actorOf(user), await ctxOf(req)); return { data: { id: params.id, deleted: true as const } }; }, +}); + +export const buyPass = defineRoute({ + method: 'post', path: '/season-passes/:id/buy', tag: 'Series', summary: 'Buy a season pass', + description: 'Registers you at every event on it, then answers with a checkout to pay (or issues the tickets when it\'s free).', + access: 'user', status: 201, params: idParams, + body: z.object({ quantity: z.number().int().min(1).max(50).default(1), provider: z.string().max(40).optional() }), + documented: { response: D.obj({ purchaseId: D.str, total: D.rand, paid: D.bool.describe('Free: the tickets are issued straight away'), redirectUrl: D.optStr.describe('Where to send them to pay'), provider: D.optStr, message: D.optStr }) }, + response: single(z.looseObject({})), + async handler({ params, body, user }) { return { data: plain(await series.buyPass(params.id, user!.id, body)) }; }, +}); + +export const payPass = defineRoute({ + method: 'post', path: '/season-pass-purchases/:id/checkout', tag: 'Series', summary: 'Pay what\'s owed on a pass', + access: 'user', params: idParams, body: z.object({ provider: z.string().max(40).optional() }), response: single(z.looseObject({})), + documented: { response: D.obj({ redirectUrl: D.optStr, provider: D.optStr, message: D.optStr }) }, + async handler({ params, body, user }) { return { data: plain(await series.payPassPurchase(params.id, user!.id, body)) }; }, +}); + +export const myPasses = defineRoute({ + method: 'get', path: '/me/season-passes', tag: 'Me', summary: 'My season passes', + access: 'user', + response: z.object({ data: z.array(z.looseObject({ id, quantity: z.number().int(), total: z.number(), status: z.string(), createdAt: isoDate })) }), + async handler({ user }) { return { data: plain(await series.myPassPurchases(user!.id)) }; }, +}); + +// ─── Bundle deals ──────────────────────────────────────────────────────────── + +const basketBody = z.object({ + eventId: id, + options: z.array(z.object({ eventOptionId: id, variantId: id.nullish(), quantity: z.number().int().min(1).max(1000), sessionIds: z.array(id).max(200).optional() })).max(50), + forUserId: id.nullable().optional().describe('Staff: price it for this person (null = a walk-in without an account)'), +}); +const bundle = z.looseObject({ id, eventId: id, name: z.string(), kind: z.enum(['exact', 'mix', 'free', 'group']), price: z.number().nullable(), isActive: z.boolean(), summary: z.string(), headline: z.string(), available: z.boolean() }); +const bundleBody = z.looseObject({ + name: z.string().trim().min(1).max(80), + kind: z.enum(['exact', 'mix', 'free', 'group']).optional().describe('exact = this set; mix = any N; free = buy N get M free; group = a price for groups'), + price: z.union([z.number(), z.string().max(20)]).nullable().optional(), + setSize: z.number().int().nullable().optional(), + freeCount: z.number().int().nullable().optional(), + groupPricing: z.enum(['per_ticket', 'percent']).nullable().optional(), + items: z.array(z.object({ eventOptionId: id, variantId: id.nullish(), quantity: z.number().int().min(1).optional() })).max(50).optional(), + description: z.string().max(2000).nullable().optional(), + isActive: z.boolean().optional(), + validFrom: z.string().max(40).nullable().optional(), + validUntil: z.string().max(40).nullable().optional(), +}); + +export const listBundles = defineRoute({ + method: 'get', path: '/events/:id/bundles', tag: 'Deals', summary: 'An event\'s bundle deals', + description: 'With how often each has been used and the discount given.', + access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [campusScope.scopeEvent()], params: idParams, + response: z.object({ data: z.array(bundle.extend({ uses: z.number(), registrations: z.number().int(), totalDiscount: z.number() })) }), + async handler({ params }) { return { data: plain(await deals.listBundles(params.id)) }; }, +}); + +export const createBundle = defineRoute({ + method: 'post', path: '/events/:id/bundles', tag: 'Deals', summary: 'Add a bundle deal', + access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [campusScope.scopeEvent({ need: 'manage' })], status: 201, + params: idParams, body: bundleBody, response: single(bundle), + async handler({ params, body, user, req }) { return { data: plain(await deals.createBundle(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const updateBundle = defineRoute({ + method: 'patch', path: '/bundles/:id', tag: 'Deals', summary: 'Change a bundle deal', + description: 'Only what\'s sent changes; when a pricing field is sent the whole deal is checked again.', + access: 'supervisor', campusScope: 'scopeEvent(bundle, manage)', middleware: [campusScope.scopeEvent({ resolve: 'bundle', need: 'manage' })], + params: idParams, body: bundleBody.partial(), response: single(bundle), + async handler({ params, body, user, req }) { return { data: plain(await deals.updateBundle(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const deleteBundle = defineRoute({ + method: 'delete', path: '/bundles/:id', tag: 'Deals', summary: 'Remove a bundle deal', + description: 'One that\'s been used is switched off instead (`switchedOff`), so registrations that got it keep their price.', + access: 'supervisor', campusScope: 'scopeEvent(bundle, manage)', middleware: [campusScope.scopeEvent({ resolve: 'bundle', need: 'manage' })], + params: idParams, response: single(z.object({ deleted: z.literal(true).optional(), switchedOff: z.literal(true).optional(), message: z.string() })), + async handler({ params, user, req }) { return { data: await deals.deleteBundle(params.id, actorOf(user), await ctxOf(req)) }; }, +}); + +export const quote = defineRoute({ + method: 'post', path: '/bundles/quote', tag: 'Deals', summary: 'The bundle deals a basket gets', + description: 'Before any coupon code — what the register page shows as you choose tickets.', + access: 'optional', body: basketBody, + response: single(z.object({ subtotal: z.number(), bundleDiscount: z.number(), bundles: z.array(z.looseObject({})), total: z.number() })), + async handler({ body, user }) { return { data: plain(await deals.quoteBundles(body, user ? actorOf(user) : null)) }; }, +}); + +// ─── Coupon codes ──────────────────────────────────────────────────────────── + +const coupon = z.looseObject({ id, code: z.string(), type: z.enum(['percent', 'fixed', 'comp']), value: z.number(), active: z.boolean(), summary: z.string() }); +const couponBody = z.looseObject({ + code: z.string().trim().min(3).max(32), + type: z.enum(['percent', 'fixed', 'comp']).describe('comp = free'), + value: z.union([z.number(), z.string().max(20)]).optional(), + description: z.string().max(2000).nullable().optional(), + active: z.boolean().optional(), + stackEarlyBird: z.boolean().optional(), + validFrom: z.string().max(40).nullable().optional(), + validUntil: z.string().max(40).nullable().optional(), + maxUses: z.union([z.number().int(), z.string()]).nullable().optional(), + maxUsesPerUser: z.union([z.number().int(), z.string()]).nullable().optional(), + minQuantity: z.union([z.number().int(), z.string()]).nullable().optional(), + restrictRoles: z.array(z.enum(['user', 'staff', 'supervisor', 'admin'])).optional(), + restrictDomain: z.string().max(120).nullable().optional(), + eventIds: z.array(id).max(200).optional().describe('Empty = every event (not for campus-scoped supervisors)'), + options: z.array(z.object({ eventOptionId: id, variantId: id.nullish() })).max(200).optional(), + userIds: z.array(id).max(1000).optional(), +}); + +export const listCoupons = defineRoute({ + method: 'get', path: '/coupons', tag: 'Deals', summary: 'Coupon codes', + description: 'With how often each has been used and the discount given. Campus-scoped supervisors see codes for their campuses\' events.', + access: 'supervisor', campusScope: 'scopeList (couponAllowed in listCoupons)', + response: z.object({ data: z.array(coupon.extend({ uses: z.number().int(), totalDiscount: z.number() })) }), + async handler({ req }) { return { data: plain(await deals.listCoupons(await ctxOf(req))) }; }, +}); + +export const redemptions = defineRoute({ + method: 'get', path: '/coupons/redemptions', tag: 'Deals', summary: 'Coupon and bundle uses', + description: 'For the Discounts report, newest first.', + access: 'supervisor', campusScope: 'scopeList (listWhere)', + query: z.object({ eventIds: z.string().max(4000).optional().describe('Comma-separated'), from: z.string().max(40).optional(), to: z.string().max(40).optional() }), + response: z.object({ data: z.array(z.looseObject({ id, kind: z.enum(['coupon', 'bundle']), uses: z.number(), discountAmount: z.number(), createdAt: isoDate })) }), + async handler({ query, req }) { + const date = (v?: string) => { if (!v) return null; const d = new Date(v); return isNaN(d.getTime()) ? null : d; }; + const eventIds = String(query.eventIds || '').split(',').map(s => s.trim()).filter(Boolean); + return { data: plain(await deals.listRedemptions({ eventIds, from: date(query.from), to: date(query.to) }, await campusScope.listWhere(req, 'event'))) }; + }, +}); + +export const getCoupon = defineRoute({ + method: 'get', path: '/coupons/:id', tag: 'Deals', summary: 'One coupon code with its uses', + access: 'supervisor', campusScope: 'scopeList (couponAllowed in getCoupon)', params: idParams, + response: single(coupon.extend({ redemptions: z.array(z.looseObject({ id })) })), + async handler({ params, req }) { return { data: plain(await deals.getCoupon(params.id, await ctxOf(req))) }; }, +}); + +export const createCoupon = defineRoute({ + method: 'post', path: '/coupons', tag: 'Deals', summary: 'Create a coupon code', + access: 'supervisor', campusScope: 'checked in createCoupon (eventIdsAllowed)', status: 201, body: couponBody, response: single(coupon), + async handler({ body, user, req }) { return { data: plain(await deals.createCoupon(body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const updateCoupon = defineRoute({ + method: 'patch', path: '/coupons/:id', tag: 'Deals', summary: 'Change a coupon code', + description: 'Only what\'s sent changes. Discounts already given keep their amount; a used code can\'t be renamed.', + access: 'supervisor', campusScope: 'checked in updateCoupon (couponAllowed)', params: idParams, body: couponBody.partial(), response: single(coupon), + async handler({ params, body, user, req }) { return { data: plain(await deals.updateCoupon(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const checkCode = defineRoute({ + method: 'post', path: '/coupons/check', tag: 'Deals', summary: 'Check a coupon code against a basket', + description: 'Always a 200: `valid` with the discount and total, or `valid: false` with why. Restricted codes need you signed in.', + access: 'optional', campusScope: 'scopeEvent(body.eventId)', middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId })], + body: basketBody.extend({ code: z.string().trim().min(1).max(40) }), + response: single(z.discriminatedUnion('valid', [ + z.object({ valid: z.literal(true), code: z.string(), type: z.string(), value: z.number(), summary: z.string(), description: z.string().nullable(), discount: z.number(), bundleDiscount: z.number(), bundles: z.array(z.looseObject({})), subtotal: z.number(), total: z.number() }), + z.object({ valid: z.literal(false), message: z.string() }), + ])), + async handler({ body, user }) { return { data: plain(await deals.checkCode(body, user ? actorOf(user) : null)) }; }, +}); + +// ─── Campuses ──────────────────────────────────────────────────────────────── + +const publicCampus = z.looseObject({ id, name: z.string(), slug: z.string() }); +const adminCampus = publicCampus.extend({ archivedAt: isoDate.nullable(), order: z.number().int(), _count: z.looseObject({ events: z.number().int() }) }); +const campusBody = z.looseObject({ + name: z.string().trim().min(1).max(120), + slug: z.string().trim().max(80).optional(), + colour: z.string().max(20).nullable().optional(), + notifyRecipientIds: z.array(id).max(100).optional().describe('Who gets this campus\'s daily summary (staff only)'), + archived: z.boolean().optional(), +}); + +export const listCampuses = defineRoute({ + method: 'get', path: '/campuses', tag: 'Campuses', summary: 'The active campuses', + description: '`enabled` false means campuses are switched off (the list is then empty).', + access: 'public', response: single(z.object({ enabled: z.boolean(), campuses: z.array(publicCampus) })), + async handler() { return { data: plain(await campuses.publicCampuses()) }; }, +}); + +export const adminList = defineRoute({ + method: 'get', path: '/campuses/admin', tag: 'Campuses', summary: 'Every campus (Site settings)', + description: 'Archived ones last, with event counts and summary recipients.', + access: 'admin', response: single(z.object({ enabled: z.boolean(), campuses: z.array(adminCampus) })), + async handler() { return { data: plain(await campuses.adminCampuses()) }; }, +}); + +export const campusBySlug = defineRoute({ + method: 'get', path: '/campuses/by-slug/:slug', tag: 'Campuses', summary: 'A campus landing page', + access: 'public', params: z.object({ slug: z.string().min(1).max(80) }), response: single(publicCampus), + async handler({ params }) { return { data: plain(await campuses.campusBySlug(params.slug)) }; }, +}); + +export const setEnabled = defineRoute({ + method: 'put', path: '/campuses/enabled', tag: 'Campuses', summary: 'Switch campuses on or off', + description: 'Off hides campus fields and filters; nothing is deleted.', + access: 'admin', body: z.object({ enabled: z.boolean() }), response: single(z.object({ enabled: z.boolean() })), + async handler({ body, user, req }) { return { data: await campuses.setCampusesEnabled(body.enabled, actorOf(user), await ctxOf(req)) }; }, +}); + +export const reorder = defineRoute({ + method: 'put', path: '/campuses/order', tag: 'Campuses', summary: 'Put the campuses in order', + access: 'admin', body: z.object({ ids: z.array(id).min(1).max(200) }), response: single(z.object({ ids: z.array(id) })), + async handler({ body }) { await campuses.reorderCampuses(body.ids); return { data: { ids: body.ids } }; }, +}); + +export const createCampus = defineRoute({ + method: 'post', path: '/campuses', tag: 'Campuses', summary: 'Add a campus', + access: 'admin', status: 201, body: campusBody, response: single(adminCampus), + async handler({ body, user, req }) { return { data: plain(await campuses.createCampus(body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const updateCampus = defineRoute({ + method: 'patch', path: '/campuses/:id', tag: 'Campuses', summary: 'Change a campus', + description: 'Details, summary recipients, or `archived`.', + access: 'admin', params: idParams, body: campusBody.partial(), response: single(adminCampus), + async handler({ params, body, user, req }) { return { data: plain(await campuses.updateCampus(params.id, body, actorOf(user), await ctxOf(req))) }; }, +}); + +export const deleteCampus = defineRoute({ + method: 'delete', path: '/campuses/:id', tag: 'Campuses', summary: 'Delete a campus', + description: 'Only one with no events and no staff limited to it — otherwise archive it (CONFLICT, `reason` CAMPUS_HAS_EVENTS or CAMPUS_HAS_SCOPED_STAFF).', + access: 'admin', params: idParams, response: deleted, + async handler({ params, user, req }) { await campuses.deleteCampus(params.id, actorOf(user), await ctxOf(req)); return { data: { id: params.id, deleted: true as const } }; }, +}); + +export const audience = defineRoute({ + method: 'get', path: '/campuses/:id/audience', tag: 'Campuses', summary: 'Everyone at a campus', + description: 'For the email and WhatsApp composers: people whose home campus it is, plus (`registrants=true`) people registered for its events in the last 12 months. News consent is checked when sending.', + access: 'supervisor', campusScope: 'scopeList (own campuses only, in campusAudience)', params: idParams, + query: z.object({ registrants: z.enum(['true', 'false']).default('false').transform(v => v === 'true') }), + response: single(z.object({ campus: z.object({ id, name: z.string() }), users: z.array(z.object({ id, name: z.string(), email: z.string(), phoneNumber: z.string().nullable() })) })), + async handler({ params, query, req }) { return { data: plain(await campuses.campusAudience(params.id, query.registrants, await ctxOf(req))) }; }, +}); diff --git a/apps/events/backend/src/v2/resources/setup.ts b/apps/events/backend/src/v2/resources/setup.ts new file mode 100644 index 0000000..c11b55b --- /dev/null +++ b/apps/events/backend/src/v2/resources/setup.ts @@ -0,0 +1,229 @@ +import { z } from 'zod'; +import type { Request, RequestHandler } from 'express'; +import { defineRoute } from '../route'; +import { ApiError } from '../errors'; +import { single } from '../paging'; +import { absoluteUrl, id, idParams, isoDate } from '../schemas'; +import * as setup from '../../services/setup'; +import { prisma } from '../legacy'; +import auth from '../../middleware/authMiddleware'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- multer and the scope middleware are JS */ +const campusScope = require('../../utils/campusScope') as { + listWhere(req: unknown, path?: string): Promise; + scopeEvent(opts?: { need?: 'view' | 'manage'; resolve?: string; from?: (req: any) => unknown }): any; +}; +const uploads = require('../../controllers/uploadController') as { upload: any; uploadLogo: any; uploadFavicon: any }; +const plain = (v: T): any => JSON.parse(JSON.stringify(v)); + +// ─── Sections ──────────────────────────────────────────────────────────────── + +const section = z.looseObject({ + id, eventId: id, name: z.string(), + allowedOptions: z.array(z.looseObject({ eventOptionId: id, eventOption: z.looseObject({ id, name: z.string() }) })), +}); + +export const listSections = defineRoute({ + method: 'get', + path: '/sections', + tag: 'Events (staff)', + summary: 'Scanning sections', + description: 'Which ticket types may come in at which door, for one event or every event you can see.', + access: 'staff', + campusScope: 'scopeList (listWhere)', + query: z.object({ eventId: id.optional() }), + response: z.object({ data: z.array(section.extend({ event: z.object({ id, title: z.string() }) })) }), + async handler({ query, req }) { + return { data: plain(await setup.listSections(query.eventId, await campusScope.listWhere(req, 'event'))) }; + }, +}); + +export const createSection = defineRoute({ + method: 'post', + path: '/sections', + tag: 'Events (staff)', + summary: 'Add a scanning section', + access: 'supervisor', + campusScope: 'scopeEvent(body.eventId, manage)', + middleware: [campusScope.scopeEvent({ from: req => req.body?.eventId, need: 'manage' })], + status: 201, + body: z.object({ eventId: id, name: z.string().trim().min(1).max(120), allowedOptionIds: z.array(id).max(100).optional() }), + response: single(section), + async handler({ body }) { + return { data: plain(await setup.createSection(body)) }; + }, +}); + +export const updateSection = defineRoute({ + method: 'patch', + path: '/sections/:id', + tag: 'Events (staff)', + summary: 'Change a scanning section', + description: '`allowedOptionIds`, when sent, replaces its ticket types.', + access: 'supervisor', + campusScope: 'scopeEvent(section, manage)', + middleware: [campusScope.scopeEvent({ resolve: 'section', need: 'manage' })], + params: idParams, + body: z.object({ name: z.string().trim().min(1).max(120).optional(), allowedOptionIds: z.array(id).max(100).optional() }), + response: single(section), + async handler({ params, body }) { + return { data: plain(await setup.updateSection(params.id, body)) }; + }, +}); + +export const deleteSection = defineRoute({ + method: 'delete', + path: '/sections/:id', + tag: 'Events (staff)', + summary: 'Remove a scanning section', + access: 'admin', + params: idParams, + response: single(z.object({ id, deleted: z.literal(true) })), + async handler({ params }) { + await setup.deleteSection(params.id); + return { data: { id: params.id, deleted: true as const } }; + }, +}); + +// ─── Planned costs ─────────────────────────────────────────────────────────── + +const cost = z.object({ + id, eventId: id, label: z.string(), costType: z.enum(['once_off', 'per_item']), amount: z.number(), + eventOptionId: id.nullable(), eventOption: z.object({ id, name: z.string() }).nullable(), + paidFromMethod: z.string().nullable().describe('How it was paid out of the takings (cash, card, eft, other)'), + notes: z.string().nullable(), createdAt: isoDate, updatedAt: isoDate.optional(), +}); +const costBody = z.object({ + label: z.string().trim().min(1).max(200), + costType: z.enum(['once_off', 'per_item']).describe('per_item = per ticket sold of `eventOptionId`'), + amount: z.union([z.number().min(0), z.string().max(20)]), + eventOptionId: id.nullable().optional(), + notes: z.string().max(2000).nullable().optional(), + paidFromMethod: z.enum(['cash', 'card', 'eft', 'other']).nullable().optional(), +}); + +export const listCosts = defineRoute({ + method: 'get', + path: '/events/:id/costs', + tag: 'Events (staff)', + summary: 'An event\'s planned costs', + access: 'supervisor', + campusScope: 'scopeEvent(manage)', + middleware: [campusScope.scopeEvent({ need: 'manage' })], + params: idParams, + response: z.object({ data: z.array(cost) }), + async handler({ params }) { + return { data: plain(await setup.listCosts(params.id)) }; + }, +}); + +export const createCost = defineRoute({ + method: 'post', + path: '/events/:id/costs', + tag: 'Events (staff)', + summary: 'Add a planned cost', + description: 'Admins. Not on a cashed-up event.', + access: 'admin', + status: 201, + params: idParams, + body: costBody, + response: single(cost), + async handler({ params, body }) { + return { data: plain(await setup.createCost(params.id, body)) }; + }, +}); + +export const updateCost = defineRoute({ + method: 'patch', + path: '/costs/:id', + tag: 'Events (staff)', + summary: 'Change a planned cost', + access: 'admin', + params: idParams, + body: costBody.partial(), + response: single(cost), + async handler({ params, body }) { + return { data: plain(await setup.updateCost(params.id, body)) }; + }, +}); + +export const deleteCost = defineRoute({ + method: 'delete', + path: '/costs/:id', + tag: 'Events (staff)', + summary: 'Remove a planned cost', + access: 'admin', + params: idParams, + response: single(z.object({ id, deleted: z.literal(true) })), + async handler({ params }) { + await setup.deleteCost(params.id); + return { data: { id: params.id, deleted: true as const } }; + }, +}); + +// ─── Image uploads ─────────────────────────────────────────────────────────── + +/** Runs a multer step for field "image", keeping any error on the request. */ +const receive = (m: any): RequestHandler => (req, res, next) => m.single('image')(req, res, (e: Error | undefined) => { + if (e) (req as Request & { multerError?: Error }).multerError = e; + next(); +}); + +/** Branding images: admins — or anyone during first-time setup, before any account exists. */ +const brandingAccess: RequestHandler = async (req, res, next) => { + try { + if (await prisma.user.count() === 0) return next(); + } catch { /* fall through to the admin check */ } + auth.protect(req, res, (e?: unknown) => (e ? next(e) : auth.admin(req, res, next))); +}; + +const uploaded = (folder: string) => async ({ req }: { req: Request }) => { + const r = req as Request & { multerError?: Error; file?: { filename: string } }; + if (r.multerError) throw new ApiError('VALIDATION_FAILED', `Upload failed: ${r.multerError.message}`, { image: r.multerError.message }); + if (!r.file) throw new ApiError('VALIDATION_FAILED', 'No file uploaded', { image: 'Choose an image' }); + const path = `/uploads/${folder}/${r.file.filename}`; + return { data: { path, url: absoluteUrl(req, path)! } }; +}; +const uploadResult = single(z.object({ path: z.string().describe('What to save on the event or setting'), url: z.string().describe('The same, as a full address') })); +const IMAGE = 'A JPEG, PNG, GIF or WebP image'; +const LOGO = 'A JPEG, PNG, WebP or SVG image'; + +export const uploadEventImage = defineRoute({ + method: 'post', + path: '/uploads/event-image', + tag: 'Uploads', + summary: 'Upload an event picture', + description: 'Returns the path to save as the event\'s `picture`.', + access: 'supervisor', + campusScope: 'campusIndependent (only stores the file; the event is checked when it is saved)', + middleware: [receive(uploads.upload)], + upload: { field: 'image', description: IMAGE }, + response: uploadResult, + handler: uploaded('events'), +}); + +export const uploadLogo = defineRoute({ + method: 'post', + path: '/uploads/logo', + tag: 'Uploads', + summary: 'Upload the site logo', + description: 'Admins — or anyone during first-time setup, before any account exists.', + access: 'public', + middleware: [brandingAccess, receive(uploads.uploadLogo)], + upload: { field: 'image', description: LOGO }, + response: uploadResult, + handler: uploaded('branding'), +}); + +export const uploadFavicon = defineRoute({ + method: 'post', + path: '/uploads/favicon', + tag: 'Uploads', + summary: 'Upload the site icon (favicon)', + description: 'Admins — or anyone during first-time setup, before any account exists.', + access: 'public', + middleware: [brandingAccess, receive(uploads.uploadFavicon)], + upload: { field: 'image', description: 'An ICO, PNG or SVG image' }, + response: uploadResult, + handler: uploaded('branding'), +}); diff --git a/apps/events/backend/src/v2/route.ts b/apps/events/backend/src/v2/route.ts new file mode 100644 index 0000000..5682cb0 --- /dev/null +++ b/apps/events/backend/src/v2/route.ts @@ -0,0 +1,146 @@ +import type { Request, RequestHandler, Response, Router } from 'express'; +import { z } from 'zod'; +import { ApiError } from './errors'; +import auth from '../middleware/authMiddleware'; + +/** + * Every /api/v2 endpoint is declared with `defineRoute`: method, path, who may call it, and zod + * schemas for the params, query, body and response. The same declaration + * - validates the request (400 VALIDATION_FAILED with per-field messages), + * - checks the response against its schema and strips anything it doesn't list (so a field + * can't leak by being added to a Prisma include), and + * - becomes the OpenAPI document (openapi.ts) — the docs can't drift from the code. + */ + +export type Access = 'public' | 'optional' | 'user' | 'staff' | 'supervisor' | 'admin'; + +/** The signed-in person, as the auth middleware puts it on the request. */ +export type ApiUser = { id: string; name: string; email: string; role: 'admin' | 'supervisor' | 'staff' | 'user' }; + +export type Ctx = { + params: P; + query: Q; + body: B; + user: ApiUser | null; + req: Request; + res: Response; +}; + +type Schema = z.ZodType; +type Infer = S extends z.ZodType ? z.infer : undefined; + +export type RouteDef

= { + method: 'get' | 'post' | 'put' | 'patch' | 'delete'; + /** Express-style, relative to /api/v2: "/events/:id". */ + path: string; + summary: string; + description?: string; + tag: string; + access: Access; + /** + * Staff and supervisor routes must say how they treat campus-scoped staff (see + * utils/campusScope.js and tests/campusScopeRoutes.test.js) — e.g. "scopeEvent(params.id)". + */ + campusScope?: string; + params?: P; + query?: Q; + body?: B; + response: R; + /** HTTP status on success (default 200). */ + status?: number; + /** Runs after the access check, e.g. a rate limiter. */ + middleware?: RequestHandler[]; + /** A multipart upload (the file in `field`, saved by a multer step in `middleware`). */ + upload?: { field: string; description: string }; + /** + * The answer is a file, not JSON: the handler returns `{ data: { contentType, filename, body } }` + * and `response` is `fileResponse`. `contentType` here is what the docs show. + */ + file?: { contentType: string }; + /** + * Documentation only (v1Route, 1.52.1): the body and the answer's `data` as the v1 handler takes + * and gives them, for the OpenAPI document. Not enforced — the handler gets what was sent and its + * answer goes out as it is — but outside production anything that doesn't fit is logged + * (`[api/v2] … doesn't match its documented …`), so the docs can't drift unnoticed. + */ + documented?: { body?: Schema; response?: Schema }; + handler: (ctx: Ctx, Infer, Infer>) => Promise> | z.input; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type AnyRoute = RouteDef; + +export const routes: AnyRoute[] = []; + +const ACCESS: Record = { + public: [], + optional: [auth.optionalAuth], + user: [auth.protect], + staff: [auth.protect, auth.staff], + supervisor: [auth.protect, auth.supervisor], + admin: [auth.protect, auth.admin], +}; + +export function defineRoute

(def: RouteDef): RouteDef { + if ((def.access === 'staff' || def.access === 'supervisor') && !def.campusScope) { + throw new Error(`${def.method.toUpperCase()} /api/v2${def.path}: staff and supervisor routes must declare campusScope`); + } + // Two definitions of one route: the first would silently win. + if (routes.some(r => r.method === def.method && r.path === def.path)) { + throw new Error(`${def.method.toUpperCase()} /api/v2${def.path} is defined twice`); + } + routes.push(def as AnyRoute); + return def; +} + +const parse = (schema: S, value: unknown): Infer => + (schema ? schema.parse(value) : undefined) as Infer; + +/** Outside production: says when a documented-only body or answer doesn't fit its documentation. */ +function warnUndocumented(def: AnyRoute, what: string, schema: Schema, value: unknown) { + if (process.env.NODE_ENV === 'production') return; + const checked = schema.safeParse(value); + if (!checked.success) { + console.warn(`[api/v2] ${def.method.toUpperCase()} ${def.path}: ${what} doesn't match its documented schema`, JSON.stringify(checked.error.issues.slice(0, 5))); + } +} + +/** Adds every defined route to the router. */ +export function mount(router: Router, list: AnyRoute[] = routes): void { + for (const def of list) { + const run: RequestHandler = async (req, res, next) => { + try { + const ctx = { + params: parse(def.params, req.params), + query: parse(def.query, req.query), + body: parse(def.body, req.body ?? {}), + user: (req as Request & { user?: ApiUser }).user ?? null, + req, + res, + }; + if (def.documented?.body) warnUndocumented(def, 'request body', def.documented.body, req.body ?? {}); + const result = await def.handler(ctx); + if (def.documented?.response) warnUndocumented(def, 'answer', def.documented.response, (result as { data?: unknown })?.data); + const checked = def.response.safeParse(result); + if (!checked.success) { + console.error(`[api/v2] ${def.method.toUpperCase()} ${def.path}: response doesn't match its schema`, checked.error.issues); + throw new ApiError('INTERNAL', 'Something went wrong on the server.'); + } + if (def.file) { + const f = (checked.data as { data: { contentType: string; filename: string; body: string | Buffer } }).data; + res.setHeader('Content-Type', f.contentType); + res.setHeader('Content-Disposition', `attachment; filename="${f.filename.replace(/"/g, '')}"`); + res.status(def.status ?? 200).send(f.body); + return; + } + res.status(def.status ?? 200).json(checked.data); + } catch (err) { + next(err); + } + }; + router[def.method](def.path, ...ACCESS[def.access], ...(def.middleware ?? []), run); + } +} + +/** The `response` of a `file` route: what the handler hands back to be sent as a download. */ +export const fileResponse = z.object({ data: z.object({ contentType: z.string(), filename: z.string(), body: z.union([z.string(), z.instanceof(Buffer)]) }) }); diff --git a/apps/events/backend/src/v2/schemas.ts b/apps/events/backend/src/v2/schemas.ts new file mode 100644 index 0000000..3c3a1ae --- /dev/null +++ b/apps/events/backend/src/v2/schemas.ts @@ -0,0 +1,27 @@ +import { z } from 'zod'; +import type { Request } from 'express'; + +/** Shared pieces of v2 schemas. Dates go out as ISO 8601 strings (UTC). */ + +export const isoDate = z.iso.datetime(); +export const id = z.string().min(1).max(64); +export const idParams = z.object({ id: id.describe('The id') }); + +/** A Date (or date string) as ISO 8601, for building responses. */ +export function iso(d: Date | string): string; +export function iso(d: Date | string | null | undefined): string | null; +export function iso(d: Date | string | null | undefined): string | null { + return d == null ? null : new Date(d).toISOString(); +} + +/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */ +export function absoluteUrl(req: Request, url: string | null | undefined): string | null { + const raw = String(url || '').trim(); + if (!raw) return null; + if (/^https?:\/\//.test(raw)) return raw; + return `${req.protocol}://${req.get('host')}${raw.startsWith('/') ? '' : '/'}${raw}`; +} + +export const campusRef = z.object({ id, name: z.string(), slug: z.string() }); +export const seriesRef = z.object({ id, name: z.string(), slug: z.string() }); +export const eventRef = z.object({ id, title: z.string(), startDate: isoDate, endDate: isoDate }); diff --git a/apps/events/backend/src/v2/viaV1.ts b/apps/events/backend/src/v2/viaV1.ts new file mode 100644 index 0000000..3ac10de --- /dev/null +++ b/apps/events/backend/src/v2/viaV1.ts @@ -0,0 +1,187 @@ +/** + * v2 routes that run a v1 handler in-process (1.51.11 –). The handler is the one v1 runs, so + * both versions behave the same; v2 adds its own path, validation, docs and response shape. + * + * - A v1 answer of 2xx becomes `{ data: }` (or a file download, for `file` routes). + * - A v1 error (`{ message, code? }` with 4xx/5xx) becomes the v2 error: the status picks `code`, + * v1's `code` becomes `reason`. + * + * The handlers are still JavaScript; moving each area into a TypeScript service (as 1.51.1 – + * 1.51.10 did) can follow later without changing the v2 API. + */ +import { readFile } from 'fs/promises'; +import { basename } from 'path'; +import { Writable } from 'stream'; +import { z } from 'zod'; +import type { Request, RequestHandler } from 'express'; +import { defineRoute, fileResponse, type Access, type Ctx } from './route'; + +/* eslint-disable @typescript-eslint/no-explicit-any -- requests and v1 answers are passed through */ +/** `url` (with its query string) is for v1 routers, which route by it. */ +type Parts = { params?: Record; query?: Record; body?: unknown; url?: string }; +type V1Answer = { status: number; json?: unknown; body?: Buffer; headers: Record; redirect?: string }; + +/** A response that records what a v1 handler sends (JSON, `send`, a piped stream or a redirect). */ +class RecordingResponse extends Writable { + statusCode = 200; + headersSent = false; + locals: Record = {}; + readonly headers: Record = {}; + private chunks: Buffer[] = []; + json?: (v: unknown) => this; + answer?: V1Answer; + private done!: (a: V1Answer) => void; + readonly finished: Promise; + + constructor() { + super(); + this.finished = new Promise(resolve => { this.done = resolve; }); + this.json = (v: unknown) => this.finishWith({ json: JSON.parse(JSON.stringify(v ?? null)) }); + } + + override _write(chunk: any, _enc: BufferEncoding, cb: () => void) { this.chunks.push(Buffer.from(chunk)); cb(); } + override _final(cb: () => void) { this.finishWith({}); cb(); } + + private finishWith(extra: Partial): this { + if (this.answer) return this; + this.headersSent = true; + this.answer = { status: this.statusCode, headers: this.headers, body: Buffer.concat(this.chunks), ...extra }; + this.done(this.answer); + return this; + } + + status(code: number) { this.statusCode = code; return this; } + sendStatus(code: number) { this.statusCode = code; return this.finishWith({}); } + setHeader(name: string, value: unknown) { this.headers[name.toLowerCase()] = String(value); return this; } + getHeader(name: string) { return this.headers[name.toLowerCase()]; } + removeHeader(name: string) { delete this.headers[name.toLowerCase()]; } + set(name: string | Record, value?: unknown) { + if (typeof name === 'object') for (const [k, v] of Object.entries(name)) this.setHeader(k, v); + else this.setHeader(name, value); + return this; + } + header(name: string, value?: unknown) { return this.set(name, value); } + type(t: string) { return this.setHeader('content-type', t.includes('/') ? t : t === 'json' ? 'application/json' : `text/${t}`); } + attachment(filename?: string) { return filename ? this.setHeader('content-disposition', `attachment; filename="${filename}"`) : this; } + send(body?: unknown) { + if (body !== null && typeof body === 'object' && !Buffer.isBuffer(body)) return this.json!(body); + if (body !== undefined) this.chunks.push(Buffer.isBuffer(body) ? body : Buffer.from(String(body))); + return this.finishWith({}); + } + // A handler that ends without writing anything still answers. + override end(...args: any[]) { + const [chunk] = args; + if (chunk !== undefined && typeof chunk !== 'function') this.chunks.push(Buffer.from(chunk)); + this.finishWith({}); + return this; + } + /** `res.download` / `res.sendFile`: the file on disk becomes the answer. */ + download(filePath: string, filename?: string | ((err?: unknown) => void)) { + const name = typeof filename === 'string' ? filename : basename(filePath); + readFile(filePath).then(buf => { + if (!this.headers['content-type']) this.setHeader('content-type', 'application/octet-stream'); + this.setHeader('content-disposition', `attachment; filename="${name}"`); + this.chunks.push(buf); + this.finishWith({}); + }, () => { this.statusCode = 404; this.finishWith({ json: { message: 'That file was not found.' } }); }); + return this; + } + sendFile(filePath: string) { + readFile(filePath).then(buf => { this.chunks.push(buf); this.finishWith({}); }, () => { this.statusCode = 404; this.finishWith({ json: { message: 'That file was not found.' } }); }); + return this; + } + redirect(a: number | string, b?: string) { + const url = typeof a === 'string' ? a : b!; + this.statusCode = typeof a === 'number' ? a : 302; + return this.finishWith({ redirect: url }); + } +} + +/** + * Runs v1 handlers (and middleware) for a v2 request. `parts` replaces the request's params, + * query or body (e.g. v2 `:id` given to v1 as `:eventId`); everything else (the user, headers, + * campus scope, read-only state) is the real request's. + */ +export async function runV1(handlers: RequestHandler | RequestHandler[], req: Request, parts: Parts = {}): Promise { + const fake = Object.create(req) as Request; + for (const key of ['params', 'query', 'body', 'url'] as const) { + if (parts[key] !== undefined) Object.defineProperty(fake, key, { value: parts[key], writable: true, configurable: true, enumerable: true }); + } + const res = new RecordingResponse(); + const chain = Array.isArray(handlers) ? handlers : [handlers]; + const step = (i: number): Promise => new Promise((resolve, reject) => { + let advanced = false; + const next = (err?: unknown) => { + advanced = true; + if (err) return reject(err); + if (i + 1 < chain.length) step(i + 1).then(resolve, reject); + // Nothing answered (e.g. a v1 router with no matching route). + else reject(Object.assign(new Error('There is no such API endpoint.'), { statusCode: 404 })); + }; + Promise.resolve(chain[i](fake, res as any, next)).then(() => { if (!advanced) resolve(); }, reject); + }); + await Promise.race([step(0).then(() => res.finished), res.finished]); + return res.answer!; +} + +/** A v1 error answer as something v2's error handler understands. */ +function v1Error(a: V1Answer): Error { + const j = (a.json ?? {}) as { message?: unknown; error?: unknown; code?: unknown }; + const text = typeof j.message === 'string' ? j.message : typeof j.error === 'string' ? j.error : a.body?.length ? a.body.toString('utf8').slice(0, 500) : 'Request failed.'; + const e = new Error(text) as Error & { statusCode: number; code?: string }; + e.statusCode = a.status; + if (typeof j.code === 'string') e.code = j.code; + return e; +} + +/** `{ data: }` — for v1 answers documented by their description. */ +export const anyData = z.object({ data: z.unknown() }); +export const listData = z.object({ data: z.array(z.looseObject({})) }); +export const objectData = z.object({ data: z.looseObject({}) }); + +type V1RouteDef = { + method: 'get' | 'post' | 'put' | 'patch' | 'delete'; + path: string; + tag: string; + summary: string; + description?: string; + access: Access; + campusScope?: string; + middleware?: RequestHandler[]; + params?: z.ZodType; + query?: z.ZodType; + body?: z.ZodType; + response?: z.ZodType; + /** The body and the answer's `data`, for the docs only (see RouteDef.documented). */ + documented?: { body?: z.ZodType; response?: z.ZodType }; + status?: number; + file?: { contentType: string }; + upload?: { field: string; description: string }; + /** The v1 handler (or middleware chain ending in one). */ + v1: RequestHandler | RequestHandler[]; + /** + * What v1 gets as params/query/body. By default: the v2 params, the raw query and the raw body + * (validated by `query`/`body` when given, but passed as sent so v1 sees what it always saw). + */ + map?: (ctx: Ctx) => Parts; +}; + +/** A v2 route answered by a v1 handler. */ +export function v1Route(def: V1RouteDef) { + const { v1, map, response, ...rest } = def; + return defineRoute({ + ...rest, + response: def.file ? fileResponse : (response ?? anyData), + async handler(ctx) { + const parts: Parts = { params: ctx.req.params, query: ctx.req.query as any, body: ctx.req.body, ...(map ? map(ctx) : {}) }; + const a = await runV1(v1, ctx.req, parts); + if (a.status >= 400) throw v1Error(a); + if (a.redirect) return { data: { redirectUrl: a.redirect } } as any; + if (def.file) { + const name = /filename="?([^";]+)"?/.exec(a.headers['content-disposition'] || '')?.[1] || 'download'; + return { data: { contentType: a.headers['content-type'] || def.file.contentType, filename: name, body: a.body ?? Buffer.alloc(0) } }; + } + return { data: a.json !== undefined ? a.json : (a.body?.length ? a.body.toString('utf8') : null) } as any; + }, + }); +} diff --git a/apps/events/backend/tests/accountEnumeration.test.ts b/apps/events/backend/tests/accountEnumeration.test.ts new file mode 100644 index 0000000..3848625 --- /dev/null +++ b/apps/events/backend/tests/accountEnumeration.test.ts @@ -0,0 +1,108 @@ +/** + * 1.51.17 security fix: nothing public says whether an account exists. Forgot-password answers + * the same for every email (before doing any per-account work), and sign-in with an unknown email + * answers exactly like a wrong password. + */ +const mockDb = { + user: { findUnique: jest.fn(), findFirst: jest.fn(), update: jest.fn() }, + passwordReset: { updateMany: jest.fn(), create: jest.fn() }, +}; +jest.mock('../src/config/db', () => mockDb); +const mockCompare = jest.fn(async () => false); +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 })); +jest.mock('../src/utils/securityEvents', () => ({ logSecurityEvent: async () => undefined, getRecentSecurityEvents: async () => [] })); +jest.mock('../src/utils/whatsapp', () => ({ normalizeZAPhone: () => null, isValidZAPhone: () => false })); + +import { logIn } from '../src/services/auth'; +import { ServiceError } from '../src/services/errors'; +// eslint-disable-next-line @typescript-eslint/no-require-imports +const { requestPasswordReset } = require('../src/controllers/userController'); + +type Answer = { status: number; body: unknown }; +function call(handler: (req: unknown, res: unknown) => Promise, body: object): Promise { + return new Promise(resolve => { + let status = 200; + const res = { + statusCode: 200, + status(n: number) { status = n; this.statusCode = n; return this; }, + json(b: unknown) { resolve({ status, body: b }); return this; }, + }; + handler({ body, headers: {}, ip: '127.0.0.1' }, res); + }); +} + +const realUser = { id: 'u1', name: 'Thandi', email: 'thandi@example.org', isActive: true, password: 'real-hash', failedAttempts: 0, lockUntil: null, role: 'user' }; + +beforeEach(() => jest.clearAllMocks()); + +describe('forgot password', () => { + test('answers the same, with the same status, for an email with and without an account', async () => { + mockDb.user.findUnique.mockResolvedValueOnce(null); + const unknown = await call(requestPasswordReset, { email: 'nobody@example.org' }); + mockDb.user.findUnique.mockResolvedValueOnce(realUser); + const known = await call(requestPasswordReset, { email: realUser.email }); + expect(unknown).toEqual(known); + expect(known.status).toBe(200); + }); + + test('only a real account gets a link, made after the answer is sent', async () => { + mockDb.user.findUnique.mockResolvedValueOnce(null); + await call(requestPasswordReset, { email: 'nobody@example.org' }); + await new Promise(r => setImmediate(r)); + expect(mockDb.passwordReset.create).not.toHaveBeenCalled(); + expect(mockSendMail).not.toHaveBeenCalled(); + + mockDb.user.findUnique.mockResolvedValueOnce(realUser); + const answered = call(requestPasswordReset, { email: realUser.email }); + await answered; + await new Promise(r => setImmediate(r)); + expect(mockDb.passwordReset.create).toHaveBeenCalledTimes(1); + expect(mockSendMail).toHaveBeenCalledWith(expect.objectContaining({ to: realUser.email })); + }); +}); + +describe('sign-in', () => { + const failure = async (p: Promise) => { try { await p; } catch (e) { return e as ServiceError; } throw new Error('expected a refusal'); }; + + test('an unknown email is refused exactly like a wrong password', async () => { + mockDb.user.findFirst.mockResolvedValueOnce(null); + const unknown = await failure(logIn({ identifier: 'nobody@example.org', password: 'x' }, { ip: '1', userAgent: 'jest' })); + mockDb.user.findFirst.mockResolvedValueOnce(realUser); + const wrong = await failure(logIn({ identifier: realUser.email, password: 'x' }, { ip: '1', userAgent: 'jest' })); + expect({ message: unknown.message, status: unknown.statusCode, v1: unknown.v1Status }).toEqual({ message: wrong.message, status: wrong.statusCode, v1: wrong.v1Status }); + }); + + test('an unknown email still does a password check, so it takes as long', async () => { + mockDb.user.findFirst.mockResolvedValueOnce(null); + await failure(logIn({ identifier: 'nobody@example.org', password: 'guess' }, { ip: '1', userAgent: 'jest' })); + 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/adminAudit.test.js b/apps/events/backend/tests/adminAudit.test.js new file mode 100644 index 0000000..7e981e8 --- /dev/null +++ b/apps/events/backend/tests/adminAudit.test.js @@ -0,0 +1,40 @@ +jest.mock('../src/config/db', () => ({})); + +const { auditLogWhere } = require('../src/utils/adminAudit'); + +describe('auditLogWhere', () => { + test('no filters → everything', () => { + expect(auditLogWhere({})).toEqual({}); + }); + + test('a "to" date includes that whole day', () => { + const where = auditLogWhere({ from: '2026-10-01', to: '2026-10-28' }); + expect(where.createdAt.gte).toEqual(new Date('2026-10-01T00:00:00')); + expect(where.createdAt.lt).toEqual(new Date('2026-10-29T00:00:00')); + expect(where.createdAt.lte).toBeUndefined(); + }); + + test('a full timestamp is used as given', () => { + const where = auditLogWhere({ to: '2026-10-28T10:00:00.000Z' }); + expect(where.createdAt.lte).toEqual(new Date('2026-10-28T10:00:00.000Z')); + }); + + test('action and role filter exactly', () => { + expect(auditLogWhere({ action: 'refund_created', role: 'supervisor' })).toEqual({ action: 'refund_created', actorRole: 'supervisor' }); + }); + + test('search looks at the person, the target and the IP', () => { + const where = auditLogWhere({ search: ' #ab12 ' }); + expect(where.OR).toEqual([ + { actor: { name: { contains: '#ab12', mode: 'insensitive' } } }, + { actor: { email: { contains: '#ab12', mode: 'insensitive' } } }, + { targetType: { contains: '#ab12', mode: 'insensitive' } }, + { targetId: { startsWith: 'ab12' } }, + { ip: { startsWith: '#ab12' } }, + ]); + }); + + test('a blank search is ignored', () => { + expect(auditLogWhere({ search: ' ' }).OR).toBeUndefined(); + }); +}); diff --git a/apps/events/backend/tests/ai.test.ts b/apps/events/backend/tests/ai.test.ts new file mode 100644 index 0000000..8bbdabc --- /dev/null +++ b/apps/events/backend/tests/ai.test.ts @@ -0,0 +1,134 @@ +// AI helpers (2.0): what the buttons do, and how a helper call goes through the Hub (§3b). + +const mockCalls: Array> = []; +const mockSettings = new Map(); +const mockDb = { + appSetting: { + findUnique: jest.fn(async ({ where }: { where: { key: string } }) => (mockSettings.has(where.key) ? { key: where.key, value: mockSettings.get(where.key) } : null)), + upsert: jest.fn(async ({ where, update }: { where: { key: string }; update: { value: string } }) => { mockSettings.set(where.key, update.value); }), + }, + aiCall: { + count: jest.fn(async () => mockCalls.filter(c => c.outcome === 'ok').length), + create: jest.fn(async ({ data }: { data: Record }) => { mockCalls.push(data); return data; }), + deleteMany: jest.fn(async () => ({ count: 0 })), + }, + user: { findMany: jest.fn(async () => [{ email: 'admin@test.local' }]) }, +}; +jest.mock('../src/config/db', () => mockDb); + +const mockLicence = { connected: true, readOnly: false, state: 'active', claims: { limits: { aiMonthlyCapCents: 5000 } } as { limits: { aiMonthlyCapCents: number } } | null }; +jest.mock('../src/hub/licence', () => ({ licenceStatus: jest.fn(async () => mockLicence) })); + +class MockHubError extends Error { + constructor(message: string, public code: string, public statusCode: number, public data: unknown = null) { super(message); } +} +const mockPost = jest.fn(); +jest.mock('../src/hub/client', () => ({ PROTOCOL_VERSION: 1, HubError: MockHubError, signedPost: (...a: unknown[]) => mockPost(...a) })); +const mockMail = jest.fn(async (_m: unknown) => undefined); +jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true })); +jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) })); + +import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai'; + +const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over }); +const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 }; + +beforeEach(() => { + mockCalls.length = 0; + mockSettings.clear(); + mockPost.mockReset(); + mockMail.mockClear(); + mockLicence.connected = true; + mockLicence.readOnly = false; + mockLicence.claims = { limits: { aiMonthlyCapCents: 5000 } }; + clearAiStatusCache(); +}); + +describe('status', () => { + test('a licence without AI never asks the Hub', async () => { + mockLicence.claims = { limits: { aiMonthlyCapCents: 0 } }; + expect(await aiStatus()).toMatchObject({ enabled: false, capReached: false }); + mockLicence.connected = false; + expect((await aiStatus()).enabled).toBe(false); + expect(mockPost).not.toHaveBeenCalled(); + }); + + test('asks the Hub and caches its answer for a minute', async () => { + mockPost.mockResolvedValue(hubStatus()); + expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } }); + await aiStatus(); + expect(mockPost).toHaveBeenCalledTimes(1); + expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 }); + }); + + test('a Hub without AI (404) means off; an unreachable Hub keeps the buttons, marked unavailable', async () => { + mockPost.mockRejectedValueOnce(new MockHubError('Not found', 'NOT_FOUND', 404)); + expect((await aiStatus()).enabled).toBe(false); + clearAiStatusCache(); + mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502)); + expect(await aiStatus()).toMatchObject({ enabled: true, available: false }); + }); +}); + +describe('running a helper', () => { + test('sends the request to the Hub, logs the call, returns the answer', async () => { + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) }); + const r = await runHelper('draft_message', 'u1', req); + expect(r.output).toBe('Hi all!'); + expect(r.status.usedCents).toBe(100.31); + expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 }); + expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]); + }); + + test('a helper switched off, or the cap reached, never reaches the Hub', async () => { + mockPost.mockResolvedValue(hubStatus({ capReached: true })); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ code: 'FORBIDDEN', reason: 'AI_CAP_REACHED' }); + clearAiStatusCache(); + mockPost.mockResolvedValue(hubStatus()); + await saveAiSettings({ helpers: { draft_message: false } }, { id: 'a1', role: 'admin' }); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_HELPER_OFF' }); + expect(mockPost).not.toHaveBeenCalledWith('/api/installs/ai/complete', expect.anything(), expect.anything()); + }); + + test('the per-person daily limit', async () => { + await saveAiSettings({ dailyLimitPerPerson: 1 }, { id: 'a1', role: 'admin' }); + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'x', chargedCents: 0.1, status: hubStatus() }); + await runHelper('draft_message', 'u1', req); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ code: 'RATE_LIMITED', reason: 'AI_DAILY_LIMIT' }); + }); + + test('the Hub refusing at the cap updates the status, so the buttons disable at once', async () => { + mockPost.mockResolvedValueOnce(hubStatus()) + .mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) })); + await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') }); + expect((await aiStatus()).capReached).toBe(true); + expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 }); + }); + + test('admins are emailed once a month at 80%', async () => { + const at80 = hubStatus({ usedPercent: 81, usedCents: 4050 }); + mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValue({ output: 'x', chargedCents: 1, status: at80 }); + await runHelper('draft_message', 'u1', req); + await runHelper('draft_message', 'u1', req); + expect(mockMail).toHaveBeenCalledTimes(1); + expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]); + }); +}); + +describe('Hub errors', () => { + test.each([ + ['AI_REFUSED', 'UNAVAILABLE', 'refused'], + ['AI_INCOMPLETE', 'UNAVAILABLE', 'incomplete'], + ['AI_OFF', 'FORBIDDEN', 'unavailable'], + ['HUB_UNREACHABLE', 'UNAVAILABLE', 'unavailable'], + ])('%s → %s, logged as %s', (hubCode, code, outcome) => { + const r = _internal.fromHubError({ code: hubCode, message: 'x' }); + expect(r.error.code).toBe(code); + expect(r.outcome).toBe(outcome); + }); + + test('today starts at midnight South African time', () => { + expect(_internal.startOfToday(new Date('2026-11-10T22:30:00Z')).toISOString()).toBe('2026-11-10T22:00:00.000Z'); + expect(_internal.startOfToday(new Date('2026-11-10T10:00:00Z')).toISOString()).toBe('2026-11-09T22:00:00.000Z'); + }); +}); diff --git a/apps/events/backend/tests/aiHelpers.test.ts b/apps/events/backend/tests/aiHelpers.test.ts new file mode 100644 index 0000000..d1b8fd4 --- /dev/null +++ b/apps/events/backend/tests/aiHelpers.test.ts @@ -0,0 +1,139 @@ +// The five AI helpers (2.0): what they send, what they keep back, and the checks done in code. + +const mockRun = jest.fn(); +jest.mock('../src/ai/index', () => ({ runHelper: (...a: unknown[]) => mockRun(...a) })); +jest.mock('../src/config/db', () => ({})); + +import { + todayLine, protect, restore, weekdayClashes, eventWarnings, reportText, feedbackText, + draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer, +} from '../src/ai/helpers'; + +const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} }; +const now = new Date('2026-10-30T08:00:00Z'); + +beforeEach(() => mockRun.mockReset()); + +const camp: EventDraftAnswer = { + title: 'Rooted Youth Camp', summary: '', description: '', startDate: '2027-03-14', startTime: '18:00', endDate: '2027-03-16', endTime: '14:00', + location: 'Camp Wartburg', capacity: 60, needsParentalConsent: true, ageGroup: 'Grades 8–12', + ticketOptions: [{ name: 'Camper', priceRand: 450, description: '', earlyBirdPriceRand: 400, earlyBirdUntil: '2027-01-31' }], + sessions: [], + costs: [ + { item: 'Venue', basis: 'R180 × 60 × 2', amountRand: 21600 }, { item: 'Bus', basis: '', amountRand: 6500 }, + { item: 'Speaker gift', basis: '', amountRand: 1000 }, { item: 'T-shirts', basis: 'R95 × 60', amountRand: 5700 }, + ], + checks: [], +}; + +describe('today and contact details', () => { + test('today is given in South African time', () => { + expect(todayLine(now)).toBe('Today is Friday 30 October 2026.'); + expect(todayLine(new Date('2026-10-30T22:30:00Z'))).toBe('Today is Saturday 31 October 2026.'); + }); + + test('emails, phone numbers and ID numbers never leave the site, and come back in the answer', () => { + const p = protect('Call Sarah on 082 555 1234 or +27 21 555 9876, email youth@church.co.za. ID 9001015009087. Bus R6 500 at 07:30.'); + // Emails are found first, then phone numbers, then ID numbers. + expect(p.text).toBe('Call Sarah on [[CONTACT2]] or [[CONTACT3]], email [[CONTACT1]]. ID [[CONTACT4]]. Bus R6 500 at 07:30.'); + expect(restore({ body: 'Questions? [[CONTACT1]] or [[CONTACT2]].', list: ['[[CONTACT3]]'] }, p.found)) + .toEqual({ body: 'Questions? youth@church.co.za or 082 555 1234.', list: ['+27 21 555 9876'] }); + }); + + test('the same detail twice gets one placeholder', () => { + expect(protect('a@b.co.za and again a@b.co.za').text).toBe('[[CONTACT1]] and again [[CONTACT1]]'); + }); +}); + +describe('checks done in code', () => { + test('a weekday that does not match its date', () => { + expect(weekdayClashes('Youth camp Fri 14 March to Sun 16 March', 2027)).toEqual([ + 'The notes say Friday 14 March, but 14 March 2027 is a Sunday. Check the dates.', + 'The notes say Sunday 16 March, but 16 March 2027 is a Tuesday. Check the dates.', + ]); + expect(weekdayClashes('Fri 14 March', 2025)).toEqual([]); + }); + + test('an event that loses money even when full', () => { + expect(eventWarnings('', camp)).toEqual([ + 'The costs in the notes come to R34 800, which needs 78 places at R450 — more than the 60 available. Even full, the event takes R27 000 (R24 000 if everyone books early), R7 800 short.', + ]); + expect(eventWarnings('', { ...camp, capacity: 80 })).toEqual([]); + expect(eventWarnings('', { ...camp, endDate: '2027-03-13' })).toContain('The end is before the start.'); + }); +}); + +describe('what the helpers send', () => { + test('draft an event: today\'s date, a schema, contact details kept back; code warnings added', async () => { + mockRun.mockResolvedValue({ output: { ...camp, description: 'Questions? [[CONTACT1]]' }, status }); + const r = await draftEvent('u1', 'Youth camp Fri 14 March, R450, 60 places. Questions: youth@church.co.za', now); + const [helper, user, req] = mockRun.mock.calls[0]; + expect([helper, user]).toEqual(['draft_event', 'u1']); + expect(req.system).toContain('Today is Friday 30 October 2026.'); + expect(req.input).not.toContain('youth@church.co.za'); + expect(req.schema.required).toContain('ticketOptions'); + expect(r.draft.description).toBe('Questions? youth@church.co.za'); + expect(r.totalCostRand).toBe(34800); + expect(r.breakEvenPlaces).toBe(78); + expect(r.warnings.some(w => w.includes('is a Sunday'))).toBe(true); + expect(r.warnings.some(w => w.includes('R7 800 short'))).toBe(true); + }); + + test('summarise a report: people reports only as anonymised totals', async () => { + for (const columns of [['Event', 'User', 'Amount'], ['Event', 'Email'], ['Event', 'Performed by', 'Notes'], ['Event', 'Attendee', 'Medical'], ['Parent / guardian']]) { + await expect(summariseReport('u1', { reportKey: 'payments', title: 'Payments', columns, rows: [['Jane']] })).rejects.toMatchObject({ reason: 'AI_REPORT_HAS_PEOPLE' }); + } + await expect(summariseReport('u1', { reportKey: 'nope', title: 'X', columns: ['A'], rows: [[1]] })).rejects.toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mockRun).not.toHaveBeenCalled(); + mockRun.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status }); + await summariseReport('u1', { reportKey: 'medicalList', title: 'Medical', columns: ['Event', 'Attendees', 'With allergies', 'With medical aid'], rows: [['Camp', 40, 6, 30]] }, now); + await summariseReport('u1', { reportKey: 'feedbackSummary', title: 'Feedback', columns: ['Event', 'Question', 'Answered', 'Result'], rows: [['Camp', 'Overall', 12, '4.5 / 5']] }, now); + expect(mockRun).toHaveBeenCalledTimes(2); + mockRun.mockReset(); + mockRun.mockResolvedValue({ output: { headline: 'h', insights: [], watchOut: [] }, status }); + await summariseReport('u1', { reportKey: 'revenue', title: 'Revenue Summary', stats: [{ label: 'Total', value: 'R66 550' }], columns: ['Event', 'Amount'], rows: [['Camp', 'R16 650']] }, now); + expect(mockRun.mock.calls[0][2].input).toBe('Report: Revenue Summary\nTotal: R66 550\nColumns: Event | Amount\nCamp | R16 650'); + }); + + test('report text is capped at 400 rows', () => { + const t = reportText({ reportKey: 'usage', title: 'T', columns: ['A'], rows: Array.from({ length: 450 }, (_, i) => [i]) }); + expect(t).toContain('(50 more rows not shown)'); + expect(t.split('\n')).toHaveLength(2 + 400 + 1); + }); + + test('feedback text: averages, counts and numbered comments, no names', () => { + expect(feedbackText({ title: 'Women\'s Conference' }, 112, 186, [ + { label: 'Overall', type: 'rating', answered: 112, average: 4.4 }, + { label: 'Come again?', type: 'yes_no', answered: 100, counts: [{ label: 'Yes', value: 90 }, { label: 'No', value: 10 }] }, + { label: 'Comments', type: 'text', answered: 2, texts: ['Hall B sound please fix it.', 'Loved the worship!'] }, + ])).toBe([ + 'Event: Women\'s Conference', 'Responses: 112 of 186 asked', 'Overall — average 4.4 (112 answers)', 'Come again? — Yes: 90, No: 10', + 'Comments — comments:', '1. Hall B sound please fix it.', '2. Loved the worship!', + ].join('\n')); + }); + + test('draft a message: WhatsApp has no subject; the event is given as facts', async () => { + mockRun.mockResolvedValue({ output: { subject: 'ignored', body: 'Hi {{name}}!' }, status }); + const r = await draftMessage('u1', { channel: 'whatsapp', note: 'bring a sleeping bag', event: { title: 'Youth Camp', start: 'Friday 14 March 2027, 18:00', location: 'Camp Wartburg' } }, now); + expect(r.message).toEqual({ subject: '', body: 'Hi {{name}}!' }); + expect(mockRun.mock.calls[0][2].input).toBe('Note: bring a sleeping bag\n\nEvent: Youth Camp, Friday 14 March 2027, 18:00, at Camp Wartburg'); + expect(mockRun.mock.calls[0][2].system).toContain('WhatsApp'); + expect(mockRun.mock.calls[0][2].system).toContain('{{event.title}}'); + }); + + test('draft a message without an event: no event placeholders offered', async () => { + mockRun.mockResolvedValue({ output: { subject: 'S', body: 'Hi {{name}}' }, status }); + await draftMessage('u1', { channel: 'email', note: 'the breakfast moves to the hotel' }, now); + const system = mockRun.mock.calls[0][2].system; + expect(system).toContain('Use no other {{…}} placeholders'); + expect(system).not.toContain('{{event.title}}'); + }); + + test('improve text: the mode and where it goes shape the instructions', async () => { + mockRun.mockResolvedValue({ output: { text: 'Fixed.', changes: [] }, status }); + await improveText('u1', { text: 'join us for are anual fun day', mode: 'fix', where: 'banner' }); + const req = mockRun.mock.calls[0][2]; + expect(req.system).toContain('a short banner across the top of the website'); + expect(req.system).toContain('Only fix spelling, grammar and punctuation'); + }); +}); diff --git a/apps/events/backend/tests/allocation.test.js b/apps/events/backend/tests/allocation.test.js new file mode 100644 index 0000000..f9704b3 --- /dev/null +++ b/apps/events/backend/tests/allocation.test.js @@ -0,0 +1,84 @@ +const { joinBlocker, autoAllocate, cleanGender } = require('../src/utils/allocation'); + +const person = (id, registrationId, gender = null) => ({ id, name: id, registrationId, gender }); +const groupsOf = (result) => { + const out = {}; + for (const p of result.placements) (out[p.groupId] = out[p.groupId] || []).push(p.attendeeId); + return out; +}; + +describe('cleanGender', () => { + test('accepts male/female in any case, blank as null', () => { + expect(cleanGender('Male')).toBe('male'); + expect(cleanGender('')).toBeNull(); + expect(() => cleanGender('other')).toThrow(); + }); +}); + +describe('joinBlocker', () => { + test('capacity', () => { + expect(joinBlocker({ name: 'Cabin 1', capacity: 2 }, 1, [person('a', 'r')])).toBeNull(); + expect(joinBlocker({ name: 'Cabin 1', capacity: 2 }, 2, [person('a', 'r')])).toMatch(/full/); + }); + + test('gender', () => { + expect(joinBlocker({ name: 'Boys', gender: 'male' }, 0, [person('a', 'r', 'male')])).toBeNull(); + expect(joinBlocker({ name: 'Boys', gender: 'male' }, 0, [person('a', 'r', 'female')])).toMatch(/males only/); + expect(joinBlocker({ name: 'Boys', gender: 'male' }, 0, [person('a', 'r')])).toMatch(/no gender recorded/); + }); +}); + +describe('autoAllocate', () => { + test('fills groups evenly', () => { + const groups = [{ id: 'g1', name: 'A' }, { id: 'g2', name: 'B' }]; + const attendees = ['a', 'b', 'c', 'd'].map(id => person(id, id)); + const r = autoAllocate({ groups, attendees }); + const g = groupsOf(r); + expect(g.g1.length).toBe(2); + expect(g.g2.length).toBe(2); + expect(r.unplaced).toEqual([]); + }); + + test('respects capacity and reports who could not be placed', () => { + const groups = [{ id: 'g1', name: 'A', capacity: 1 }]; + const r = autoAllocate({ groups, attendees: [person('a', 'r1'), person('b', 'r2')] }); + expect(r.placements.length).toBe(1); + expect(r.unplaced.length).toBe(1); + }); + + test('respects gender', () => { + const groups = [{ id: 'boys', name: 'Boys', gender: 'male' }, { id: 'girls', name: 'Girls', gender: 'female' }]; + const r = autoAllocate({ groups, attendees: [person('a', 'r1', 'male'), person('b', 'r2', 'female'), person('c', 'r3')] }); + expect(groupsOf(r)).toEqual({ boys: ['a'], girls: ['b'] }); + expect(r.unplaced).toEqual(['c']); + }); + + test('keeps a registration together when a group can take them all', () => { + const groups = [{ id: 'g1', name: 'A', capacity: 3 }, { id: 'g2', name: 'B', capacity: 3 }]; + const attendees = [person('s1', 'fam'), person('s2', 'fam'), person('x', 'solo')]; + const g = groupsOf(autoAllocate({ groups, attendees, mode: 'together' })); + const famGroup = Object.keys(g).find(k => g[k].includes('s1')); + expect(g[famGroup]).toContain('s2'); + }); + + test('places siblings one by one when no group fits them all', () => { + const groups = [{ id: 'boys', name: 'Boys', gender: 'male' }, { id: 'girls', name: 'Girls', gender: 'female' }]; + const r = autoAllocate({ groups, attendees: [person('bro', 'fam', 'male'), person('sis', 'fam', 'female')], mode: 'together' }); + expect(groupsOf(r)).toEqual({ boys: ['bro'], girls: ['sis'] }); + }); + + test('split mode spreads a registration across groups', () => { + const groups = [{ id: 'g1', name: 'A' }, { id: 'g2', name: 'B' }]; + const attendees = [person('f1', 'friends'), person('f2', 'friends')]; + const g = groupsOf(autoAllocate({ groups, attendees, mode: 'split' })); + expect(g.g1.length).toBe(1); + expect(g.g2.length).toBe(1); + }); + + test('counts people already placed and leaves them where they are', () => { + const groups = [{ id: 'g1', name: 'A', capacity: 2 }, { id: 'g2', name: 'B', capacity: 2 }]; + const attendees = [person('a', 'r1'), person('b', 'r2'), person('c', 'r3')]; + const r = autoAllocate({ groups, attendees, assigned: new Map([['a', 'g1'], ['b', 'g1']]) }); + expect(r.placements).toEqual([{ attendeeId: 'c', groupId: 'g2' }]); + }); +}); diff --git a/apps/events/backend/tests/analytics.test.js b/apps/events/backend/tests/analytics.test.js new file mode 100644 index 0000000..9fbdbb1 --- /dev/null +++ b/apps/events/backend/tests/analytics.test.js @@ -0,0 +1,70 @@ +const { deviceFromUA, cleanSource, sessionsFrom, rollupRows, funnelReport } = require('../src/utils/analytics'); + +const ev = (sessionId, stage, day, extra = {}) => ({ sessionId, stage, createdAt: `${day}T10:00:00Z`, ...extra }); + +describe('deviceFromUA', () => { + test('mobile, tablet, desktop and bots', () => { + expect(deviceFromUA('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148')).toBe('mobile'); + expect(deviceFromUA('Mozilla/5.0 (Linux; Android 14; SM-X200) Safari')).toBe('tablet'); + expect(deviceFromUA('Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120')).toBe('desktop'); + expect(deviceFromUA('Googlebot/2.1')).toBeNull(); + expect(deviceFromUA('')).toBeNull(); + }); +}); + +describe('cleanSource', () => { + test('tidies, defaulting to direct', () => { + expect(cleanSource(' Facebook ')).toBe('facebook'); + expect(cleanSource('camp-2025`); + w.document.close(); + } catch (e) { + setError(errorMessage(e) || "Couldn't load the lists"); + } + }; + + return ( +

+
+
+ +
+
+ +

Rooms & groups

+

Put attendees into rooms, small groups, teams or buses

+
+
+ + {!canView &&
You need supervisor access to manage allocations.
} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + { setEventId(id); setSetId(""); }} /> +
+ {board && ( +
+ {board.sets.map(s => ( + + ))} + setNewSetName(e.target.value)} onKeyDown={e => { if (e.key === "Enter") addSet(); }} /> + +
+ )} +
+ + {board && board.attendees.length === 0 && ( +
+ No named attendees yet. Allocation works per person, so it needs names — turn on "Named attendees" for the event{board.event.collectGender ? "" : " (and \"Ask each person's gender\" if rooms are split by gender)"}. +
+ )} + {board && board.unnamedPlaces > 0 && ( +

{board.unnamedPlaces} place(s) have no name yet, so they can't be placed until the person booking adds names.

+ )} + + {current && board && ( + <> +
+ +
+ + + + + {board.event.requiresParentalConsent && ( + + )} + + +
+
+ + {groupForm ? ( +
+
setGroupForm({ ...groupForm, name: e.target.value })} placeholder="Cabin 1" autoFocus />
+
setGroupForm({ ...groupForm, capacity: e.target.value })} placeholder="No limit" />
+
+ +
+
+ +
+ + +
+ ) : ( + + )} + + +
+
+ + {unassigned.map(p => )} + +
+
+ {current.groups.length === 0 &&

Add groups (rooms, cabins, buses…) to start placing people.

} + {current.groups.map(g => { + const members = membersOf(g.id); + const full = g.capacity != null && members.length >= g.capacity; + const subtitle = [`${members.length}${g.capacity ? ` / ${g.capacity}` : ""}${full ? " · full" : ""}`, g.gender ? (g.gender === "male" ? "males" : "females") : "", g.leader ? `leader ${g.leader.name}` : ""].filter(Boolean).join(" · "); + return ( + + + +
+ }> + {members.map(p => )} + + ); + })} +
+
+ + + )} + {board && board.sets.length === 0 && board.attendees.length > 0 && ( +

Start by adding a set, e.g. "Rooms", "Small groups" or "Buses". An event can have several.

+ )} +
+ )} + + ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx new file mode 100644 index 0000000..1dea102 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -0,0 +1,2111 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { useAuth } from "@/hooks/useAuth"; +import { useRouter } from "next/navigation"; +import { fetchManagedEvents, fetchEvent } from "@/lib/api"; +import { scoreUser } from "@/lib/fuzzyMatch"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField"; +import { BundleBuilder, BundleOffers, BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals"; +import { BackLink } from "@/components/shared/BackLink"; +import { TransferTicketModal, canOfferTransfer } from "@/components/shared/TransferTicketModal"; +import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor"; +import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react"; +import { errorMessage } from "@/lib/utils"; +import { optionUnitNow, variantUnitNow } from "@/lib/pricing"; +import { printTicketCards, ticketTypeLabel as ticketLabel } from "@/lib/ticketPrint"; +import { bookableSessions, choosesSessions, isPickOption, todaysSession } from "@/lib/sessions"; +import { SessionPicker } from "@/components/events/SessionPicker"; +import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRecord, UserSummary } from "@/types"; +import { EventPicker } from "@/components/shared/EventPicker"; +import { AttendeeFormModal, formsStillNeeded } from "@/components/shared/AttendeeFormModal"; +import { apiV2, apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; + +type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" }; + +// GET /api/tickets/event/:id — a bare list (older builds wrapped it in `tickets` or `data`). +type EventTicketsResponse = TicketRecord[] | { tickets?: TicketRecord[]; data?: TicketRecord[] }; +const ticketsFrom = (res: EventTicketsResponse | null | undefined): TicketRecord[] => + Array.isArray(res) ? res : (res?.tickets || res?.data || []); + +type Mode = "registration" | "payment" | "checkin" | "tickets" | "refund"; + +const MODE_LABELS: Record = { + registration: "REGISTRATION", + payment: "PAYMENT", + checkin: "CHECK-IN", + tickets: "TICKETS", + refund: "REFUND", +}; + +const MODE_ICONS: Record = { + registration: UserPlus, + payment: CreditCard, + checkin: CheckSquare, + tickets: Ticket, + refund: RotateCcw, +}; + +// ─── Fuzzy search helpers ───────────────────────────────────────────────────── + +function fuzzyFilterRegs(allRegs: Registration[], search: string): Registration[] { + if (!search) return allRegs; + if (search.length === 1) { + const q = search.toLowerCase(); + return allRegs.filter(r => + String(r.user?.name || "").toLowerCase().includes(q) || + String(r.user?.email || "").toLowerCase().includes(q) || + String(r.user?.phoneNumber || "").includes(q) + ); + } + return allRegs + .map(r => ({ r, score: scoreUser(r.user || {}, search) })) + .filter(x => x.score >= 0.45) + .sort((a, b) => b.score - a.score) + .map(x => x.r); +} + +// ─── Pricing helpers ───────────────────────────────────────────────────────── + +// Total due on a registration: the backend's tranche-aware total when present, else +// the sum of its lines at their snapshot (or current list) prices. +function registrationTotal(r: Registration): number { + return r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => { + const price = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) + ? Number(opt.priceSnapshot) + : (opt.eventOption?.price ?? 0); + return sum + price * (opt.quantity || 0); + }, 0); +} + +const totalPaidOn = (r: Registration) => (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0); + +function initQuantities(eventOptions: EventOption[]): Record { + const map: Record = {}; + (eventOptions || []).forEach((o) => { + if ((o.variants || []).length > 0) { + (o.variants || []).forEach((v) => { map[`${o.id}::${v.id}`] = 0; }); + } else { + map[o.id] = 0; + } + }); + return map; +} + +export default function AtTheDoorPage() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const [events, setEvents] = useState([]); + const [eventId, setEventId] = useState(""); + + const [eventOptions, setEventOptions] = useState([]); + const [doorHasPickOptions, setDoorHasPickOptions] = useState(false); + // "Pick sessions" events: the event (for its sessions) and the sessions chosen per + // quantity key. Picked sessions are booked on new registrations only. + const [doorEvent, setDoorEvent] = useState(null); + const [picks, setPicks] = useState>({}); + const [showOptionsModal, setShowOptionsModal] = useState(false); + const [pendingUser, setPendingUser] = useState(null); + const [doorCoupon, setDoorCoupon] = useState(null); + const [doorAllowsNames, setDoorAllowsNames] = useState(false); + const [doorYouthStart, setDoorYouthStart] = useState(null); + const [doorCollectGender, setDoorCollectGender] = useState(false); + const [doorBundles, setDoorBundles] = useState([]); + const [doorNaming, setDoorNaming] = useState(false); + const [doorEntries, setDoorEntries] = useState({}); + const [doorDelivery, setDoorDelivery] = useState("payer"); + const [pendingEditReg, setPendingEditReg] = useState(null); + const [confirming, setConfirming] = useState(false); + const [quantities, setQuantities] = useState>({}); + // Already-issued ticket quantity per option/variant, keyed like `quantities` — a + // registration being edited can never drop an item below this (tickets are never + // deleted or shrunk, only ever grown, once paid). + const [minQuantities, setMinQuantities] = useState>({}); + + const [showDonationModal, setShowDonationModal] = useState(false); + const [donationUser, setDonationUser] = useState(null); + + const [showNewAttendeeModal, setShowNewAttendeeModal] = useState(false); + const [newAttendeeSeed, setNewAttendeeSeed] = useState(""); + + useEffect(() => { + if (!token) return; + (async () => { + try { + const evs = await fetchManagedEvents(token); + const now = Date.now(); + + const active = (evs || []).filter(ev => { + const t = new Date(ev.endDate).getTime(); + // Registrations/payments are rejected server-side for closed (cashed-up) + // events — don't offer them here. + return !isNaN(t) && t > now && ev.cashupStatus !== 'closed'; + }); + + active.sort( + (a, b) => + new Date(a.startDate).getTime() - + new Date(b.startDate).getTime() + ); + + setEvents(active); + + if (active.length > 0) { + setEventId(active[0].id); // default + } + } catch {} + })(); + }, [token]); + + useEffect(() => { + if (!token || !eventId) return; + + (async () => { + try { + const ev = await fetchEvent(eventId, { + authToken: token + }); + + const all = ev.options || ev.eventOptions || []; + setDoorEvent(ev); + setEventOptions(all); + setDoorHasPickOptions(choosesSessions(ev)); + setDoorAllowsNames(!!ev.allowNamedAttendees || !!ev.requiresParentalConsent); + setDoorYouthStart(ev.requiresParentalConsent ? ev.startDate : null); + setDoorCollectGender(!!ev.collectGender); + setDoorBundles(ev.bundles || []); + } catch { + setDoorEvent(null); + setEventOptions([]); + setDoorBundles([]); + } + })(); + }, [eventId, token]); + + const canView = useMemo(() => { + const role = user?.role; + return role === "admin" || role === "supervisor" || role === "staff"; + }, [user]); + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [mode, setMode] = useState("registration"); + + const [activeRegistration, setActiveRegistration] = useState(null); + const [info, setInfo] = useDismissingState(null); + const [error, setError] = useDismissingState(null); + + // A required attendee form holds the tickets back: it pops up to fill in now, or "Fill in + // later" (tickets are issued anyway and the attendee gets a link). + const [formPrompt, setFormPrompt] = useState<{ registration: Registration; needed: number } | null>(null); + const loadFull = (id: string) => apiV2Data("get", "/registrations/{id}/full", { params: { id }, authToken: token }) as Promise; + const promptFormFor = (full: Registration) => { + const needed = formsStillNeeded(doorEvent?.form, full); + if (needed > 0 && full.status !== "cancelled") setFormPrompt({ registration: full, needed }); + return needed; + }; + + const handleRegistrationCreated = (registration: Registration) => { + setActiveRegistration(registration); // 🚀 Jump automatically (see effect below) + if ((registration.formsNeeded || 0) > 0) setFormPrompt({ registration, needed: registration.formsNeeded || 0 }); + }; + + const handleRegistrationSelected = (registration: Registration) => { + setActiveRegistration(registration); + // The search list doesn't carry the forms, so look at the whole registration. + loadFull(registration.id).then(promptFormFor).catch(() => {}); + }; + + const handleFormDone = async ({ later, ticketsIssued, sentTo }: { later: boolean; ticketsIssued: number; sentTo?: string[] }) => { + const reg = formPrompt?.registration; + setFormPrompt(null); + const issued = ticketsIssued > 0 ? " Tickets issued." : ""; + setInfo(later + ? `Form left for later${sentTo && sentTo.length ? ` — a link was sent by ${sentTo.join(" and ")}` : ""}.${issued}` + : `Attendee form saved.${issued}`); + if (reg) { + try { setActiveRegistration(await loadFull(reg.id)); } catch {} + } + }; + + useEffect(() => { + if (!activeRegistration) return; + + const id = setTimeout(() => { + // Fully paid → head straight to check-in; otherwise there's still a + // balance to collect, so go capture payment first. + setMode(activeRegistration.status === "paid" ? "checkin" : "payment"); + }, 0); + + return () => clearTimeout(id); + + }, [activeRegistration]); + + // Charged per session / has sessions to tick (every ticket on a "pick sessions" event). + const isPick = (optionId: string) => isPickOption(doorEvent, eventOptions.find(o => o.id === optionId)); + const choosing = choosesSessions(doorEvent); + + const confirmRegistration = async () => { + if (confirming) return; + + const opts = Object.entries(quantities) + .filter(([, qty]) => qty > 0) + .map(([key, quantity]) => { + const [eventOptionId, variantId] = key.split("::"); + return { eventOptionId, quantity, ...(variantId ? { variantId } : {}), ...(choosing && !pendingEditReg ? { sessionIds: picks[key] || [] } : {}) }; + }); + + if (!opts.length) { + setError("Select at least one item"); + return; + } + const noSessions = opts.find(o => "sessionIds" in o && o.sessionIds && o.sessionIds.length === 0); + if (noSessions) { + setError(`Choose the sessions for "${eventOptions.find(o => o.id === noSessions.eventOptionId)?.name || "the ticket"}".`); + return; + } + + for (const [key, minQty] of Object.entries(minQuantities)) { + if (minQty > 0 && (quantities[key] || 0) < minQty) { + const [eventOptionId, variantId] = key.split("::"); + const opt = eventOptions.find((o) => o.id === eventOptionId); + const variant = variantId ? (opt?.variants || []).find((v) => v.id === variantId) : null; + const label = variant ? `${opt?.name || "item"} (${variant.name})` : (opt?.name || "item"); + setError(`Cannot reduce "${label}" below the ${minQty} already issued`); + return; + } + } + + if (!pendingEditReg && doorYouthStart) { + const missing = consentDetailsMissing(eventOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries, doorYouthStart); + if (missing) { setError(missing); return; } + } + + // Picked-session lines take no names. + const nameOptions = eventOptions.filter(o => !isPick(o.id)); + setConfirming(true); + try { + if (pendingEditReg) { + // Edit existing registration — replace options via PUT + let res = await (apiV2Data("put", "/registrations/{id}/items", { + params: { id: pendingEditReg.id }, + authToken: token, + body: { options: opts }, + }) as Promise); + let message = "Registration updated"; + if (doorCoupon) { + // Applied after the items are saved, so it's worked out on the final items. + try { + res = await (apiV2Data("post", "/registrations/{id}/coupon", { + params: { id: pendingEditReg.id }, + authToken: token, + body: { code: doorCoupon.code }, + }) as Promise); + message = `Registration updated — code ${doorCoupon.code} applied`; + } catch (ce) { + message = `Registration updated, but the code wasn't applied: ${errorMessage(ce) || "unknown error"}`; + } + } + setShowOptionsModal(false); + setPendingEditReg(null); + setInfo(message); + handleRegistrationSelected(res); + } else if (pendingUser) { + // New attendee + const res = await (apiV2Data("post", "/registrations/manual", { + authToken: token, + body: { + eventId, + user: { + name: pendingUser.name, + ...(pendingUser.email ? { email: pendingUser.email } : {}), + ...(pendingUser.phone ? { phoneNumber: pendingUser.phone } : {}), + }, + options: opts, + notificationPreference: pendingUser.notifPref, + ...(doorCoupon ? { couponCode: doorCoupon.code } : {}), + ...(doorAllowsNames && (doorNaming || doorYouthStart) && attendeesPayload(nameOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries).length > 0 + ? { attendees: attendeesPayload(nameOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries), ticketDelivery: doorDelivery } + : {}), + }, + }) as Promise); + setShowOptionsModal(false); + if (res?.couponError) setError(`Registered, but the code wasn't applied: ${res.couponError}`); + handleRegistrationCreated(res); + } + } catch (e) { + setError(errorMessage(e) || "Failed"); + } finally { + setConfirming(false); + } + }; + + // Opens the new-attendee modal (pre-filled with whatever the user typed in search) + const handleShowNewAttendee = (seed: string) => { + setNewAttendeeSeed(seed); + setShowNewAttendeeModal(true); + }; + + // Called when NewAttendeeModal is confirmed — proceed to options selection + const handleNewAttendeeConfirm = ({ name, email, phone, notifPref }: { name: string; email: string; phone: string; notifPref: "email" | "whatsapp" | "both" }) => { + const qtyMap = initQuantities(eventOptions); + const pickMap: Record = {}; + // Default main ticket to 1 (first variant if variants exist). On a "pick sessions" + // event with a session today that still has room, that's one place in today's session. + const today = todaysSession(doorEvent); + const todayPick = today && doorEvent && choosing ? eventOptions.find(o => o.isMainTicket + && bookableSessions(doorEvent, o, true).some(s => s.id === today.id && (s.left === null || s.left > 0))) : undefined; + eventOptions.forEach(o => { + if (!o.isMainTicket || (todayPick ? o !== todayPick : choosing)) return; + const key = (o.variants || []).length > 0 ? `${o.id}::${(o.variants || [])[0].id}` : o.id; + qtyMap[key] = 1; + if (o === todayPick && today) pickMap[key] = [today.id]; + }); + setQuantities(qtyMap); + setPicks(pickMap); + setMinQuantities({}); + setPendingUser({ name, email: email || null, phone: phone || null, notifPref }); + setPendingEditReg(null); + setDoorCoupon(null); + setDoorNaming(false); + setDoorEntries({}); + setDoorDelivery("payer"); + setShowNewAttendeeModal(false); + setShowOptionsModal(true); + }; + + // Edit an existing registration — pre-fill with current quantities. + // Re-fetches the registration fresh rather than trusting the (possibly up to 5-minutes-stale, + // see DoorRegistrationPanel's polling interval) cached search-result snapshot, so the + // already-issued-ticket floor below is always computed from current data. + const handleEditRegistration = async (reg: Registration) => { + let freshReg = reg; + try { + freshReg = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: reg.id }, authToken: token }) as Promise); + } catch (e) { + setError(errorMessage(e) || "Failed to load latest registration data"); + return; + } + + const qtyMap = initQuantities(eventOptions.filter(o => !isPick(o.id))); + const regOptions = (freshReg.registrationOptions || []).filter(ro => !ro.sessionId); + regOptions.forEach((ro) => { + const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId; + if (key in qtyMap) qtyMap[key] = ro.quantity || 0; + }); + + // Already-issued ticket quantity per option/variant — floor for the edit below + const minQtyMap: Record = {}; + regOptions.forEach((ro) => { + const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId; + const issuedQty = (ro.tickets || []).reduce((s, t) => s + (t.quantity || 0), 0); + if (issuedQty > 0) minQtyMap[key] = (minQtyMap[key] || 0) + issuedQty; + }); + + setQuantities(qtyMap); + setPicks({}); + setMinQuantities(minQtyMap); + setPendingEditReg(freshReg); + setPendingUser(null); + setDoorCoupon(null); + setShowOptionsModal(true); + }; + + const handlePaymentCaptured = async (registration?: Registration, partial?: boolean) => { + + if (partial && registration) { + setActiveRegistration(registration); + setInfo("Partial payment recorded"); + return; + } + + if (!registration && !activeRegistration) return; + + const reg = registration || activeRegistration; + + // Tickets are generated and emailed/WhatsApped automatically server-side + // once a registration reaches "paid" (see paymentController) — no need to + // fetch/print them here, just move straight to checking the attendee in. + // Unless a required attendee form holds them back: that pops up first. + setActiveRegistration(reg); + setMode("checkin"); + if (reg && promptFormFor(reg) > 0) { + setInfo("Payment recorded — fill in the attendee form (or choose Fill in later) to issue the tickets."); + return; + } + setInfo("Payment recorded — tickets sent. Ready to check in."); + }; + + const handleDonation = (user?: UserSummary) => { + setDonationUser(user || null); // null = anonymous + setShowDonationModal(true); + }; + + return ( +
+ +
+
+
+ +
+
+ +

At The Door

+
+
+ + +
+ + {!canView && ( +
+ Access denied. +
+ )} + + {error && ( +
+ {error} +
+ )} + + {info && ( +
+ {info} +
+ )} + + {/* Mode Buttons */} +
+ {(["registration", "payment", "checkin", "tickets", "refund"] as Mode[]).map(m => { + const Icon = MODE_ICONS[m]; + return ( + + ); + })} +
+ + {/* ✅ Panels */} + {mode === "registration" && ( + + )} + + {mode === "payment" && ( + + )} + + {mode === "checkin" && ( + loadFull(activeRegistration.id).then(full => { + if (promptFormFor(full) === 0) setError("No attendee form is outstanding. If the tickets are still missing, an admin can issue them in Corrections."); + }).catch(e => setError(errorMessage(e) || "Couldn't load the registration")) : undefined} + /> + )} + + {mode === "tickets" && ( + + )} + + {mode === "refund" && ( + + )} + { setShowOptionsModal(false); setPendingEditReg(null); }} + options={pendingEditReg ? eventOptions.filter(o => !isPick(o.id)) : eventOptions} + pick={doorEvent && doorHasPickOptions ? { event: doorEvent, picks, setPicks } : null} + quantities={quantities} + setQuantities={setQuantities} + minQuantities={minQuantities} + onConfirm={confirmRegistration} + confirming={confirming} + isEdit={!!pendingEditReg} + totalPaid={pendingEditReg ? totalPaidOn(pendingEditReg) : 0} + eventId={eventId} + token={token} + coupon={doorCoupon} + setCoupon={setDoorCoupon} + couponForUserId={pendingEditReg ? pendingEditReg.userId : null} + existingCode={(pendingEditReg?.couponRedemptions || [])[0]?.coupon?.code || null} + bundles={doorBundles} + names={doorAllowsNames && !pendingEditReg ? { + enabled: doorNaming, onEnabledChange: setDoorNaming, + entries: doorEntries, onEntriesChange: setDoorEntries, + delivery: doorDelivery, onDeliveryChange: setDoorDelivery, + consentEventStart: doorYouthStart || undefined, + collectGender: doorCollectGender, + } : null} + /> + setShowDonationModal(false)} + user={donationUser} + token={token} + eventId={eventId} + setError={setError} + /> + setShowNewAttendeeModal(false)} + seed={newAttendeeSeed} + onConfirm={handleNewAttendeeConfirm} + /> + {formPrompt && ( + + )} +
+ ); +} + +function DoorRegistrationPanel({ token, eventId, onSelected, onEditRegistration, onNewAttendee, onDonation }: { + token: string | null; + eventId: string; + onSelected: (r: Registration) => void; + onEditRegistration: (r: Registration) => void; + onNewAttendee: (seed: string) => void; + onDonation: (user?: UserSummary) => void; +}) { + const [search, setSearch] = useState(""); + const [allRegs, setAllRegs] = useState([]); + const [loading, setLoading] = useState(false); + + // Load registrations for this event — once on mount/eventId change, then every 5 min + useEffect(() => { + if (!token || !eventId) return; + let cancelled = false; + + const load = async () => { + try { + setLoading(true); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); + if (!cancelled) setAllRegs(regs || []); + } catch { + if (!cancelled) setAllRegs([]); + } finally { + if (!cancelled) setLoading(false); + } + }; + + load(); + const timer = setInterval(load, 300000); + return () => { cancelled = true; clearInterval(timer); }; + }, [token, eventId]); + + const results = fuzzyFilterRegs(allRegs, search); + + return ( +
+ +
+
Find / Register
+ +
+ + setSearch(e.target.value)} + autoFocus + /> + +
+ + {results.map(r => ( +
+
+
+
{r.user?.name || "Guest"}
+
+ {r.user?.email && !r.user.email.endsWith("@guest.local") ? r.user.email : ""} + {r.user?.phoneNumber ? ` · ${r.user.phoneNumber}` : ""} +
+
+ {r.status === "paid" ? "PAID ✅" : `UNPAID · ${r.status}`} +
+
+
+ + + +
+
+
+ ))} + + {/* New attendee row */} +
onNewAttendee(search)} + > +
+ {search ? `New attendee "${search}"…` : "New attendee…"} +
+
+ Register
+
+ + {!loading && allRegs.length === 0 && ( +
No registrations yet for this event.
+ )} +
+ + +
+ ); +} + +function DoorPaymentPanel({ token, registration, onSuccess, setError }: { + token: string | null; + registration: Registration | null; + onSuccess: (registration?: Registration, partial?: boolean) => void; + setError: (e: string | null) => void; +}) { + const [amount, setAmount] = useState(""); + const [method, setMethod] = useState("card"); + const [saving, setSaving] = useState(false); + const [showRefund, setShowRefund] = useState(false); + const [showSendTickets, setShowSendTickets] = useState(false); + + if (!registration) { + return ( +
+ No registration selected +
+ ); + } + + // Backend attaches a tranche-aware totalDueComputed (exact even when a line spans + // multiple early-bird prices) — fall back to the old client-side estimate otherwise. + const totalValue = registrationTotal(registration); + const paidValue = totalPaidOn(registration); + + const balance = Math.max(0, totalValue - paidValue); + + const save = async () => { + if (!balance) { + setError("Nothing due on this registration"); + return; + } + + try { + setSaving(true); + + await apiV2Data("post", "/payments", { + authToken: token, + body: { + registrationId: registration.id, + amount: parseFloat(amount), + method + }, + }); + + const updated = await (apiV2Data("get", "/registrations/{id}/full", { + params: { id: registration.id }, + authToken: token, + }) as Promise); + + const updatedBalance = Math.max(0, registrationTotal(updated) - totalPaidOn(updated)); + + if (updatedBalance === 0) { + onSuccess(updated); // 🎯 ONLY NOW generate tickets + } else { + onSuccess(updated, true); // 🎯 partial payment flow + } + + } catch (e) { + setError(errorMessage(e) || "Payment failed"); + } finally { + setSaving(false); + } + }; + + return ( +
+ +
Payment
+ + {/* ✅ User */} +
+
+ {registration.user?.name || "Guest"} +
+
+ + {/* ✅ BIG MONEY BLOCK 😌🔥 */} +
+ +
+
TOTAL
+
+ R {totalValue.toFixed(2)} +
+
+ +
+
PAID
+
+ R {paidValue.toFixed(2)} +
+
+ +
+
DUE
+
+ R {balance.toFixed(2)} +
+
+ +
+ + {/* ✅ Amount + Full Pay */} +
+ + setAmount(e.target.value)} + autoFocus + /> + + {balance > 0 && ( + + )} + +
+ + {/* ✅ Method */} + + + {/* Capture — only show when there's a balance */} + {balance > 0 && ( + + )} + + {/* Print / Send — show when fully paid */} + {balance === 0 && ( +
+ + +
+ )} + + {/* Refund */} + {paidValue > 0 && ( + + )} + + setShowRefund(false)} + token={token} + registration={registration} + maxRefund={paidValue} + onRefunded={(updated) => { + setShowRefund(false); + onSuccess(updated, true); + }} + /> + + setShowSendTickets(false)} + token={token} + registration={registration} + /> +
+ ); +} + +function DoorTicketsPanel({ token, eventId }: { token: string | null; eventId: string }) { + const [search, setSearch] = useState(""); + const [allTickets, setAllTickets] = useState([]); + const [loading, setLoading] = useState(false); + const [sendTarget, setSendTarget] = useState(null); + const [transferTarget, setTransferTarget] = useState(null); + const [notice, setNotice] = useState(null); + // Memoised so the send modal's reset effect doesn't rerun on every render of this panel. + const sendRegistration = useMemo(() => sendTarget ? { + id: sendTarget.registrationOption?.registration?.id || sendTarget.registrationOption?.registrationId || "", + user: sendTarget.user, + } : null, [sendTarget]); + + // Load all tickets for the event once + useEffect(() => { + if (!token || !eventId) return; + (async () => { + try { + setLoading(true); + const res = await (apiV2Data("get", "/events/{id}/tickets", { params: { id: eventId }, authToken: token }) as Promise); + setAllTickets(ticketsFrom(res)); + } catch { + setAllTickets([]); + } finally { + setLoading(false); + } + })(); + }, [token, eventId]); + + const tickets = !search + ? allTickets + : (() => { + const q = search.toLowerCase(); + const byId = allTickets.filter(t => + String(t.id).toLowerCase().includes(q) || + String(t.qrCode || "").toLowerCase().includes(q) + ); + if (byId.length > 0) return byId; + if (search.length < 2) return allTickets.filter(t => + String(t.user?.name || "").toLowerCase().includes(q) || + String(t.user?.email || "").toLowerCase().includes(q) + ); + return allTickets + .map(t => ({ t, score: scoreUser(t.user || {}, search) })) + .filter(x => x.score >= 0.45) + .sort((a, b) => b.score - a.score) + .map(x => x.t); + })(); + + const load = async () => { + if (!token || !eventId) return; + try { + setLoading(true); + const res = await (apiV2Data("get", "/events/{id}/tickets", { params: { id: eventId }, authToken: token }) as Promise); + setAllTickets(ticketsFrom(res)); + } catch { + setAllTickets([]); + } finally { + setLoading(false); + } + }; + + const print = (ticket: TicketRecord) => printTicketCards([ticket], (t) => t.user?.name); + + return ( +
+
+
Tickets
+ +
+ +
+ setSearch(e.target.value)} + autoFocus + /> +
+ + {loading && ( +
+ Searching… +
+ )} + + {notice &&
{notice}
} +
+ {tickets.map(t => ( +
+
+
+ {t.attendee?.name || t.user?.name || "Guest"} +
+ {t.attendee?.name && t.user?.name && t.attendee.name !== t.user.name && ( +
Booked by {t.user.name}
+ )} +
+ {ticketLabel(t)} +
+
+ +
+ + + {canOfferTransfer(t, t.event, true) && ( + + )} +
+
+ ))} + + {!loading && tickets.length === 0 && ( +
+ No tickets found +
+ )} +
+ + {transferTarget && ( + setTransferTarget(null)} + onDone={(msg) => { setTransferTarget(null); setNotice(msg); load(); }} + /> + )} + {sendRegistration && ( + setSendTarget(null)} + token={token} + registration={sendRegistration} + /> + )} +
+ ); +} + +function DoorCheckInPanel({ token, eventId, registration, setError, setInfo, onFillForm }: { + token: string | null; + eventId: string; + registration: Registration | null; + setError: (e: string | null) => void; + setInfo: (s: string | null) => void; + /** No tickets yet: open the attendee form that holds them back. */ + onFillForm?: () => void; +}) { + const [ticketsForEvent, setTicketsForEvent] = useState([]); + const [loading, setLoading] = useState(false); + const [qtyByTicket, setQtyByTicket] = useState>({}); + const [submittingId, setSubmittingId] = useState(null); + + const load = useCallback(async () => { + if (!token || !eventId) return; + try { + setLoading(true); + const res = await (apiV2Data("get", "/events/{id}/tickets", { params: { id: eventId }, authToken: token }) as Promise); + const tickets = ticketsFrom(res); + setTicketsForEvent(tickets.filter((t) => t.registrationOption?.eventOption?.isMainTicket)); + } catch { + setTicketsForEvent([]); + } finally { + setLoading(false); + } + }, [token, eventId]); + + // Again when the registration changes: its tickets may have just been issued. + useExternalEffect(() => { void registration; load(); }, [load, registration]); + + if (!registration) { + return ( +
+ No registration selected +
+ ); + } + + // Multi-day events: check-in is per session, so only today's session's check-ins count. + const session = todaysSession(ticketsForEvent[0]?.event); + const myTickets = ticketsForEvent + .filter(t => t.registrationOption?.registration?.id === registration.id) + .map(t => { + const totalRedeemed = (t.usages || []) + .filter(u => !session || u.sessionId === session.id) + .reduce((s, u) => s + (u.quantityRedeemed || 1), 0); + const remaining = (t.quantity || 1) - totalRedeemed; + return { ...t, totalRedeemed, remaining }; + }); + + type CheckInTicket = (typeof myTickets)[number]; + const qtyFor = (t: CheckInTicket) => qtyByTicket[t.id] ?? (t.remaining > 0 ? t.remaining : 1); + const setQtyFor = (t: CheckInTicket, n: number) => + setQtyByTicket(q => ({ ...q, [t.id]: Math.max(1, Math.min(t.remaining || 1, n)) })); + + const commit = async (ticket: CheckInTicket) => { + const qty = qtyFor(ticket); + try { + setSubmittingId(ticket.id); + const { data: res } = await apiV2("post", "/checkin/{qrCode}", { + params: { qrCode: ticket.qrCode }, authToken: token, body: { people: qty, eventId }, + }); + // Already used, consent missing, wrong session…: say why. + if (res.outcome !== "checked_in") throw new Error(res.message); + setInfo(`${res.checkedIn} checked in for ${registration.user?.name || "guest"}${ + (res.remaining ?? 0) > 0 ? ` — ${res.remaining} remaining` : " — fully checked in" + }. Confirmation sent.`); + await load(); + } catch (e) { + setError(errorMessage(e) || "Check-in failed"); + } finally { + setSubmittingId(null); + } + }; + + return ( +
+ +
Check-In{session ? {session.label || "Today's session"} : null}
+ + {/* ✅ User */} +
+
+ {registration.user?.name || "Guest"} +
+
+ + {loading && ( +
Loading…
+ )} + + {!loading && myTickets.length === 0 && ( + registration.status === "paid" && onFillForm ? ( +
+ No tickets yet. If the event has an attendee form, it’s holding them back. + +
+ ) : ( +
+ {registration.status === "paid" ? "No Main Tickets on this registration" : "No tickets yet — they're issued once it's paid."} +
+ ) + )} + +
+ {myTickets.map(t => { + const qty = qtyFor(t); + return ( +
+
{ticketLabel(t)}
+ +
+
+
TOTAL
+
{t.quantity || 1}
+
+ +
+
CHECKED IN
+
{t.totalRedeemed}
+
+ +
+
REMAINING
+
{t.remaining}
+
+
+ + {t.remaining > 0 ? ( +
+ +
{qty}
+ + + +
+ ) : ( +
Fully checked in ✓
+ )} +
+ ); + })} +
+
+ ); +} + +type OptionsModalProps = { + open: boolean; + onClose: () => void; + options: EventOption[]; + quantities: Record; + setQuantities: React.Dispatch>>; + minQuantities?: Record; + onConfirm: () => void; + confirming: boolean; + isEdit: boolean; + totalPaid?: number; + eventId: string; + token: string | null; + coupon: AppliedCoupon | null; + setCoupon: (c: AppliedCoupon | null) => void; + couponForUserId: string | null; + existingCode: string | null; + bundles: PublicBundle[]; + // Named-attendee editor settings, or null when the event doesn't take names. + names: Omit, "options" | "qtyFor" | "payerLabel"> | null; + // A "pick sessions" event: its sessions and the sessions chosen per quantity key. + pick: { event: Event; picks: Record; setPicks: React.Dispatch>> } | null; +}; + +function OptionsModal({ open, onClose, options, quantities, setQuantities, minQuantities = {}, onConfirm, confirming, isEdit, totalPaid = 0, eventId, token, coupon, setCoupon, couponForUserId, existingCode, bundles, names, pick }: OptionsModalProps) { + const pickOpt = (optionId: string) => !!pick && isPickOption(pick.event, (options || []).find(o => o.id === optionId)); + // Sessions are ticked on new bookings only (edits leave booked sessions as they are). + const choiceOpt = (optionId: string) => !!pick && !isEdit && (options || []).some(o => o.id === optionId); + // A picked option is priced per session. + const times = (key: string) => (pick && pickOpt(key.split("::")[0]) ? (pick.picks[key] || []).length : 1); + const basket = Object.entries(quantities) + .filter(([, qty]) => qty > 0) + .map(([key, quantity]) => { + const [eventOptionId, variantId] = key.split("::"); + return { eventOptionId, quantity, variantId: variantId || null, ...(pick && choiceOpt(eventOptionId) ? { sessionIds: pick.picks[key] || [] } : {}) }; + }); + // The sessions show straight away; ticking one when the quantity is 0 makes it 1. + const picker = (key: string, option: EventOption) => { + if (!pick || !choiceOpt(option.id)) return null; + const qty = quantities[key] || 0; + return 0 ? pick.picks[key] || [] : []} + onChange={ids => { pick.setPicks(p => ({ ...p, [key]: ids })); if (qty === 0 && ids.length > 0) setQuantities(q => ({ ...q, [key]: 1 })); }} />; + }; + const perSession = (o: EventOption) => (pickOpt(o.id) ? " per session" : ""); + // Bundle deals apply to the whole registration, so this holds for edits too. + const bundleQuote = useBundleQuote({ eventId, basket, token, forUserId: couponForUserId, enabled: open }); + + if (!open) return null; + + const safeOptions: EventOption[] = options || []; + + const total = safeOptions.reduce((sum, o) => { + if ((o.variants || []).length > 0) { + return sum + (o.variants || []).reduce((vs, v) => + vs + (quantities[`${o.id}::${v.id}`] || 0) * times(`${o.id}::${v.id}`) * variantUnitNow(o, v), 0); + } + return sum + (quantities[o.id] || 0) * times(o.id) * optionUnitNow(o); + }, 0); + + const afterBundles = bundleQuote ? bundleQuote.total : total; + const belowPaid = isEdit && afterBundles < totalPaid; + const belowIssued = isEdit && Object.entries(minQuantities).some( + ([key, minQty]) => minQty > 0 && (quantities[key] || 0) < minQty + ); + + const stepper = (key: string, delta: number) => + setQuantities((q) => ({ ...q, [key]: Math.max(minQuantities[key] || 0, (q[key] || 0) + delta) })); + + return ( +
+
+ + {/* Header */} +
+
+ {isEdit ? "Edit Registration" : "Select Items"} +
+ {isEdit && pick && ( +
+ Sessions already booked stay as they are. To add sessions, book them as a new registration. +
+ )} + {isEdit && totalPaid > 0 && ( +
+ Already paid: R {Number(totalPaid).toFixed(2)} — new total must be at least this amount. +
+ )} +
+ + {/* Scrollable Content */} +
+ + quantities[v ? `${o}::${v}` : o] || 0} + onSetQuantity={(o, v, n) => setQuantities(q => ({ ...q, [v ? `${o}::${v}` : o]: n }))} + /> + {safeOptions.map((opt) => { + const hasVariants = (opt.variants || []).length > 0; + if (hasVariants) { + return ( +
+
+ {opt.name} + {opt.isMainTicket && • Main} +
+ {(opt.variants || []).map((v) => { + const unit = variantUnitNow(opt, v); + const basePrice = v.price !== null && v.price !== undefined ? v.price : opt.price; + const key = `${opt.id}::${v.id}`; + const minQty = minQuantities[key] || 0; + return ( +
+
+
+
{v.name}
+
+ R {unit.toFixed(2)}{perSession(opt)} + {unit < basePrice && basePrice > 0 && (early bird)} +
+ {minQty > 0 &&
{minQty} already issued
} +
+
+ +
{quantities[key] || 0}
+ +
+
+ {picker(key, opt)} +
+ ); + })} +
+ ); + } + const unit = optionUnitNow(opt); + const minQty = minQuantities[opt.id] || 0; + return ( +
+
{opt.name}
+
+ R {unit.toFixed(2)}{perSession(opt)} + {unit < opt.price && opt.price > 0 && (early bird, was R {opt.price.toFixed(2)})} + {opt.isMainTicket ? " • Main" : ""} +
+ {minQty > 0 &&
{minQty} already issued
} +
+ +
{quantities[opt.id] || 0}
+ +
+ {picker(opt.id, opt)} +
+ ); + })} +
+ + {/* Footer */} +
+ {belowPaid && ( +
+ New total (R {afterBundles.toFixed(2)}) is less than amount already paid (R {Number(totalPaid).toFixed(2)}). Please increase the selection. +
+ )} + {belowIssued && ( +
+ One or more items are below the quantity already issued as tickets. Please increase the selection. +
+ )} + {names && ( +
+ !pickOpt(o.id))} + qtyFor={(o: string, v: string | null) => quantities[v ? `${o}::${v}` : o] || 0} + {...names} + payerLabel="the person registering" + /> +
+ )} + {existingCode ? ( +
Code {existingCode} is applied to this registration.
+ ) : ( +
+ +
+ )} +
+
+ {coupon && coupon.discount > 0 && !isEdit && ( +
R {coupon.subtotal.toFixed(2)} −R {coupon.discount.toFixed(2)}
+ )} + +
Total: R {(coupon && !isEdit ? coupon.total : afterBundles).toFixed(2)}
+ {coupon && isEdit &&
Code {coupon.code} is applied when you save
} +
+
+ + +
+
+
+ +
+
+ ); +} + +function DonationModal({ open, onClose, user, token, eventId, onSuccess, setError }: { + open: boolean; + onClose: () => void; + user: UserSummary | null; + token: string | null; + eventId: string; + onSuccess?: () => void; + setError: (e: string | null) => void; +}) { + const [amount, setAmount] = useState(""); + const [method, setMethod] = useState("cash"); + const [saving, setSaving] = useState(false); + + if (!open) return null; + + const saveDonation = async () => { + const amt = parseFloat(amount); + + if (!amt || amt <= 0) { + setError("Enter valid amount"); + return; + } + + try { + setSaving(true); + + await apiV2Data("post", "/payments", { + authToken: token, + body: { + amount: amt, + method, + userId: user?.id || undefined, + eventId, + isDonation: true + }, + }); + + onSuccess?.(); + + setAmount(""); + onClose(); + + } catch (e) { + setError(errorMessage(e) || "Donation failed"); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ +
+ Donation +
+ +
+ {user ? user.name : "Anonymous Donation"} +
+ + setAmount(e.target.value)} + autoFocus + /> + + + +
+ + + +
+
+
+ ); +} + +function SendTicketsModal({ open, onClose, token, registration }: { + open: boolean; + onClose: () => void; + token: string | null; + registration: Pick | null; +}) { + const [channel, setChannel] = useState<"email" | "whatsapp" | "both">("email"); + const [phone, setPhone] = useState(""); + const [email, setEmail] = useState(""); + const [sending, setSending] = useState(false); + const [localError, setLocalError] = useDismissingState(""); + const [localInfo, setLocalInfo] = useState(""); + + // Each time it opens: start from the registration's details. + useStateSync(() => { + if (open && registration) { + setPhone(registration.user?.phoneNumber || ""); + setEmail(registration.user?.email?.endsWith("@guest.local") ? "" : registration.user?.email || ""); + setLocalError(""); + setLocalInfo(""); + } + }, [open, registration, setLocalError]); + + if (!open) return null; + + const send = async () => { + setLocalError(""); + if ((channel === "email" || channel === "both") && !email.trim()) { + setLocalError("Email address is required for email delivery."); + return; + } + if ((channel === "whatsapp" || channel === "both") && !phone.trim()) { + setLocalError("Phone number is required for WhatsApp delivery."); + return; + } + setSending(true); + try { + await apiV2Data("post", "/tickets/send", { + authToken: token, + body: { + registrationId: registration?.id, + channel, + overrideEmail: email.trim() || undefined, + overridePhone: phone.trim() || undefined, + }, + }); + setLocalInfo("Tickets sent successfully."); + setTimeout(() => { setLocalInfo(""); onClose(); }, 7000); + } catch (e) { + setLocalError(errorMessage(e) || "Failed to send tickets"); + } finally { + setSending(false); + } + }; + + return ( +
+
+
+
Send Tickets
+
+ {registration?.user?.name || "Guest"} +
+ +
+ +
+ {(["email", "whatsapp", "both"] as const).map((c) => ( + + ))} +
+
+ + {(channel === "email" || channel === "both") && ( +
+ + setEmail(e.target.value)} + /> +
+ )} + + {(channel === "whatsapp" || channel === "both") && ( +
+ + setPhone(e.target.value)} + /> +
+ )} + + {localError &&

{localError}

} + {localInfo &&

{localInfo}

} + +
+ + +
+
+
+
+ ); +} + +function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded }: { + open: boolean; + onClose: () => void; + token: string | null; + registration: Registration | null; + maxRefund: number; + onRefunded: (updated: Registration) => void; +}) { + const [amount, setAmount] = useState(""); + const [method, setMethod] = useState("cash"); + const [reason, setReason] = useState(""); + const [saving, setSaving] = useState(false); + const [localError, setLocalError] = useDismissingState(""); + + useStateSync(() => { + if (open) { setAmount(""); setReason(""); setLocalError(""); } + }, [open, setLocalError]); + + if (!open || !registration) return null; + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + const amt = parseFloat(amount); + if (!amt || amt <= 0) { setLocalError("Enter a valid amount."); return; } + if (amt > maxRefund) { setLocalError(`Cannot exceed total paid (R ${Number(maxRefund).toFixed(2)}).`); return; } + + setSaving(true); + setLocalError(""); + try { + await apiV2Data("post", "/payments/refunds", { + authToken: token, + body: { + userId: registration.userId, + registrationId: registration.id, + amount: amt, + method, + reason: reason || undefined, + }, + }); + // Re-fetch registration to get updated status & payments + const updated = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registration.id }, authToken: token }) as Promise); + onRefunded(updated); + } catch (e) { + setLocalError(errorMessage(e) || "Refund failed."); + } finally { + setSaving(false); + } + }; + + return ( +
+
+
+
Issue Refund
+
+ {registration.user?.name || "Guest"} + · Total paid: R {Number(maxRefund).toFixed(2)} +
+ +
+ +
+ setAmount(e.target.value)} + autoFocus + /> + +
+
+ +
+ + +
+ +
+ + setReason(e.target.value)} + /> +
+ + {localError &&

{localError}

} + +
+ + +
+
+
+
+ ); +} + +function DoorRefundPanel({ token, eventId, setInfo }: { + token: string | null; + eventId: string; + setInfo: (s: string | null) => void; +}) { + const [search, setSearch] = useState(""); + const [allRegs, setAllRegs] = useState([]); + const [loading, setLoading] = useState(false); + const [selectedReg, setSelectedReg] = useState(null); + const [showRefund, setShowRefund] = useState(false); + + const load = useCallback(async () => { + if (!token || !eventId) return; + try { + setLoading(true); + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); + setAllRegs(regs || []); + } catch { + setAllRegs([]); + } finally { + setLoading(false); + } + }, [token, eventId]); + + useExternalEffect(() => { + load(); + }, [load]); + + // Only show registrations that have at least one payment + const paidRegs = allRegs.filter(r => totalPaidOn(r) > 0); + const results = fuzzyFilterRegs(paidRegs, search); + + const handleRefunded = async (updated: Registration) => { + setShowRefund(false); + setSelectedReg(updated); + setInfo("Refund recorded"); + // Refresh list + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise).catch(() => null); + if (regs) setAllRegs(regs); + }; + + const maxRefund = selectedReg ? totalPaidOn(selectedReg) : 0; + + return ( +
+
+
Refunds
+ +
+ + {!selectedReg ? ( + <> + setSearch(e.target.value)} + autoFocus + /> + +
+ {results.map(r => { + const paidValue = totalPaidOn(r); + return ( +
+
+
{r.user?.name || "Guest"}
+
+ {r.user?.email && !r.user.email.endsWith("@guest.local") ? r.user.email : ""} + {r.user?.phoneNumber ? ` · ${r.user.phoneNumber}` : ""} +
+
+ Paid: R {paidValue.toFixed(2)} · {r.status} +
+
+ +
+ ); + })} + + {!loading && results.length === 0 && ( +
+ No paid registrations found for this event. +
+ )} +
+ + ) : ( +
+ + +
+
{selectedReg.user?.name || "Guest"}
+
+ {selectedReg.user?.email && !selectedReg.user.email.endsWith("@guest.local") ? selectedReg.user.email : ""} + {selectedReg.user?.phoneNumber ? ` · ${selectedReg.user.phoneNumber}` : ""} +
+
+
+
TOTAL
+
+ R {registrationTotal(selectedReg).toFixed(2)} +
+
+
+
PAID
+
R {maxRefund.toFixed(2)}
+
+
+ + {(selectedReg.payments || []).length > 0 && ( +
+
Payment history
+
+ {(selectedReg.payments || []).map((p, i) => ( +
+ + {p.amount < 0 ? "Refund" : "Payment"} — {p.method || "—"} + {/* A refund's reason is stored in its status field. */} + {p.amount < 0 && p.status ? ` (${p.status})` : ""} + + + R {Number(p.amount).toFixed(2)} + +
+ ))} +
+
+ )} +
+ + {maxRefund > 0 ? ( + + ) : ( +
+ Nothing to refund — net paid is R 0.00. +
+ )} +
+ )} + + setShowRefund(false)} + token={token} + registration={selectedReg} + maxRefund={maxRefund} + onRefunded={handleRefunded} + /> +
+ ); +} + +function NewAttendeeModal({ open, onClose, seed, onConfirm }: { + open: boolean; + onClose: () => void; + seed: string; + onConfirm: (data: { name: string; email: string; phone: string; notifPref: "email" | "whatsapp" | "both" }) => void; +}) { + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [phone, setPhone] = useState(""); + const [notifPref, setNotifPref] = useState<"email" | "whatsapp" | "both">("email"); + const [err, setErr] = useState(""); + + // Pre-fill name from whatever was typed in search + useStateSync(() => { + if (open) { + setName(seed || ""); + setEmail(""); + setPhone(""); + setNotifPref("email"); + setErr(""); + } + }, [open, seed]); + + if (!open) return null; + + const derivedPref = email.trim() && phone.trim() ? notifPref : phone.trim() ? "whatsapp" : "email"; + + const submit = (e: React.FormEvent) => { + e.preventDefault(); + if (!name.trim()) { setErr("Name is required."); return; } + if (!email.trim() && !phone.trim()) { setErr("Provide at least an email or phone number."); return; } + onConfirm({ name: name.trim(), email: email.trim(), phone: phone.trim(), notifPref: derivedPref }); + }; + + return ( +
+
+
+
New Attendee
+ +
+ + setName(e.target.value)} + placeholder="Full name" + autoFocus + /> +
+ +
+ + setEmail(e.target.value)} + placeholder="Email address" + /> +
+ +
+ + { + const v = e.target.value; + setPhone(v); + if (v.trim() && !email.trim()) setNotifPref("whatsapp"); + else if (!v.trim() && email.trim()) setNotifPref("email"); + }} + placeholder="+27…" + /> +
+ + {/* Preference selector — shown only when both channels are provided */} + {email.trim() && phone.trim() && ( +
+ +
+ {(["email", "whatsapp", "both"] as const).map((p) => ( + + ))} +
+
+ )} + +

At least one of email or cell number is required. If no email is provided, a guest account is created.

+ + {err &&

{err}

} + +
+ + +
+
+
+
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx new file mode 100644 index 0000000..efa2bef --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx @@ -0,0 +1,294 @@ +"use client"; + +import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react"; +import { useRouter, useSearchParams } from "next/navigation"; +import { ClipboardCheck, Check, Download, FileSpreadsheet, FileText, Send, Award, Search, Ban } from "lucide-react"; +import { useAuth } from "@/hooks/useAuth"; +import { API_BASE, fetchManagedEvents } from "@/lib/api"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { errorMessage } from "@/lib/utils"; +import { fetchApiFile, saveBlob } from "@/lib/export"; +import type { AttendanceRegister, AttendanceRow, Event } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; +import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; +import { useExternalEffect, useNow } from "@/lib/hooks"; + +type Filter = "all" | "completed" | "not_completed" | "missed_recent"; + +const colDate = new Intl.DateTimeFormat("en-GB", { weekday: "short", day: "numeric", month: "short" }); + +function AttendancePageInner() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const search = useSearchParams(); + const canView = ["admin", "supervisor", "staff"].includes(user?.role || ""); + const canManage = user?.role === "admin" || user?.role === "supervisor"; + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [events, setEvents] = useState([]); + const [eventId, setEventId] = useState(search.get("eventId") || ""); + const [reg, setReg] = useState(null); + const [busy, setBusy] = useState(false); + const [pending, setPending] = useState(null); + const [query, setQuery] = useState(""); + const [filter, setFilter] = useState("all"); + const [showCancelled, setShowCancelled] = useState(false); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + + useEffect(() => { + if (!token || !canView) return; + fetchManagedEvents(token, { past: true }) + .then(evs => { + // Multi-day events first (that's what the register is mostly for), newest first. + const list = (evs || []).filter(e => e.requiresRegistration !== false) + .sort((a, b) => Number(b.scheduleType === "sessions") - Number(a.scheduleType === "sessions") || new Date(b.startDate).getTime() - new Date(a.startDate).getTime()); + setEvents(list); + if (!eventId && list.length) setEventId(list[0].id); + }) + .catch(e => setError(errorMessage(e) || "Failed to load events")); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [token, canView]); + + const load = useCallback(async () => { + if (!token || !eventId) return; + setBusy(true); + try { + setReg(await (apiV2Data("get", "/events/{id}/attendance", { params: { id: eventId }, authToken: token }) as Promise)); + } catch (e) { + setError(errorMessage(e) || "Failed to load the register"); + } finally { + setBusy(false); + } + }, [token, eventId, setError]); + useExternalEffect(() => { load(); }, [load]); + + const columns = useMemo(() => (reg?.columns || []).filter(c => showCancelled || !c.cancelled), [reg, showCancelled]); + const multi = reg?.event.scheduleType === "sessions"; + // Sessions already held (for "missed the last two"). + const now = useNow(); + const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < now).map(c => c.id), [reg, now]); + + const rows = useMemo(() => { + const q = query.trim().toLowerCase(); + return (reg?.rows || []).filter(r => { + if (q && ![r.name, r.bookedBy, r.email, r.phone].some(v => v?.toLowerCase().includes(q))) return false; + if (filter === "completed") return r.completed; + if (filter === "not_completed") return !r.completed; + if (filter === "missed_recent") { + const lastTwo = heldIds.slice(-2); + return lastTwo.length > 0 && lastTwo.every(id => !r.checkIns[id]); + } + return true; + }); + }, [reg, query, filter, heldIds]); + + const toggle = async (row: AttendanceRow, sessionId: string) => { + if (!canManage || !token) return; + const present = !row.checkIns[sessionId]; + const key = `${row.ticketId}:${sessionId}`; + setPending(key); + try { + // Picked sessions have a ticket per session. + const ticketId = row.sessionTickets?.[sessionId] || row.ticketId; + await apiV2Data("post", "/events/{id}/attendance", { params: { id: eventId }, authToken: token, body: { ticketId, sessionId, present } }); + const col = reg?.columns.find(c => c.id === sessionId); + setInfo(`${row.name || "Attendee"} marked ${present ? "present" : "absent"}${multi && col ? ` for ${col.label}` : ""}.`); + await load(); + } catch (e) { + setError(errorMessage(e) || "Couldn't update attendance"); + } finally { + setPending(null); + } + }; + + const post = async (path: string, body: object, done: (r: Record) => string) => { + if (!token) return; + setBusy(true); + try { + const r = await apiV2Raw>("post", path, { authToken: token, body }); + setInfo(done(r)); + await load(); + } catch (e) { + setError(errorMessage(e) || "Something went wrong"); + } finally { + setBusy(false); + } + }; + + const download = async (path: string, filename: string) => { + if (!token) return; + try { + saveBlob(await fetchApiFile(API_BASE, token, path), filename); + } catch (e) { + setError(errorMessage(e) || "Download failed"); + } + }; + + const safeTitle = (reg?.event.title || "event").replace(/[^a-z0-9 -]/gi, "").slice(0, 60); + const certsOn = !!reg?.event.certificatesEnabled; + const issued = (reg?.rows || []).filter(r => r.certificate && !r.certificate.revokedAt).length; + const unsent = (reg?.rows || []).filter(r => r.certificate && !r.certificate.revokedAt && !r.certificate.emailedAt).length; + const completed = (reg?.rows || []).filter(r => r.completed).length; + + return ( +
+
+
+ +
+
+ +

Attendance

+

Who came to each session, and completion certificates

+
+
+ + {!canView &&
You need staff access to view attendance.
} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + { setEventId(id); }} placeholder="No events" /> +
+
+ + setQuery(e.target.value)} /> +
+ + {multi && (reg?.columns || []).some(c => c.cancelled) && ( + + )} +
+ + +
+
+ + {reg && ( +
+ {reg.rows.length} attendee{reg.rows.length === 1 ? "" : "s"} + {completed} completed + {certsOn && {issued} certificate{issued === 1 ? "" : "s"} issued} + {!multi && Single-date event — one check-in column} +
+ )} + + {reg && certsOn && canManage && ( +
+ + Certificates are issued automatically when the event ends. You can also: + + + +
+ )} + + {busy && !reg &&

Loading…

} + {reg && rows.length === 0 &&

{reg.rows.length === 0 ? "No tickets for this event yet." : "Nobody matches."}

} + + {reg && rows.length > 0 && ( +
+ + + + + {columns.map(c => ( + + ))} + + {certsOn && } + + + + {rows.map(r => ( + + + {columns.map(c => { + const qty = r.checkIns[c.id] || 0; + const key = `${r.ticketId}:${c.id}`; + if (r.bookedSessions && !r.bookedSessions.includes(c.id)) { + return ; + } + const disabled = !canManage || c.cancelled || pending !== null || reg.event.cashupStatus === "closed"; + return ( + + ); + })} + + {certsOn && ( + + )} + + ))} + + + + + {columns.map(c => )} + + +
Name +
{c.label}
+
{multi ? colDate.format(new Date(c.startsAt)) : ""}
+
TotalCertificate
+
{r.name || "—"}{r.quantity > 1 && ×{r.quantity}}
+
{r.variant ? `${r.option} — ${r.variant}` : r.option}{r.bookedBy ? ` · booked by ${r.bookedBy}` : ""}
+
— + + + {r.attended}/{r.total} + + {r.certificate && !r.certificate.revokedAt ? ( +
+ {r.certificate.code} + + {canManage && } + {canManage && } +
+ ) : canManage ? ( + + ) : —} +
Present{c.cancelled ? "—" : reg.totals[c.id] || 0} + {certsOn && } +
+
+ )} + {reg && canManage && ( +

Click a box to mark someone present or absent (e.g. they were let in without a scan). Changes are recorded in the audit log.

+ )} +
+ )} +
+ ); +} + +export default function AttendancePage() { + return ( + + + + ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx new file mode 100644 index 0000000..79ca028 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx @@ -0,0 +1,543 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { useAuth } from "@/hooks/useAuth"; +import { useRouter } from "next/navigation"; +import { fetchManagedEvents } from "@/lib/api"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { Gift, Plus, X, Trash2, Pencil, Power, CalendarClock } from "lucide-react"; +import { errorMessage } from "@/lib/utils"; +import { BackLink } from "@/components/shared/BackLink"; +import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types"; +import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; + +type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] }; +type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] }; + +type ItemDraft = { eventOptionId: string; variantId: string | null; quantity: string }; +type Draft = { + name: string; + description: string; + kind: BundleKind; + price: string; + setSize: string; + freeCount: string; + groupPricing: BundleGroupPricing; + items: ItemDraft[]; + validFrom: string; + validUntil: string; + isActive: boolean; +}; + +const blankDraft = (options: OptionLite[]): Draft => ({ + name: "", description: "", kind: "exact", price: "", setSize: "4", freeCount: "1", groupPricing: "per_ticket", + items: options.slice(0, 2).map(o => ({ eventOptionId: o.id, variantId: null, quantity: "1" })), + validFrom: "", validUntil: "", isActive: true, +}); + +// wants local "YYYY-MM-DDTHH:mm". +const toLocalInput = (iso: string | null | undefined) => { + if (!iso) return ""; + const d = new Date(iso); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; +}; + +const draftFromBundle = (b: EventBundle): Draft => ({ + name: b.name, description: b.description || "", kind: b.kind || "exact", + price: b.kind === "free" ? "" : String(b.price), + setSize: b.setSize ? String(b.setSize) : "4", freeCount: b.freeCount ? String(b.freeCount) : "1", + groupPricing: b.groupPricing || "per_ticket", + items: b.items.map(i => ({ eventOptionId: i.eventOptionId, variantId: i.variantId || null, quantity: String(i.quantity) })), + validFrom: toLocalInput(b.validFrom), validUntil: toLocalInput(b.validUntil), isActive: b.isActive, +}); + +const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : ""); +const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`; +// fieldCls has no width, for fields sized by their row (inputCls is full width). +const fieldCls = "border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; +const inputCls = `w-full ${fieldCls}`; + +const KIND_INFO: Record = { + exact: { label: "Exact set", hint: "These tickets in these numbers", example: "2 adults + 3 kids for R220" }, + mix: { label: "Pick any", hint: "Any mix of the chosen tickets", example: "Any 4 tickets for R250" }, + free: { label: "Buy X get Y free", hint: "Cheapest ones in each set are free", example: "Buy 3, get 1 free" }, + group: { label: "Group discount", hint: "A lower price from a group size up", example: "10+ tickets: R70 each" }, +}; + +/** Standard price of one unit of an item (variant price, else the option's). */ +function unitPrice(options: OptionLite[], item: { eventOptionId: string; variantId: string | null }) { + const o = options.find(x => x.id === item.eventOptionId); + if (!o) return 0; + const v = item.variantId ? (o.variants || []).find(x => x.id === item.variantId) : null; + return Number(v && v.price !== null && v.price !== undefined ? v.price : o.price) || 0; +} + +function bundleStatus(b: EventBundle): { label: string; cls: string } { + const now = Date.now(); + if (!b.isActive) return { label: "Off", cls: "bg-gray-100 text-gray-600" }; + if (b.validUntil && new Date(b.validUntil).getTime() < now) return { label: "Ended", cls: "bg-gray-100 text-gray-600" }; + if (b.validFrom && new Date(b.validFrom).getTime() > now) return { label: "Scheduled", cls: "bg-amber-100 text-amber-800" }; + return { label: "On sale", cls: "bg-green-100 text-green-800" }; +} + +export default function BundlesPage() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [allEvents, setAllEvents] = useState([]); + const [eventId, setEventId] = useState(""); + const [bundles, setBundles] = useState([]); + const [fetching, setFetching] = useState(false); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null); + + useEffect(() => { + if (!token || !canView) return; + fetchManagedEvents(token, { past: true }) + .then(list => setAllEvents(list || [])) + .catch(e => setError(errorMessage(e) || "Failed to load events")); + }, [token, canView, setError]); + + // Start on the next upcoming event (or the latest one). + useStateSync(() => { + if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents)); + }, [allEvents, eventId]); + + const event = allEvents.find(e => e.id === eventId) || null; + const options = event?.eventOptions || []; + + const load = useCallback(async () => { + if (!token || !eventId) { setBundles([]); return; } + setFetching(true); + try { + setBundles(await (apiV2Data("get", "/events/{id}/bundles", { params: { id: eventId }, authToken: token }) as Promise)); + } catch (e) { + setError(errorMessage(e) || "Failed to load bundles"); + } finally { + setFetching(false); + } + }, [token, eventId, setError]); + + useExternalEffect(() => { load(); }, [load]); + + const toggleActive = async (b: EventBundle) => { + try { + await apiV2Data("patch", "/bundles/{id}", { params: { id: b.id }, authToken: token, body: { isActive: !b.isActive } }); + setInfo(`${b.name} turned ${b.isActive ? "off" : "on"}.`); + load(); + } catch (e) { + setError(errorMessage(e) || "Failed to update bundle"); + } + }; + + const remove = async (b: EventBundle) => { + if (!window.confirm(`Delete "${b.name}"?`)) return; + try { + const res = await (apiV2Data("delete", "/bundles/{id}", { params: { id: b.id }, authToken: token }) as Promise<{ message: string }>); + setInfo(res?.message || "Bundle deleted"); + load(); + } catch (e) { + setError(errorMessage(e) || "Failed to delete bundle"); + } + }; + + const startNew = () => setEditing({ id: null, draft: blankDraft(options) }); + const canAdd = !!event && options.length > 0; + + return ( +
+
+
+
+ +
+
+ +

Bundle deals

+

Tickets sold together for one price

+
+
+ {canView && ( + + )} +
+ + {!canView && ( +
You need supervisor access to manage bundle deals.
+ )} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + +
+
+ + {event && options.length === 0 && ( +

This event has no tickets yet. Add ticket options to the event first.

+ )} + + {event && options.length > 0 && !fetching && bundles.length === 0 && ( +
+
+ +
+

No bundle deals for this event yet

+

e.g. "Family deal: 2 adults + 3 kids for R220". Buyers get it automatically when their tickets match.

+ +
+ )} + + {bundles.length > 0 && ( +
+ {bundles.map(b => ( + setEditing({ id: b.id, draft: draftFromBundle(b) })} + onToggle={() => toggleActive(b)} + onDelete={() => remove(b)} + /> + ))} +
+ )} + +

+ Bundles apply automatically, as many times as someone's tickets allow, and only when cheaper than the tickets at the prices + actually charged (early-bird and staff prices included). Coupon codes come off afterwards. +

+
+ )} + + {editing && event && ( + setEditing(null)} + onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }} + /> + )} +
+ ); +} + +function BundleCard({ bundle: b, onEdit, onToggle, onDelete }: { bundle: EventBundle; onEdit: () => void; onToggle: () => void; onDelete: () => void }) { + const status = bundleStatus(b); + const kind = b.kind || "exact"; + const dates = b.validFrom || b.validUntil + ? `${b.validFrom ? fmtDate(b.validFrom) : "Now"} – ${b.validUntil ? fmtDate(b.validUntil) : "no end date"}` + : null; + return ( +
+
+
+
{b.name}
+ {b.description &&
{b.description}
} +
+ {status.label} +
+ +
{KIND_INFO[kind].label}{kind === "exact" ? "" : ` · ${kind === "group" ? "qualifying" : "any of"}:`}
+ +
+ {b.items.map(i => ( + + {kind === "exact" && {i.quantity} ×} {i.eventOption?.name || "Ticket"}{i.variant ? ` (${i.variant.name})` : ""} + + ))} +
+ +
+
+ {kind === "exact" || kind === "mix" ? ( + <> + {fmtRand(b.price)} + {kind === "mix" ? `for any ${b.setSize}` : "for the set"} + {b.standardValue !== null && {fmtRand(b.standardValue)}} + + ) : kind === "free" ? ( + Buy {(b.setSize || 0) - (b.freeCount || 0)}, get {b.freeCount} free + ) : ( + <> + {b.groupPricing === "percent" ? `${b.price}% off` : `${fmtRand(b.price)} each`} + from {b.setSize} tickets + + )} +
+
+ {b.savingText || (kind === "free" || (kind === "group" && b.groupPricing === "percent") ? "" : "No saving at the standard prices")} +
+
+ +
+
+ Used {b.uses || 0}× on {b.registrations || 0} registration{b.registrations === 1 ? "" : "s"} · {fmtRand(b.totalDiscount || 0)} given +
+ {dates &&
{dates}
} +
+ +
+ + + +
+
+ ); +} + +function BundleModal({ token, event, bundleId, initial, onClose, onSaved }: { + token: string; + event: EventLite; + bundleId: string | null; + initial: Draft; + onClose: () => void; + onSaved: (message: string) => void; +}) { + const [d, setD] = useState(initial); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); + const options = event.eventOptions || []; + + const setItem = (i: number, patch: Partial) => set("items", d.items.map((it, j) => (j === i ? { ...it, ...patch } : it))); + const exact = d.kind === "exact"; + const price = Number(d.price) || 0; + const size = Math.max(0, Math.floor(Number(d.setSize) || 0)); + const free = Math.max(0, Math.floor(Number(d.freeCount) || 0)); + const dearest = d.items.reduce((m, it) => Math.max(m, unitPrice(options, it)), 0); + // Exact: what the set costs separately. Pick any: the dearest possible set. + const standardValue = exact ? d.items.reduce((s, it) => s + unitPrice(options, it) * (Number(it.quantity) || 0), 0) : dearest * size; + const saving_ = standardValue - price; + const priceLabel = exact ? "Bundle price (R)" : d.kind === "mix" ? "Price for the set (R)" : d.groupPricing === "percent" ? "Percentage off (%)" : "Price per ticket (R)"; + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + setError(null); + setSaving(true); + try { + const body = { + name: d.name.trim(), + description: d.description.trim() || null, + kind: d.kind, + price: d.kind === "free" ? 0 : Number(d.price), + setSize: exact ? null : Number(d.setSize), + freeCount: d.kind === "free" ? Number(d.freeCount) : null, + groupPricing: d.kind === "group" ? d.groupPricing : null, + items: d.items.map(it => ({ eventOptionId: it.eventOptionId, variantId: it.variantId, quantity: exact ? Number(it.quantity) : 1 })), + validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null, + validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null, + isActive: d.isActive, + }; + if (bundleId) { + await apiV2Data("patch", "/bundles/{id}", { params: { id: bundleId }, authToken: token, body: body as never }); + onSaved(`${body.name} saved.`); + } else { + await apiV2Data("post", "/events/{id}/bundles", { params: { id: event.id }, authToken: token, body: body as never }); + onSaved(`${body.name} created.`); + } + } catch (err) { + setError(errorMessage(err) || "Failed to save"); + } finally { + setSaving(false); + } + }; + + return ( +
+
e.stopPropagation()}> +
+
+

{bundleId ? "Edit bundle" : "New bundle deal"}

+

{event.title}

+
+ +
+ +
+
+
+ + set("name", e.target.value)} placeholder="Family deal" required maxLength={80} /> +

Shown to buyers and on receipts.

+
+
+ + set("description", e.target.value)} placeholder="Bring the whole family" /> +
+
+ +
+ +
+ {(Object.keys(KIND_INFO) as BundleKind[]).map(k => ( + + ))} +
+
+ +
+ + {!exact &&

Any of these count towards the deal.

} +
+ {d.items.map((it, i) => { + const opt = options.find(o => o.id === it.eventOptionId); + const hasVariants = (opt?.variants || []).length > 0; + return ( +
+
+ {exact && ( + <> + setItem(i, { quantity: e.target.value })} aria-label="Quantity" required /> + × + + )} + + +
+ {hasVariants && ( + + )} +
+ ); + })} +
+ +
+ + {!exact && ( +
+
+ + set("setSize", e.target.value)} required /> +
+ {d.kind === "free" && ( +
+ + set("freeCount", e.target.value)} required /> +
+ )} + {d.kind === "group" && ( +
+ + +
+ )} +
+ )} + + {d.kind === "free" ? ( +
+ {size > free && free > 0 + ? <>Buy {size - free}, get {free} free. In every {size} qualifying tickets, the cheapest {free === 1 ? "one is" : `${free} are`} free. + : The set needs more tickets than are free.} +
+ ) : ( +
+ + set("price", e.target.value)} required /> + {d.kind === "group" ? ( +

+ {size >= 2 ? `From ${size} qualifying tickets, every one of them ` : "Every qualifying ticket "} + {d.groupPricing === "percent" ? `gets ${d.price || "…"}% off.` : `costs ${d.price === "" ? "…" : fmtRand(price)} (tickets already cheaper stay as they are).`} +

+ ) : ( + <> +
+
+
{exact ? "Separately" : "Dearest set"}
+
{fmtRand(standardValue)}
+
+
+
Bundle
+
{d.price === "" ? "—" : fmtRand(price)}
+
+
+
Saving
+
{d.price === "" ? "—" : fmtRand(Math.max(0, saving_))}
+
+
+ {d.price !== "" && saving_ <= 0 &&

The bundle isn't cheaper than the standard prices, so it won't apply unless prices change.

} + {!exact &&

The saving depends on which tickets are picked; it only applies when the set price is cheaper.

} + + )} +
+ )} + +
+
+ + set("validFrom", e.target.value)} /> +
+
+ + set("validUntil", e.target.value)} /> +
+
+ + + + {error &&
{error}
} +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx new file mode 100644 index 0000000..57d17dd --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx @@ -0,0 +1,236 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { useAuth } from "@/hooks/useAuth"; +import { useRouter, useSearchParams } from "next/navigation"; +import { fetchManagedEvents } from "@/lib/api"; +import { formatDate } from "@/lib/date"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { ShieldCheck, Send, RefreshCw, HeartPulse, Printer } from "lucide-react"; +import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; +import { errorMessage } from "@/lib/utils"; +import type { Event, ConsentRow, MedicalRow } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; +import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; + + +const STATUS_STYLE: Record = { + not_required: { label: "Not needed (18+)", cls: "bg-gray-100 text-gray-600" }, + missing: { label: "No request", cls: "bg-red-100 text-red-800" }, + pending: { label: "Pending", cls: "bg-amber-100 text-amber-800" }, + given: { label: "Given", cls: "bg-green-100 text-green-800" }, + declined: { label: "Declined", cls: "bg-red-100 text-red-800" }, +}; + +const esc = (s: unknown) => String(s ?? "").replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c] as string)); + +export default function ConsentTrackerPage() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const search = useSearchParams(); + const canView = useMemo(() => ["admin", "supervisor", "staff"].includes(user?.role || ""), [user]); + const isSupervisor = user?.role === "admin" || user?.role === "supervisor"; + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [events, setEvents] = useState([]); + const [eventId, setEventId] = useState(search.get("eventId") || ""); + type ConsentData = { event: Pick; counts: Record; rows: ConsentRow[] }; + const [data, setData] = useState(null); + const [filter, setFilter] = useState<"minors" | "all" | "waiting">("minors"); + const [busy, setBusy] = useState(false); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + + useEffect(() => { + if (!token || !canView) return; + fetchManagedEvents(token, { past: true }) + .then(evs => { + const youth = (evs || []).filter(e => e.requiresParentalConsent); + setEvents(youth); + if (!eventId && youth.length) setEventId(defaultEventId(youth)); + }) + .catch(e => setError(e?.message || "Failed to load events")); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [token, canView]); + + const load = useCallback(async () => { + if (!token || !eventId) return; + setBusy(true); + try { + setData(await (apiV2Data("get", "/events/{id}/consent", { params: { id: eventId }, authToken: token }) as Promise)); + } catch (e) { + setError(errorMessage(e) || "Failed to load consent status"); + } finally { + setBusy(false); + } + }, [token, eventId, setError]); + + useExternalEffect(() => { load(); }, [load]); + + const rows = useMemo(() => { + const all = data?.rows || []; + if (filter === "all") return all; + if (filter === "waiting") return all.filter(r => ["missing", "pending", "declined"].includes(r.status) || r.request?.outdated); + return all.filter(r => r.minor); + }, [data, filter]); + + const outdatedCount = (data?.rows || []).filter(r => r.request?.outdated || (r.minor && r.status === "missing")).length; + + const act = async (fn: () => Promise) => { + setBusy(true); + try { + const res = (await fn()) as { message: string }; + setInfo(res.message); + await load(); + } catch (e) { + setError(errorMessage(e) || "Something went wrong"); + } finally { + setBusy(false); + } + }; + + const resendOne = (r: ConsentRow) => act(() => apiV2Data("post", "/consent-requests/{id}/resend", { params: { id: r.request!.id }, authToken: token, body: {} })); + const resendAll = () => act(() => apiV2Data("post", "/events/{id}/consent/resend-pending", { params: { id: eventId }, authToken: token, body: {} })); + const rerequest = () => act(() => apiV2Data("post", "/events/{id}/consent/rerequest", { params: { id: eventId }, authToken: token, body: {} })); + + // Printable list for camp leaders. Opening it is recorded in the audit log. + const printMedical = async () => { + try { + const res = await (apiV2Data("get", "/events/{id}/consent/medical", { params: { id: eventId }, authToken: token }) as Promise<{ event: Pick; rows: MedicalRow[] }>); + const w = window.open("", "_blank"); + if (!w) { setError("Allow pop-ups to print the medical list."); return; } + const rowsHtml = res.rows.map(r => ` + + ${esc(r.name)}
${r.dateOfBirth ? esc(formatDate(new Date(r.dateOfBirth))) : ""} + ${r.purged ? "Deleted after the event" : ` + ${r.medical?.allergies ? `
Allergies: ${esc(r.medical.allergies)}
` : ""} + ${r.medical?.medication ? `
Medication: ${esc(r.medical.medication)}
` : ""} + ${r.medical?.conditions ? `
Conditions: ${esc(r.medical.conditions)}
` : ""} + ${r.medical?.medicalAid ? `
Medical aid: ${esc(r.medical.medicalAid)}
` : ""}`} + ${r.emergency ? `${esc(r.emergency.name)}${r.emergency.relationship ? ` (${esc(r.emergency.relationship)})` : ""}
${esc(r.emergency.phone)}` : ""} + ${esc(r.parentName)}
${esc(r.parentPhone)} + ${r.photoConsent === null ? "" : r.photoConsent ? "Yes" : "No"} + `).join(""); + w.document.write(`Medical & emergency list — ${esc(res.event.title)} + +

Medical & emergency list — ${esc(res.event.title)}

+

Confidential — for event leaders only. Do not leave unattended; destroy after the event.

+ + ${rowsHtml || ''}
AttendeeMedicalEmergency contactParent / guardianPhotos
No consent given yet.
+ `); + w.document.close(); + } catch (e) { + setError(errorMessage(e) || "Failed to load the medical list"); + } + }; + + return ( +
+
+
+ +
+
+ +

Parental consent

+

Youth events: who still needs a parent's consent before check-in

+
+
+ + {!canView &&
You need staff access to view consent status.
} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + { setEventId(id); }} placeholder="No youth events" /> +
+
+ + +
+ {isSupervisor && eventId && ( +
+ + + +
+ )} +
+ + {data && ( +
+ {(["given", "pending", "declined", "missing"] as const).map(s => ( + {STATUS_STYLE[s].label}: {data.counts?.[s] || 0} + ))} +
+ )} + +
+ + + + Attendee + Parent / guardian + Consent + Booked by + Actions + + + + {rows.map(r => { + const st = STATUS_STYLE[r.status]; + return ( + + +
{r.name}
+
{r.dateOfBirth ? formatDate(new Date(r.dateOfBirth)) : "No date of birth"}
+
+ + {r.parentName ? <> +
{r.parentName}
+
{[r.parentEmail, r.parentPhone].filter(Boolean).join(" · ")}
+ : —} +
+ + {st.label} + {r.request?.outdated &&
Given on an older version of the text
} + {r.request?.respondedAt &&
{r.request.signedName} · {formatDate(new Date(r.request.respondedAt))}
} + {r.status === "pending" && r.request &&
Sent {formatDate(new Date(r.request.lastSentAt))}{r.request.remindersSent ? ` · ${r.request.remindersSent} reminder(s)` : ""}
} +
+ {r.bookedBy?.name}
{r.registrationStatus}
+ + {r.status === "pending" && r.request && ( + + )} + +
+ ); + })} + {!busy && rows.length === 0 && ( + {eventId ? "No attendees to show." : "Pick a youth event."} + )} +
+
+
+

Reminders go out automatically 2 days after a request, then every 3 days until the event. Medical details are deleted a set number of days after the event (Site Settings → Legal).

+
+ )} +
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx new file mode 100644 index 0000000..721dbc7 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx @@ -0,0 +1,690 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { useAuth } from "@/hooks/useAuth"; +import { useRouter } from "next/navigation"; +import { fetchManagedEvents } from "@/lib/api"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, ListChecks } from "lucide-react"; +import { errorMessage } from "@/lib/utils"; +import { BackLink } from "@/components/shared/BackLink"; +import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; + +type CouponType = "percent" | "fixed" | "comp"; +type Role = "user" | "staff" | "supervisor" | "admin"; + +type EventLite = { + id: string; + title: string; + startDate: string; + endDate?: string; + eventOptions: { id: string; name: string; variants?: { id: string; name: string }[] }[]; +}; + +type Coupon = { + id: string; + code: string; + description: string | null; + type: CouponType; + value: number; + stackEarlyBird: boolean; + validFrom: string | null; + validUntil: string | null; + maxUses: number | null; + maxUsesPerUser: number | null; + minQuantity: number | null; + restrictRoles: Role[]; + restrictDomain: string | null; + active: boolean; + summary: string; + uses: number; + totalDiscount: number; + events: { eventId: string; event: { id: string; title: string } }[]; + options: { eventOptionId: string; variantId: string | null; eventOption: { name: string; eventId: string }; variant: { name: string } | null }[]; + allowedUsers: { userId: string; user: { id: string; name: string; email: string } }[]; +}; + +type Redemption = { + id: string; + discountAmount: number; + createdAt: string; + releasedAt: string | null; + user: { name: string; email: string }; + appliedBy: { name: string } | null; + registration: { status: string; event: { title: string } }; +}; + +type Draft = { + code: string; + description: string; + type: CouponType; + value: string; + stackEarlyBird: boolean; + validFrom: string; + validUntil: string; + maxUses: string; + maxUsesPerUser: string; + minQuantity: string; + eventIds: string[]; + options: { eventOptionId: string; variantId: string | null }[]; + restrictTo: "anyone" | "roles" | "users" | "domain"; + restrictRoles: Role[]; + restrictDomain: string; + users: { id: string; name: string; email: string }[]; + active: boolean; +}; + +const blankDraft = (): Draft => ({ + code: "", description: "", type: "percent", value: "", stackEarlyBird: false, + validFrom: "", validUntil: "", maxUses: "", maxUsesPerUser: "1", minQuantity: "", + eventIds: [], options: [], restrictTo: "anyone", restrictRoles: ["staff", "supervisor", "admin"], + restrictDomain: "", users: [], active: true, +}); + +// wants local "YYYY-MM-DDTHH:mm". +const toLocalInput = (iso: string | null) => { + if (!iso) return ""; + const d = new Date(iso); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; +}; + +function draftFromCoupon(c: Coupon): Draft { + const restrictTo: Draft["restrictTo"] = c.allowedUsers.length ? "users" : c.restrictRoles.length ? "roles" : c.restrictDomain ? "domain" : "anyone"; + return { + code: c.code, description: c.description || "", type: c.type, value: c.type === "comp" ? "" : String(c.value), + stackEarlyBird: c.stackEarlyBird, validFrom: toLocalInput(c.validFrom), validUntil: toLocalInput(c.validUntil), + maxUses: c.maxUses ? String(c.maxUses) : "", maxUsesPerUser: c.maxUsesPerUser ? String(c.maxUsesPerUser) : "", + minQuantity: c.minQuantity ? String(c.minQuantity) : "", eventIds: c.events.map(e => e.eventId), + options: c.options.map(o => ({ eventOptionId: o.eventOptionId, variantId: o.variantId })), + restrictTo, restrictRoles: c.restrictRoles.length ? c.restrictRoles : ["staff", "supervisor", "admin"], + restrictDomain: c.restrictDomain || "", users: c.allowedUsers.map(u => u.user), active: c.active, + }; +} + +function bodyFromDraft(d: Draft) { + return { + code: d.code.trim(), + description: d.description.trim() || null, + type: d.type, + value: d.type === "comp" ? 0 : Number(d.value), + stackEarlyBird: d.stackEarlyBird, + validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null, + validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null, + maxUses: d.maxUses || null, + maxUsesPerUser: d.maxUsesPerUser || null, + minQuantity: d.minQuantity || null, + eventIds: d.eventIds, + options: d.options, + restrictRoles: d.restrictTo === "roles" ? d.restrictRoles : [], + restrictDomain: d.restrictTo === "domain" ? d.restrictDomain.trim() : null, + userIds: d.restrictTo === "users" ? d.users.map(u => u.id) : [], + active: d.active, + }; +} + +const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : ""); +const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`; +const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"; +const isPast = (ev: EventLite) => new Date(ev.endDate || ev.startDate).getTime() < Date.now(); + +type Status = { key: "active" | "scheduled" | "off" | "expired" | "used"; label: string; cls: string }; +function couponStatus(c: Coupon): Status { + const now = Date.now(); + if (!c.active) return { key: "off", label: "Off", cls: "bg-gray-100 text-gray-600" }; + if (c.validUntil && new Date(c.validUntil).getTime() < now) return { key: "expired", label: "Expired", cls: "bg-gray-100 text-gray-600" }; + if (c.maxUses && c.uses >= c.maxUses) return { key: "used", label: "Used up", cls: "bg-gray-100 text-gray-600" }; + if (c.validFrom && new Date(c.validFrom).getTime() > now) return { key: "scheduled", label: "Scheduled", cls: "bg-amber-100 text-amber-800" }; + return { key: "active", label: "Active", cls: "bg-green-100 text-green-800" }; +} + +export default function CouponsPage() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + const [coupons, setCoupons] = useState([]); + const [events, setEvents] = useState([]); + const [fetching, setFetching] = useState(false); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + const [query, setQuery] = useState(""); + const [showInactive, setShowInactive] = useState(false); + + const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null); + const [viewing, setViewing] = useState<{ coupon: Coupon; redemptions: Redemption[] } | null>(null); + + const load = useCallback(async () => { + if (!token) return; + setFetching(true); + try { + const [c, ev] = await Promise.all([ + (apiV2Data("get", "/coupons", { authToken: token }) as Promise), + fetchManagedEvents(token, { past: true }), + ]); + setCoupons(c || []); + setEvents(ev || []); + } catch (e) { + setError(errorMessage(e) || "Failed to load coupons"); + } finally { + setFetching(false); + } + }, [token, setError]); + + useExternalEffect(() => { if (token && canView) load(); }, [token, canView, load]); + + // Codes that can still be used first; off, expired and used-up ones only when asked for. + const visible = useMemo(() => { + const q = query.trim().toLowerCase(); + const order: Record = { active: 0, scheduled: 1, used: 2, expired: 3, off: 4 }; + return coupons + .map(c => ({ c, status: couponStatus(c) })) + .filter(({ c, status }) => (showInactive || status.key === "active" || status.key === "scheduled") + && (!q || c.code.toLowerCase().includes(q) || (c.description || "").toLowerCase().includes(q) || c.events.some(e => e.event.title.toLowerCase().includes(q)))) + .sort((a, b) => order[a.status.key] - order[b.status.key]); + }, [coupons, query, showInactive]); + const hiddenCount = coupons.filter(c => !["active", "scheduled"].includes(couponStatus(c).key)).length; + + const toggleActive = async (c: Coupon) => { + try { + await apiV2Data("patch", "/coupons/{id}", { params: { id: c.id }, authToken: token, body: { active: !c.active } }); + setInfo(`${c.code} turned ${c.active ? "off" : "on"}.`); + load(); + } catch (e) { + setError(errorMessage(e) || "Failed to update coupon"); + } + }; + + const openUses = async (c: Coupon) => { + try { + const full = await (apiV2Data("get", "/coupons/{id}", { params: { id: c.id }, authToken: token }) as Promise); + setViewing({ coupon: c, redemptions: full.redemptions || [] }); + } catch (e) { + setError(errorMessage(e) || "Failed to load uses"); + } + }; + + const startNew = () => setEditing({ id: null, draft: blankDraft() }); + + return ( +
+
+
+
+ +
+
+ +

Coupon codes

+

Discounts for staff, leaders, volunteers and promotions

+
+
+ {canView && ( + + )} +
+ + {!canView && ( +
You need supervisor access to manage coupon codes.
+ )} + {error &&
{error}
} + {info &&
{info}
} + + {canView && ( +
+
+
+ + setQuery(e.target.value)} /> +
+ +
+ + {!fetching && visible.length === 0 && ( +
+
+ +
+

{coupons.length === 0 ? "No coupon codes yet" : "No codes match"}

+

e.g. "STAFF50": 50% off for staff, or "WELCOME20": R20 off for first-time visitors.

+ {coupons.length === 0 && ( + + )} +
+ )} + + {visible.length > 0 && ( +
+ {visible.map(({ c, status }) => ( + openUses(c)} + onEdit={() => setEditing({ id: c.id, draft: draftFromCoupon(c) })} + onToggle={() => toggleActive(c)} + /> + ))} +
+ )} +
+ )} + + {editing && ( + setEditing(null)} + onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }} + /> + )} + + {viewing && ( + Uses of {viewing.coupon.code}} onClose={() => setViewing(null)}> + {viewing.redemptions.length === 0 ? ( +

This code hasn't been used yet.

+ ) : ( +
    + {viewing.redemptions.map(r => ( +
  • +
    +
    {r.user.name}
    +
    {r.user.email}
    +
    {r.registration.event.title} · {fmtDate(r.createdAt)}
    + {r.appliedBy &&
    Applied by {r.appliedBy.name}
    } +
    +
    +
    {fmtRand(r.discountAmount)}
    + {r.releasedAt &&
    Released (cancelled)
    } +
    +
  • + ))} +
+ )} +
+ )} +
+ ); +} + +/** A dialog that slides up full-width on phones and sits centred on bigger screens. */ +function Sheet({ title, subtitle, onClose, children, footer, onSubmit }: { + title: React.ReactNode; + subtitle?: React.ReactNode; + onClose: () => void; + children: React.ReactNode; + footer?: React.ReactNode; + onSubmit?: (e: React.FormEvent) => void; +}) { + const Box = onSubmit ? "form" : "div"; + return ( +
+ e.stopPropagation()}> +
+
+

{title}

+ {subtitle &&

{subtitle}

} +
+ +
+
{children}
+ {footer &&
{footer}
} +
+
+ ); +} + +function CouponCard({ coupon: c, status, onUses, onEdit, onToggle }: { coupon: Coupon; status: Status; onUses: () => void; onEdit: () => void; onToggle: () => void }) { + const restricted = c.allowedUsers.length + ? `${c.allowedUsers.length} ${c.allowedUsers.length === 1 ? "person" : "people"}` + : c.restrictRoles.length ? c.restrictRoles.map(r => (r === "user" ? "members" : r)).join(", ") : c.restrictDomain ? `@${c.restrictDomain}` : null; + const dates = c.validFrom || c.validUntil ? `${c.validFrom ? fmtDate(c.validFrom) : "Now"} – ${c.validUntil ? fmtDate(c.validUntil) : "no end date"}` : null; + const limits = [ + c.maxUses ? `${c.maxUses} uses in total` : null, + c.maxUsesPerUser ? `${c.maxUsesPerUser} per person` : null, + c.minQuantity ? `min ${c.minQuantity} tickets` : null, + ].filter(Boolean).join(" · "); + const live = status.key === "active" || status.key === "scheduled"; + + return ( +
+
+
+
{c.code}
+ {c.description &&
{c.description}
} +
+ {status.label} +
+ +
+ {c.summary} + {c.options.length > 0 && ( + on {c.options.map(o => o.eventOption.name + (o.variant ? ` (${o.variant.name})` : "")).join(", ")} + )} +
+ +
+ {c.events.length === 0 + ? All events + : c.events.map(e => ( + {e.event.title} + ))} +
+ +
+
Used {c.uses}{c.maxUses ? ` / ${c.maxUses}` : ""}× · {fmtRand(c.totalDiscount)} given
+ {restricted &&
Only for {restricted}
} + {dates &&
{dates}
} + {limits &&
{limits}
} +
+ +
+ + + +
+
+ ); +} + +function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { + token: string; + events: EventLite[]; + couponId: string | null; + initial: Draft; + onClose: () => void; + onSaved: (message: string) => void; +}) { + const [d, setD] = useState(initial); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const [userQuery, setUserQuery] = useState(""); + const [foundUsers, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); + const searchingUsers = d.restrictTo === "users" && userQuery.trim().length >= 2; + // Only while there's a search (a shorter query clears the list without another render). + const userResults = searchingUsers ? foundUsers : []; + const [eventQuery, setEventQuery] = useState(""); + const [showPast, setShowPast] = useState(false); + const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); + + // Upcoming events soonest first. Past events only when asked for, but ones already + // picked always stay in the list so they can be unticked. + const eventChoices = useMemo(() => { + const q = eventQuery.trim().toLowerCase(); + const upcoming = events.filter(e => !isPast(e)).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); + const past = events.filter(isPast).sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime()); + return [...upcoming, ...past] + .filter(e => showPast || !isPast(e) || d.eventIds.includes(e.id)) + .filter(e => !q || e.title.toLowerCase().includes(q)); + }, [events, eventQuery, showPast, d.eventIds]); + const pastCount = events.filter(isPast).length; + + // Ticket options only make sense within the chosen events. + const scopedEvents = useMemo(() => events.filter(e => d.eventIds.includes(e.id)), [events, d.eventIds]); + + useEffect(() => { + if (!searchingUsers) return; + const t = setTimeout(async () => { + try { + const res = await (apiV2Data("get", "/users", { query: { search: userQuery.trim(), limit: "8" }, authToken: token }) as Promise<{ data: { id: string; name: string; email: string }[] }>); + setUserResults(res?.data || []); + } catch { setUserResults([]); } + }, 300); + return () => clearTimeout(t); + }, [userQuery, searchingUsers, token]); + + const toggleEvent = (id: string) => { + const eventIds = d.eventIds.includes(id) ? d.eventIds.filter(x => x !== id) : [...d.eventIds, id]; + // Drop scoped options from events that are no longer selected. + const keepOptionIds = new Set(events.filter(e => eventIds.includes(e.id)).flatMap(e => e.eventOptions.map(o => o.id))); + setD(prev => ({ ...prev, eventIds, options: prev.options.filter(o => keepOptionIds.has(o.eventOptionId)) })); + }; + + const scopeKey = (o: { eventOptionId: string; variantId: string | null }) => `${o.eventOptionId}::${o.variantId || ""}`; + const toggleScope = (eventOptionId: string, variantId: string | null) => { + const key = scopeKey({ eventOptionId, variantId }); + set("options", d.options.some(o => scopeKey(o) === key) ? d.options.filter(o => scopeKey(o) !== key) : [...d.options, { eventOptionId, variantId }]); + }; + + const save = async (e: React.FormEvent) => { + e.preventDefault(); + setError(null); + if (d.restrictTo === "users" && d.users.length === 0) { setError("Add at least one person, or choose another restriction."); return; } + setSaving(true); + try { + const body = bodyFromDraft(d); + if (couponId) { + await apiV2Data("patch", "/coupons/{id}", { params: { id: couponId }, authToken: token, body: body as never }); + onSaved(`${body.code.toUpperCase()} saved.`); + } else { + await apiV2Data("post", "/coupons", { authToken: token, body: body as never }); + onSaved(`${body.code.toUpperCase()} created.`); + } + } catch (err) { + setError(errorMessage(err) || "Failed to save"); + } finally { + setSaving(false); + } + }; + + const label = "block text-sm font-medium text-gray-700 mb-1"; + const optional = (optional); + + return ( + + + + + )} + > +
+
+
+ + set("code", e.target.value.toUpperCase().replace(/[^A-Z0-9_-]/g, ""))} placeholder="STAFF50" required maxLength={32} /> +

Letters, numbers, - and _. Not case-sensitive when entered.

+
+
+ + set("description", e.target.value)} placeholder="Staff discount for Camp 2026" /> +

Only staff see this.

+
+
+ +
+ +
+ {([["percent", "Percentage", "e.g. 20% off"], ["fixed", "Amount off", "e.g. R50 off"], ["comp", "Free", "100% off"]] as [CouponType, string, string][]).map(([t, name, hint]) => ( + + ))} +
+ {d.type !== "comp" && ( +
+ + set("value", e.target.value)} required /> +
+ )} + +
+ +
+ +

+ {d.eventIds.length === 0 ? "None picked: the code works for every event." : `${d.eventIds.length} picked. The code only works for ${d.eventIds.length === 1 ? "this event" : "these events"}.`} +

+
+
+ + setEventQuery(e.target.value)} /> +
+ {pastCount > 0 && ( + + )} +
+
+ {eventChoices.map(ev => ( + + ))} + {eventChoices.length === 0 &&

{eventQuery ? "No events match." : "No upcoming events."}

} +
+
+ + {scopedEvents.length > 0 && ( +
+ +

Leave all unticked to discount the whole registration.

+
+ {scopedEvents.map(ev => ( +
+
{ev.title}
+ {ev.eventOptions.map(o => ( +
+ + {(o.variants || []).map(v => ( + + ))} +
+ ))} +
+ ))} +
+
+ )} + +
+
+ + set("validFrom", e.target.value)} /> +
+
+ + set("validUntil", e.target.value)} /> +
+
+ +
+
+ + set("maxUses", e.target.value)} placeholder="Unlimited" /> +
+
+ + set("maxUsesPerUser", e.target.value)} placeholder="Unlimited" /> +
+
+ + set("minQuantity", e.target.value)} placeholder="None" /> +
+
+ +
+ + + {d.restrictTo !== "anyone" && ( +

Restricted codes need the person to be logged in (or registered by staff), so they can't be shared in group chats.

+ )} + + {d.restrictTo === "roles" && ( +
+ {(["user", "staff", "supervisor", "admin"] as Role[]).map(r => ( + + ))} +
+ )} + + {d.restrictTo === "domain" && ( + set("restrictDomain", e.target.value)} placeholder="church.org" required /> + )} + + {d.restrictTo === "users" && ( +
+
+ {d.users.map(u => ( + + {u.name} + + + ))} +
+ setUserQuery(e.target.value)} placeholder="Search by name, email or phone" /> + {userResults.length > 0 && ( +
+ {userResults.filter(r => !d.users.some(u => u.id === r.id)).map(r => ( + + ))} +
+ )} +
+ )} +
+ + + + {error &&
{error}
} +
+
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx new file mode 100644 index 0000000..3499e21 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -0,0 +1,1229 @@ +"use client"; + +import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react"; +import { useAuth } from "@/hooks/useAuth"; +import { useRouter, useSearchParams } from "next/navigation"; +import { fetchAllUsers, fetchManagedEvents } from "@/lib/api"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { Mail, Users, Zap, Clock } from "lucide-react"; +import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter"; +import { errorMessage } from "@/lib/utils"; +import type { Event, MessageSendResult, Registration, User } from "@/types"; +import { BackLink } from "@/components/shared/BackLink"; +import { MessageKindPicker, matchedText, type MessageKind } from "@/components/shared/MessageKindPicker"; +import { CampusAudiencePicker } from "@/components/shared/CampusAudiencePicker"; +import { EventPicker } from "@/components/shared/EventPicker"; +import { apiV2Data } from "@/lib/apiV2"; +import { AiDraftMessage } from "@/components/shared/AiDraftMessage"; +import { AiImprove } from "@/components/shared/AiImprove"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; + +type Attendee = { id: string; name: string; email: string; pref: string }; +type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets'; +type StatusFilter = 'any'|'paid'|'unpaid'|'partial_paid'|'cancelled'; +type MessageFilter = { status?: Exclude; attendeeIds?: string[]; allocationGroupId?: string }; +// A message body goes as `html` when it looks like markup, otherwise as plain `text`. +type EmailContent = { html?: string; text?: string }; +type EmailSendResult = MessageSendResult<{ email: string; name?: string }>; + +export default function EmailAttendeesPage() { + return ( + Loading...}> + + + ); +} + +function AttendeesCheckboxDropdown({ + attendees, + loading, + selectedIds, + onChange, + channel = "email", +}: { + attendees: { id: string; name: string; email?: string; pref: string }[]; + loading: boolean; + selectedIds: string[]; + onChange: (ids: string[]) => void; + channel?: "email" | "whatsapp"; +}) { + const [open, setOpen] = useState(false); + + const allIds = useMemo(() => attendees.map(a => a.id), [attendees]); + const allSelected = selectedIds.length > 0 && selectedIds.length === allIds.length; + const noneSelected = selectedIds.length === 0; + + const prefMatch = (pref: string) => + channel === "email" ? pref === "email" || pref === "both" : pref === "whatsapp" || pref === "both"; + + const prefLabel = (pref: string) => { + if (pref === "both") return "both"; + if (pref === "whatsapp") return "WA"; + if (pref === "email") return "email"; + return pref || "email"; + }; + + const mismatched = selectedIds.filter(id => { + const a = attendees.find(x => x.id === id); + return a && !prefMatch(a.pref); + }); + + const toggleAll = (checked: boolean) => onChange(checked ? allIds : []); + const toggleId = (id: string) => { + if (selectedIds.includes(id)) onChange(selectedIds.filter(x => x !== id)); + else onChange([...selectedIds, id]); + }; + + const summary = loading + ? "Loading attendees…" + : attendees.length === 0 + ? "No attendees" + : allSelected + ? `All attendees (${attendees.length})` + : noneSelected + ? "None selected" + : `${selectedIds.length} selected`; + + return ( +
+ + {open && ( +
+
+ +
+ + +
+
+ {loading ? ( +
Loading…
+ ) : attendees.length === 0 ? ( +
No attendees found
+ ) : ( +
    + {attendees.map(a => { + const checked = selectedIds.includes(a.id); + const match = prefMatch(a.pref); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ +
+
+ )} +
+ ); +} + +function PrefWarning({ attendees, selectedIds, channel }: { attendees: { id: string; pref: string }[]; selectedIds: string[]; channel: "email" | "whatsapp" }) { + const mismatched = useMemo(() => { + const prefMatch = (pref: string) => + channel === "email" ? pref === "email" || pref === "both" : pref === "whatsapp" || pref === "both"; + return selectedIds.filter(id => { + const a = attendees.find(x => x.id === id); + return a && !prefMatch(a.pref); + }); + }, [attendees, selectedIds, channel]); + + if (mismatched.length === 0) return null; + return ( +
+ {mismatched.length} selected attendee(s) have a notification preference that doesn't include{" "} + {channel === "email" ? "email" : "WhatsApp"}. They will still receive the message, but it may not be their preferred channel. + {" "}Use the dropdown to filter by preference. +
+ ); +} + +function EmailAttendeesPageInner() { + const { user, loading, token } = useAuth(); + const router = useRouter(); + const search = useSearchParams(); + const preselectEventId = search?.get("eventId") || ""; + + const canView = useMemo(() => { + const role = user?.role; + return role === "admin" || role === "supervisor"; + }, [user]); + + useEffect(() => { + if (loading) return; + if (!user) router.replace("/login"); + }, [user, loading, router]); + + // Load events for selection + const [loadingEvents, setLoadingEvents] = useState(false); + const [error, setError] = useDismissingState(null); + const [info, setInfo] = useDismissingState(null); + + // Tabs: attendees (current), automations (coming soon), broadcasts + const [tab, setTab] = useState<'attendees'|'automations'|'broadcasts'|'scheduled'>('attendees'); + + const [allEvents, setAllEvents] = useState([]); + // Every event; the pickers open on upcoming ones and keep past ones a click away. + const events = allEvents; + + const loadEvents = useCallback(async () => { + try { + setLoadingEvents(true); + const evs = await fetchManagedEvents(token || undefined, { past: true }); + const sorted = (evs || []).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); + setAllEvents(sorted); + } catch (e) { + setError(errorMessage(e) || "Failed to load events"); + } finally { + setLoadingEvents(false); + } + }, [token, setError]); + + // Reload when the signed-in user changes too (e.g. after an impersonation switch). + useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]); + + const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]); + const [loadingUsers, setLoadingUsers] = useState(false); + // Load users for broadcasts + useExternalEffect(() => { + const run = async () => { + try { + if (!token) return; + setLoadingUsers(true); + const allUsers = await fetchAllUsers(token); + const mapped = allUsers + .filter((u) => u.isActive !== false && !u.email?.endsWith('@guest.local')) + .map((u) => ({ id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' })) + .sort((a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' })); + setUsers(mapped); + } catch { + // ignore for now + } finally { + setLoadingUsers(false); + } + }; + run(); + }, [token]); + + // Form state + const [eventId, setEventId] = useState(preselectEventId); + useStateSync(() => { + if (preselectEventId) setEventId(preselectEventId); + }, [preselectEventId]); + + const [templateKey, setTemplateKey] = useState('custom'); + const [messageKind, setMessageKind] = useState('update'); + const [showInfo, setShowInfo] = useState(false); + + // Broadcasts state + const [selectedUserIds, setSelectedUserIds] = useState([]); + const [broadcastEventId, setBroadcastEventId] = useState(""); + const [broadcastSubject, setBroadcastSubject] = useState(""); + const [broadcastBody, setBroadcastBody] = useState(""); + const [broadcastEmails, setBroadcastEmails] = useState(""); + const [broadcastPreviewCount, setBroadcastPreviewCount] = useState(null); + const [broadcastPreviewSample, setBroadcastPreviewSample] = useState<{email:string;name?:string}[]|null>(null); + const [broadcastScheduledAtLocal, setBroadcastScheduledAtLocal] = useState(""); + const [broadcastKind, setBroadcastKind] = useState('news'); + const resetBroadcastForm = () => { + setBroadcastKind('news'); + setSelectedUserIds([]); + setBroadcastEventId(""); + setBroadcastSubject(""); + setBroadcastBody(""); + setBroadcastEmails(""); + setBroadcastPreviewCount(null); + setBroadcastPreviewSample(null); + setBroadcastScheduledAtLocal(""); + }; + + // Scheduled jobs state + type ScheduledJob = { id: string; kind: 'attendees'|'broadcast'|'unknown'; eventId?: string|null; broadcast?: boolean; channel?: string; recipient?: string|null; scheduledAt: string; createdAt: string; status: 'queued'|'sending'|'sent'|'error'; attempts: number; sentAt?: string|null; lastError?: string|null; subject?: string; html?: string; text?: string; hasHtml?: boolean; hasText?: boolean }; + const [scheduled, setScheduled] = useState([]); + const [loadingScheduled, setLoadingScheduled] = useState(false); + const [editing, setEditing] = useState(null); + const [editSubject, setEditSubject] = useState(''); + const [editBody, setEditBody] = useState(''); + const [editWhen, setEditWhen] = useState(''); + const [savingEdit, setSavingEdit] = useState(false); + + const loadScheduled = useCallback(async () => { + try { + if (!token) return; + setLoadingScheduled(true); + const res = await (apiV2Data("get", "/scheduled-messages", { query: { channel: "email" }, authToken: token }) as Promise<{jobs: ScheduledJob[]}>); + setScheduled(Array.isArray(res?.jobs) ? res.jobs : []); + } catch { + // ignore here; surfaces via UI when tab open + } finally { + setLoadingScheduled(false); + } + }, [token]); + + useExternalEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]); + + const openEdit = (job: ScheduledJob) => { + setEditing(job); + setEditSubject(job.subject || ''); + setEditBody(job.html || job.text || ''); + try { setEditWhen(toLocalInputValue(new Date(job.scheduledAt))); } catch { setEditWhen(''); } + }; + + const saveEdit = async () => { + if (!editing) return; + try { + setSavingEdit(true); + if (!token) { setError('Not authenticated'); return; } + const body: { scheduledAt?: string; subject?: string } & EmailContent = {}; + if (editWhen) body.scheduledAt = new Date(editWhen).toISOString(); + if (editSubject.trim().length || editBody.trim().length) { + body.subject = editSubject; + if (editBody.trim()) { + if (editBody.trim().startsWith('<')) body.html = editBody; else body.text = editBody; + } else { + // if clearing body, explicitly set text to empty to override + body.text = ''; + body.html = ''; + } + } + await apiV2Data("patch", "/scheduled-messages/{id}", { params: { id: editing.id }, authToken: token, body }); + setInfo('Scheduled email updated.'); + setEditing(null); + loadScheduled(); + } catch (e) { + setError(errorMessage(e) || 'Failed to update scheduled email'); + } finally { + setSavingEdit(false); + } + }; + + const removeJob = async (job: ScheduledJob) => { + try { + if (!token) { setError('Not authenticated'); return; } + await apiV2Data("delete", "/scheduled-messages/{id}", { params: { id: job.id }, authToken: token }); + setInfo('Scheduled email removed.'); + loadScheduled(); + } catch (e) { + setError(errorMessage(e) || 'Failed to remove scheduled email'); + } + }; + + const [subject, setSubject] = useState(""); + const [body, setBody] = useState(""); + const [subjectDirty, setSubjectDirty] = useState(false); + const [bodyDirty, setBodyDirty] = useState(false); + const [status, setStatus] = useState("any"); + const [groupId, setGroupId] = useState(""); + // Attendees list and selection + const [attendees, setAttendees] = useState([]); + const [selectedAttendeeIds, setSelectedAttendeeIds] = useState([]); + const [loadingAttendees, setLoadingAttendees] = useState(false); + + // Event helper to prefill templates + const currentEvent = useMemo(() => (events || []).find(e => e.id === eventId), [events, eventId]); + + // A template fills in the subject and message, unless they were typed over. + useStateSync(() => { + const title = currentEvent?.title || 'the event'; + if (templateKey === 'payment_reminder') { + if (!subjectDirty) setSubject(`Payment reminder: ${title}`); + if (!bodyDirty) setBody(`Hi {{name}}\n\nThis is a friendly reminder that you have an outstanding balance of {{balance}} for {{event.title}}.\nEvent starts: {{event.start}}\n\nPlease settle your balance to secure your tickets. Thank you!`); + } else if (templateKey === 'event_reminder') { + if (!subjectDirty) setSubject(`Reminder: ${title}`); + if (!bodyDirty) setBody(`Hi {{name}}\n\nA quick reminder about {{event.title}}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`); + } else if (templateKey === 'tickets') { + // Tickets template does not require subject/body + setSubjectDirty(false); + setBodyDirty(false); + setSubject(''); + setBody(''); + } + // custom: leave whatever the supervisor typed alone. + // When event changes, refresh defaults if not dirty + }, [templateKey, currentEvent, subjectDirty, bodyDirty]); + + const [previewCount, setPreviewCount] = useState(null); + const [previewSample, setPreviewSample] = useState<{email:string;name?:string}[] | null>(null); + const [sending, setSending] = useState(false); + const [scheduledAtLocal, setScheduledAtLocal] = useState(""); + + const mismatchedAttendees = useMemo( + () => selectedAttendeeIds.filter(id => { + const a = attendees.find(x => x.id === id); + return a && a.pref !== 'email' && a.pref !== 'both'; + }), + [attendees, selectedAttendeeIds] + ); + + // Load attendees when event changes + useEffect(() => { + const run = async () => { + try { + setLoadingAttendees(true); + setAttendees([]); + setSelectedAttendeeIds([]); + if (!eventId || !token) return; + const regs = await (apiV2Data("get", "/events/{id}/registrations", { params: { id: eventId }, authToken: token }) as Promise); + const uniq = new Map(); + (regs || []).forEach((r) => { + const u: User | undefined = r?.user; + if (u?.id && u?.email && !u.email.endsWith('@guest.local') && u.isActive !== false) { + uniq.set(u.id, { id: u.id, name: u.name || '', email: u.email || '', pref: u.notificationPreference || 'email' }); + } + }); + const list = Array.from(uniq.values()).sort((a,b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' })); + setAttendees(list); + // Default: select those with email/both preference; fall back to all + const matching = list.filter(a => a.pref === 'email' || a.pref === 'both').map(a => a.id); + setSelectedAttendeeIds(matching.length > 0 ? matching : list.map(a => a.id)); + } catch { + // ignore + } finally { + setLoadingAttendees(false); + } + }; + run(); + }, [eventId, token]); + + const onPreview = async () => { + try { + setError(null); setInfo(null); setPreviewCount(null); setPreviewSample(null); + if (!token) { setError("Not authenticated"); return; } + if (!eventId) { setError("Please select an event"); return; } + if (templateKey !== 'tickets') { + if (!subject.trim()) { setError("Subject is required"); return; } + if (!body.trim()) { setError("Message is required"); return; } + } + const payload: { subject: string; filter: MessageFilter; dryRun: boolean; template: TemplateKey; kind: MessageKind } & EmailContent = { + subject: subject || "(no subject)", + filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined }, + dryRun: true, + template: templateKey, + kind: messageKind, + }; + if (templateKey !== 'tickets') { + if (body.trim().startsWith('<')) payload.html = body; else payload.text = body; + } + const res = await (apiV2Data("post", "/events/{id}/email-attendees", { params: { id: eventId }, authToken: token, body: payload }) as Promise); + setPreviewCount(res?.matched ?? 0); + setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null); + setInfo(matchedText(res)); + } catch (e) { + setError(errorMessage(e) || 'Failed to preview recipients'); + } + }; + + const resetAttendeesForm = () => { + setTemplateKey('custom'); + setMessageKind('update'); + setSubject(''); setBody(''); + setSubjectDirty(false); setBodyDirty(false); + setStatus('any'); + setScheduledAtLocal(''); + setPreviewCount(null); setPreviewSample(null); + // Keep event selection but reselect email/both attendees + const matching = attendees.filter(a => a.pref === 'email' || a.pref === 'both').map(a => a.id); + setSelectedAttendeeIds(matching.length > 0 ? matching : attendees.map(a => a.id)); + }; + + const onSend = async () => { + try { + setError(null); setInfo(null); + if (!token) { setError("Not authenticated"); return; } + if (!eventId) { setError("Please select an event"); return; } + if (templateKey !== 'tickets') { + if (!subject.trim()) { setError("Subject is required"); return; } + if (!body.trim()) { setError("Message is required"); return; } + } + setSending(true); + const payload: { subject: string; filter: MessageFilter; template: TemplateKey; kind: MessageKind } & EmailContent = { + subject, + filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined }, + template: templateKey, + kind: messageKind, + }; + if (templateKey !== 'tickets') { + if (body.trim().startsWith('<')) payload.html = body; else payload.text = body.replace(/\n/g, '\n'); + } + const res = await (apiV2Data("post", "/events/{id}/email-attendees", { params: { id: eventId }, authToken: token, body: payload }) as Promise); + const queued = res?.queued ?? res?.matched ?? 0; + setInfo(`Queued ${queued} recipient(s) for sending.`); + // Reset form to default state + resetAttendeesForm(); + } catch (e) { + setError(errorMessage(e) || 'Failed to send emails'); + } finally { + setSending(false); + } + }; + + return ( +
+
+
+
+ +
+
+ +

Email Attendees

+
+
+
+ + {!canView && ( +
+ You need supervisor or admin access to use this page. +
+ )} + + {error &&
{error}
} + {info &&
{info}
} + + {/* Tabs like on Payments page */} +
+ + + + +
+ + {tab === 'attendees' && ( +
+
+
+ +
+ + {loadingEvents && Loading…} +
+
+ +
+
+
+ + +
+ +
+
+
Available placeholders: {'{{name}}'}, {'{{event.title}}'}, {'{{event.start}}'}, {'{{balance}}'}, {'{{payment.link}}'}
+
+
+ + {templateKey !== 'tickets' && ( + + )} + + {showInfo && ( +
+
setShowInfo(false)} /> +
+
+
+

Dynamic parameters

+ +
+
+

You can personalize your subject and message using these placeholders. They will be replaced per recipient when sending.

+
    +
  • {'{{name}}'} — attendee’s name.
  • +
  • {'{{event.title}}'} — the event title.
  • +
  • {'{{event.start}}'} — the event start date/time (local).
  • +
  • {'{{balance}}'} — outstanding amount across the attendee’s registrations for the selected event.
  • +
  • {'{{payment.link}}'} — a direct online payment link for the attendee's outstanding balance (generated per recipient when sending).
  • +
+

Example: Hi {'{{name}}'}, your balance is {'{{balance}}'}. Pay here: {'{{payment.link}}'}

+

To add new placeholders, extend backend/src/utils/placeholders.js and update this help.

+
+
+
+
+ )} + +
+
+ + { setSubject(e.target.value); setSubjectDirty(true); }} placeholder="Subject" /> +
+
+ + +
+ +
+ + {templateKey !== 'tickets' ? ( +
+
+ { setSubject(d.subject); setSubjectDirty(true); setBody(d.body); setBodyDirty(true); }} /> +
+ + +
+
+ + setEditWhen(e.target.value)} /> +
+
+ + +
+
+
+
+
+ )} + + )} + + ); +} + + +function toLocalInputValue(d: Date) { + const pad = (n: number) => String(n).padStart(2, '0'); + const y = d.getFullYear(); + const m = pad(d.getMonth() + 1); + const day = pad(d.getDate()); + const hh = pad(d.getHours()); + const mm = pad(d.getMinutes()); + return `${y}-${m}-${day}T${hh}:${mm}`; +} + +function AutomationsPanel({ events, token, onInfo, onError }:{ events: Event[]; token?: string | null; onInfo: (s: string | null) => void; onError: (s: string | null) => void }) { + const [autoEventId, setAutoEventId] = React.useState(''); + const currentEvent = React.useMemo(() => (events || []).find((e) => e.id === autoEventId), [events, autoEventId]); + + // Defaults builders + const preWeekDefault = React.useMemo(() => ({ + subject: `1 Week to Go: {{event.title}}!`, + body: `Hi {{name}}\n\nJust a friendly reminder that {{event.title}} is one week away.\n\nVenue: [add venue]\nTime: {{event.start}}\nParking: [add parking info]\nPacking list: [add items if needed]\n\nMore details: {{event.link}}`, + }), []); + const finalDefault = React.useMemo(() => ({ + subject: `We’ll See You Tomorrow at {{event.title}}!`, + body: `Hi {{name}}\n\nFinal reminder for {{event.title}}.\nArrival instructions: [add arrival info]\nPlease have your QR code/ticket ready at entry.\n\nEvent details: {{event.link}}`, + }), []); + const thanksDefault = React.useMemo(() => ({ + subject: `Thanks for Joining {{event.title}}!`, + body: `Hi {{name}}\n\nThank you for joining us at {{event.title}}!\nHighlights: [add highlights]\nPhotos/recordings: [add links]\nSponsor shoutouts: [add sponsors]\n\nSee you next time!`, + }), []); + const promoDefault = React.useMemo(() => ({ + subject: `Don’t Miss Our Next Event: {{promo.title}}`, + body: `Hi {{name}}\n\nWe’d love to see you at our next event: {{promo.title}}.\nFind out more and register here: {{promo.link}}`, + }), []); + + // Enable toggles + const [enablePre, setEnablePre] = React.useState(true); + const [enableFinal, setEnableFinal] = React.useState(true); + const [enableThanks, setEnableThanks] = React.useState(true); + // Sponsors of "sponsor a spot" events get their own thank-you. + const [enableSponsors, setEnableSponsors] = React.useState(true); + const [sponsorSubject, setSponsorSubject] = React.useState('Thank you for sponsoring a spot at {{event.title}}'); + const [sponsorBody, setSponsorBody] = React.useState(`Hi {{name}} + +Thank you for sponsoring a spot at {{event.title}}. Because of you, someone was able to be there who otherwise couldn't. + +[add a highlight or two] + +With gratitude`); + const [enablePromo, setEnablePromo] = React.useState(false); + + // Subjects/Bodies + const [preSubject, setPreSubject] = React.useState(preWeekDefault.subject); + const [preBody, setPreBody] = React.useState(preWeekDefault.body); + const [finalSubject, setFinalSubject] = React.useState(finalDefault.subject); + const [finalBody, setFinalBody] = React.useState(finalDefault.body); + const [thanksSubject, setThanksSubject] = React.useState(thanksDefault.subject); + const [thanksBody, setThanksBody] = React.useState(thanksDefault.body); + const [promoSubject, setPromoSubject] = React.useState(promoDefault.subject); + const [promoBody, setPromoBody] = React.useState(promoDefault.body); + + // Timing + const [finalHours, setFinalHours] = React.useState<'24'|'48'>('24'); + const [preWhen, setPreWhen] = React.useState(''); + const [finalWhen, setFinalWhen] = React.useState(''); + const [thanksWhen, setThanksWhen] = React.useState(''); + const [promoWhen, setPromoWhen] = React.useState(''); + const [promoEventId, setPromoEventId] = React.useState(''); + + // Compute defaults when event changes or finalHours change + useStateSync(() => { + if (!currentEvent) { setPreWhen(''); setFinalWhen(''); setThanksWhen(''); setPromoWhen(''); return; } + try { + const start = new Date(currentEvent.startDate); + const end = new Date(currentEvent.endDate || currentEvent.startDate); + // Pre-event: 7 days before start at 09:00 + const pre = new Date(start); + pre.setDate(pre.getDate() - 7); + pre.setHours(9, 0, 0, 0); + setPreWhen(toLocalInputValue(pre)); + // Final reminder: hours before start + const fin = new Date(start); + fin.setHours(fin.getHours() - (finalHours === '48' ? 48 : 24)); + setFinalWhen(toLocalInputValue(fin)); + // Thanks: day after end at 09:00 + const ty = new Date(end); + ty.setDate(ty.getDate() + 1); + ty.setHours(9, 0, 0, 0); + setThanksWhen(toLocalInputValue(ty)); + // Promo: 3 days after end at 09:00 + const pr = new Date(end); + pr.setDate(pr.getDate() + 3); + pr.setHours(9, 0, 0, 0); + setPromoWhen(toLocalInputValue(pr)); + // Prefill subjects again using event title (user can edit afterward) + const title = currentEvent.title || 'the event'; + setPreSubject(`1 Week to Go: ${title}!`); + setFinalSubject(`We’ll See You Tomorrow at ${title}!`); + setThanksSubject(`Thanks for Joining ${title}!`); + setPromoSubject(`Don’t Miss Our Next Event: {{promo.title}`); + } catch {} + }, [currentEvent, finalHours]); + + const onSchedule = async () => { + try { + onError(null); onInfo(null); + if (!token) { onError('Not authenticated'); return; } + if (!autoEventId) { onError('Please select an event'); return; } + type AutomationJob = { subject: string; scheduledAt: string; audience?: 'sponsors'; promoEventId?: string } & EmailContent; + const jobs: AutomationJob[] = []; + if (enablePre && preSubject.trim() && preBody.trim() && preWhen) { + const payload: AutomationJob = { subject: preSubject, scheduledAt: new Date(preWhen).toISOString() }; + if (preBody.trim().startsWith('<')) payload.html = preBody; else payload.text = preBody; + jobs.push(payload); + } + if (enableFinal && finalSubject.trim() && finalBody.trim() && finalWhen) { + const payload: AutomationJob = { subject: finalSubject, scheduledAt: new Date(finalWhen).toISOString() }; + if (finalBody.trim().startsWith('<')) payload.html = finalBody; else payload.text = finalBody; + jobs.push(payload); + } + if (enableThanks && thanksSubject.trim() && thanksBody.trim() && thanksWhen) { + const payload: AutomationJob = { subject: thanksSubject, scheduledAt: new Date(thanksWhen).toISOString() }; + if (thanksBody.trim().startsWith('<')) payload.html = thanksBody; else payload.text = thanksBody; + jobs.push(payload); + } + if (currentEvent?.allowSponsorships && enableSponsors && sponsorSubject.trim() && sponsorBody.trim() && thanksWhen) { + const payload: AutomationJob = { subject: sponsorSubject, scheduledAt: new Date(thanksWhen).toISOString(), audience: 'sponsors' }; + if (sponsorBody.trim().startsWith('<')) payload.html = sponsorBody; else payload.text = sponsorBody; + jobs.push(payload); + } + if (enablePromo && promoSubject.trim() && promoBody.trim() && promoWhen) { + const payload: AutomationJob = { subject: promoSubject, scheduledAt: new Date(promoWhen).toISOString(), promoEventId: promoEventId || undefined }; + if (promoBody.trim().startsWith('<')) payload.html = promoBody; else payload.text = promoBody; + jobs.push(payload); + } + if (jobs.length === 0) { onError('Please enable at least one automation and fill in details'); return; } + const res = await (apiV2Data("post", "/automations/schedule", { authToken: token, body: { eventId: autoEventId, jobs } }) as Promise<{ message?: string }>); + onInfo(res?.message || `Scheduled ${jobs.length} automation(s).`); + // Reset to defaults (keep event selection) + setEnablePre(true); setEnableFinal(true); setEnableThanks(true); setEnablePromo(false); + setPreSubject(preWeekDefault.subject); setPreBody(preWeekDefault.body); + setFinalSubject(finalDefault.subject); setFinalBody(finalDefault.body); setFinalHours('24'); + setThanksSubject(thanksDefault.subject); setThanksBody(thanksDefault.body); + setPromoSubject(promoDefault.subject); setPromoBody(promoDefault.body); setPromoEventId(''); + } catch (e) { + onError(errorMessage(e) || 'Failed to schedule automations'); + } + }; + + return ( +
+
+ + +
+ +
+
+ Pre-Event Reminder (1 week before) + +
+
+ + setPreSubject(e.target.value)} placeholder="1 Week to Go: {{event.title}}!" /> +
+
+ + setPreWhen(e.target.value)} /> +
+
+ +