diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index cc04ffb..8b8adb7 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -77,6 +77,17 @@ and this project follows [Semantic Versioning](https://semver.org/). 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 diff --git a/apps/events/FEATURES.md b/apps/events/FEATURES.md index fe4b09f..e982985 100644 --- a/apps/events/FEATURES.md +++ b/apps/events/FEATURES.md @@ -903,8 +903,8 @@ can't start, the same jobs run on in-process timers. - **Sentry** error monitoring when `SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN` are set. - Unhandled promise rejections are logged and don't crash the server. -- Backend status page (`/`) and built-in API docs page (`/docs`); **API v2** (`/api/v2`, 1.51.0) - with one error shape, paged lists and an OpenAPI 3.1 reference at `/docs/v2` (admins). Public +- Backend status page (`/`); **API v2** (`/api/v2`, 1.51.0 — the only API since 2.0, which removed + v1; `/docs` redirects to `/docs/v2`) with one error shape, paged lists and an OpenAPI 3.1 reference at `/docs/v2` (admins). Public events, my account and registrations, registering, cancelling and paying online (1.51.1), signing up, logging in (with the 2FA step), changing my details and checking tickets in (1.51.2; the scanner and at-the-door use it from 1.51.3); the frontend's v2 calls are typed from the diff --git a/apps/events/README.md b/apps/events/README.md index ef017f5..727d69c 100644 --- a/apps/events/README.md +++ b/apps/events/README.md @@ -20,7 +20,8 @@ The backend provides a RESTful API for managing users, events, registrations, pa - Static uploads for event images Documentation: see Backend API Documentation and Backend README for environment setup and endpoints. -- Backend API Documentation: ./backend/API_DOCUMENTATION.md +- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md +- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md - Backend README: ./backend/README.md ### Frontend @@ -155,7 +156,8 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use. ## Useful Links -- Backend API Documentation: ./backend/API_DOCUMENTATION.md +- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md +- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md - Backend README: ./backend/README.md - Frontend README: ./frontend/README.md - Site Settings — defaults reference: ./SETTINGS.md @@ -163,6 +165,9 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use. ## Recent Changes +> Older notes, kept for history. The `/api/…` paths they mention are API v1, removed in 2.0 — +> MIGRATING-TO-2.md lists each one's v2 replacement. Since 1.33 the changes are in CHANGELOG.md. + ### Sold-out handling, tiered stock warnings & UI polish **Backend** diff --git a/apps/events/SETTINGS.md b/apps/events/SETTINGS.md index f4771b2..e2f8693 100644 --- a/apps/events/SETTINGS.md +++ b/apps/events/SETTINGS.md @@ -60,7 +60,7 @@ or Branding tab has been saved even once — the wizard always writes ## Payments -Managed in the Payments tab (through `/api/payments/providers/settings` and `/api/yoco`, not the generic settings endpoints). +Managed in the Payments tab (through `/api/v2/payments/providers/settings` and `/api/v2/payments/yoco/config`, not the generic settings endpoints). | Setting | Default when unset | Notes | |---|---|---| @@ -89,7 +89,7 @@ Managed in the Payments tab (through `/api/payments/providers/settings` and `/ap | Setting | Default when unset | Notes | |---|---|---| -| `campuses_enabled` | `false` | Site settings → Campuses → "Use campuses". Changed only through `PUT /api/campuses/settings` (audited); hidden from the generic settings endpoints. Off hides campus fields and filters everywhere; campuses and each event's campus are kept. The campuses themselves are in the `Campus` table. | +| `campuses_enabled` | `false` | Site settings → Campuses → "Use campuses". Changed only through `PUT /api/v2/campuses/enabled` (audited); hidden from the generic settings endpoints. Off hides campus fields and filters everywhere; campuses and each event's campus are kept. The campuses themselves are in the `Campus` table. | ## Cross Events Hub (licence) @@ -106,7 +106,7 @@ Managed in the Payments tab (through `/api/payments/providers/settings` and `/ap | Setting | Default when unset | Notes | |---|---|---| | `WAWP_ACCESS_TOKEN` / `WAWP_INSTANCE_ID` | `WAWP_ACCESS_TOKEN`/`WAWP_INSTANCE_ID` env vars, else *(blank)* | No hardcoded default — WhatsApp sending is simply unavailable until both are configured (Admin → Site Settings → WhatsApp). | -| `WAWP_WEBHOOK_SECRET` | Generated (random) the first time the WhatsApp tab is opened | Part of the webhook URL shown in Site Settings → WhatsApp (`/api/whatsapp/webhook?secret=…`). WAWP doesn't sign webhooks, so incoming messages (STOP replies) are only acted on when the secret matches. Not editable in the UI; delete the row to get a new one (then update the URL in WAWP). The URL uses `BACKEND_URL`. | +| `WAWP_WEBHOOK_SECRET` | Generated (random) the first time the WhatsApp tab is opened | Part of the webhook URL shown in Site Settings → WhatsApp (`/api/v2/webhooks/whatsapp?secret=…`; set-ups from before 1.51.16 use `/api/whatsapp/webhook?secret=…`, which still works). WAWP doesn't sign webhooks, so incoming messages (STOP replies) are only acted on when the secret matches. Not editable in the UI; delete the row to get a new one (then update the URL in WAWP). The URL uses `BACKEND_URL`. | ## Privacy (POPIA) diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index 3089939..5b2ac86 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,25 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 2.0.0 + +- **AI helpers.** Where you already work, a button can now do the first draft for you: describe + an event in a sentence and the new-event form is filled in; turn a short note into a friendly + email or WhatsApp message; get a plain-language summary under a report or of an event's + feedback; or improve, shorten or correct a piece of text. You always see the suggestion first — + nothing is saved or sent until you do it. The buttons appear when your licence includes an AI + allowance (ask us about it); Site settings → AI shows what's been used this month. Only what a + helper needs is sent: email addresses and phone numbers in your text stay on your site, reports + are only summarised when they list no people, and feedback goes without names. +- **Stronger password protection.** Passwords are now stored with a stronger, modern method. Nobody + needs to do anything: each person's password is upgraded the next time they sign in. +- **The site banner keeps time.** A banner with start and end times now appears and disappears at + those times on pages that are already open. +- **For anyone with their own integration** (a script or website plug-in that talks to Cross Events + directly): the old version of the connection was retired. Payments, WhatsApp replies and links in + emails you've already sent keep working. Whoever looks after your integration can ask us for the + migration guide. + ## 1.52.3 - **A licence check fix.** When a site's licence has run out or isn't connected, the site is diff --git a/apps/events/docs/HANDOVER.md b/apps/events/docs/HANDOVER.md index 0ae19dd..04de392 100644 --- a/apps/events/docs/HANDOVER.md +++ b/apps/events/docs/HANDOVER.md @@ -1,6 +1,6 @@ # Handover — where things stand and how to carry on -Last updated: 2026-11-02, after **1.52.2** and Hub **1.6.0**; 2.0.0 in progress on `release/2.0`. The plan itself is in +Last updated: 2026-11-02, after **1.52.3** and Hub **1.6.1**; 2.0.0 in progress on `release/2.0`. The plan itself is in [ROADMAP-v2.md](./ROADMAP-v2.md) (decisions table at the end); the previous round of features is in [FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md). @@ -14,6 +14,7 @@ encrypted settings unreadable or break existing installs. | Version | What | |---------|------| +| 1.52.3 | **Urgent fix:** licence read-only mode blocks the `/api/v2` routes too (`src/hub/readOnly.js` only listed v1 paths, and the screens have used v2 since 1.51.15). A test checks each blocked v2 path is a real route | | 1.52.2 | `scripts/deploy.sh` stops first (listing them) when files in the install were changed or added by hand; `--check` runs only that; runs from a copy outside the install too; `ALLOW_LOCAL_CHANGES=1` overrides | | 1.52.1 | **API documentation complete:** every v2 route documents its body, answer and parameters — the ~300 answered by v1 handlers through `documented` shapes (`src/v2/docs.ts`), shown but not enforced, logged outside production when they don't fit; empty bodies say "No body needed". Test `tests/v2Docs.test.ts` | | 1.52.0 | **Urgent fix + Corrections:** required attendee forms no longer leave paid door/manual registrations without tickets — popup with "Fill in later" (`Registration.formWaivedAt`, `POST /api/v2/registrations/{id}/form-later`); one form per person on picked sessions; forms with no questions don't hold tickets; kiosk asks for the forms the server says are missing. Admin **Corrections** page (`src/services/corrections.ts`, `/api/v2/corrections/…`): issue missing tickets, pay later (`ticketsReleasedAt`), make it free (`complimentaryDiscount`), check in after the event. Migration `20261102120000_corrections`. e2e `e2e/corrections.spec.ts` | @@ -79,40 +80,35 @@ encrypted settings unreadable or break existing installs. ## Next up -Hub 1.1.0 is deployed with update requests rolled out, and `scripts/install.sh` has been tried on -a test server (both done 2026-10-28). - -1. **2.0.0 — in progress on `release/2.0`** (WIP commit per part; tag 2.0.0 only when all of it - is in). The parts and their state are in the roadmap's Status table: - - ✅ **Hub 1.6.0** — the AI proxy (tagged, pushed). Real Claude calls tested 2026-10-30 through - a local Hub with Joshua's key: fine, and a fraction of a cent each. - - ✅ **AI plumbing** on Cross Events (`backend/src/ai/`, `/api/v2/ai/*`, Site settings → AI, - ``, `useAiStatus()`; roadmap §15 "Progress"). - - **Next: the five helpers** (`backend/src/ai/helpers.ts`, their routes and buttons, an eval set, - privacy notice text). - - Then **v1 removed** — keep answering the v1 webhook paths and the old links in sent messages - (`src/v2/links.ts`): providers and old emails still use them. Then the **migration guide**. +1. **2.0.0 — on `release/2.0`** (a WIP commit per part; tag 2.0.0 only when all of it is in). + State per part is in the roadmap's Status table: + - ✅ **Hub 1.6.0 – 1.6.1** — the AI proxy, model list with prices (Sonnet 5.5 for every helper). + - ✅ **AI plumbing** and ✅ **the five helpers** with their buttons, the eval set (`npm run ai:eval`, + 19/19 through a local Hub on 2026-10-30) and the privacy notice text. + - ✅ **v1 removed** (2026-11-02, see [v1 removed](#v1-removed-20)), with ✅ **Argon2id passwords** + ([Passwords](#passwords-20)) and ✅ `node-fetch` gone. Backend 690 tests and e2e 102/102 pass. + - ✅ **Migration guide:** `MIGRATING-TO-2.md` (generated v1 → v2 table at the end). + - ✅ **React Compiler lint rules back to errors** (2026-11-02; see [Next.js 16](#nextjs-16-1515)) — + `npx eslint src` clean, e2e 102/102, production build passes. + - **Still to do for 2.0:** the 2.0.0 sections of WHATS-NEW.md (church-facing: AI helpers, + stronger passwords; nothing else they'd notice) and the CHANGELOG heading; README/FEATURES/ + SETTINGS passes for v1 references (README still lists `/api/...` endpoints); then merge + `release/2.0` into `main` and tag `v2.0.0`. - **Marketing site** (roadmap §17): a simple static HTML site — Cross Code as the main site, - with a Cross Events page; room for a church app and a full church website later. Repo, - domain and hosting to decide first. + with a Cross Events page. Repo, domain, hosting, prices shown or not, and the contact route + to decide first. - Testing AI locally: run the Hub (`../events-hub`, port 5200), set Settings → AI there, give a test licence an AI cap, and start Cross Events with `HUB_URL=http://localhost:5200`. 2. **AI rules** (decided 2026-10-29, roadmap §15): the AI buttons show only when the licence's monthly cap is above R0, and are disabled (not hidden) once it's reached. The Hub charges the real cost plus a markup % (a default and a per-licence override) and counts the cap in charged - rand. AI endpoints are `/api/v2` only. The model is **Claude Sonnet 5.5** for every helper - (2026-10-30, after a Haiku/Sonnet trial), set on the Hub (Settings → AI, Hub 1.6.1); its list + rand. AI endpoints are `/api/v2` only. The model is set on the Hub (Settings → AI); its list prices live in `events-hub/backend/src/utils/aiModels.js`. -3. **Clean-ups before or with 2.0:** - - Turn the React Compiler lint rules back to errors (see [Next.js 16](#nextjs-16-1515)) — every - screen is on v2 now, but they're still `warn` in `frontend/eslint.config.mjs`. - - `node-fetch` is still listed in `backend/package.json` though nothing in `src/` uses it — - remove it. - - Password hashing upgrade with rehash-on-login (roadmap §14) isn't done: still `bcryptjs`. - Decide whether it's in 2.0. -4. **Later:** move from ExcelTS — deprecated in favour of `documonster` by the same author - (pre-1.0 in Oct 2026) — once documonster is stable. After 1.51.7 has run everywhere, the old - `pgboss` schema can be dropped (`DROP SCHEMA pgboss CASCADE;`). +3. **Later (2.x):** move the v1 controllers behind `v1Route` into TypeScript services (the v2 API + doesn't change); remove the handlers no v2 route uses any more (e.g. the v1 scan handler and + `v1ScanResponse`, `v1Status` in `services/errors.ts`). Move from ExcelTS to `documonster` once + it is stable. After 1.51.7 has run everywhere, drop the old `pgboss` schema + (`DROP SCHEMA pgboss CASCADE;`). Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026-10-28). @@ -129,8 +125,8 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 - **Changelog:** add entries to `[Unreleased]` as you go, in plain language. CHANGELOG.md is the full log; WHATS-NEW.md is what churches see before updating (the Hub reads it from main every 15 minutes, for tagged versions only and sets the latest version from the tags — nothing to do in the Hub). -- **Docs to keep in step:** CHANGELOG.md, FEATURES.md, README.md, SETTINGS.md, - backend/API_DOCUMENTATION.md, the `/docs` route list in `backend/src/app.js` (v2 documents itself), and +- **Docs to keep in step:** CHANGELOG.md, FEATURES.md, README.md, SETTINGS.md (the API documents + itself at `/docs/v2`; `backend/API_DOCUMENTATION.md` only points there), and in-app help in `frontend/src/content/help/` (register new pages in `registry.ts`). - **Prisma migrations:** `npx prisma migrate dev --create-only --name x` against a local DB. Prisma 7 keeps adding an unrelated `_EventNotifyRecipients` primary-key/index @@ -585,10 +581,27 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 - Turbopack for dev and build (the default). Lint with `npm run lint` / `npx eslint src` (`next lint` is gone). There's no middleware/proxy file — add `src/proxy.ts` (Next 16's name) only if needed. -- **React Compiler lint rules are warnings, not errors** (`eslint.config.mjs`): 181 existing places, - mostly `useEffect(() => { load(); }, [...])`. The plan was to fix them as each screen moved onto - v2; every screen is on v2 now (1.51.15) but the rules are still `warn` — fix what's left and turn - them back to errors before or with 2.0. Don't add new ones. +- **React Compiler lint rules are errors** again (2.0; they were warnings from 1.51.5 with 181 + places to fix). How the code meets them — `frontend/src/lib/hooks.ts`: + - **State that follows other state or props** ("when the event changes, start the form again", + "each time the popup opens, clear it"): `useStateSync(update, deps)` — updates while rendering + (React's "adjusting state when a prop changes"). Deps must be stable values: a new array or + object each render loops (e.g. key on `campuses[0]?.id`, not the list). Prefer computing in + render, or setting it in the event handler that causes the change. + - **Loading from the API or reading the browser** (localStorage, the URL, a cookie, browser + events) and setting state from it: `useExternalEffect(run, deps)` — `useEffect` under a name that + says why. Both hooks' deps are checked by exhaustive-deps (`additionalHooks` in + `eslint.config.mjs`); to reload when something not used in the body changes, name it inside + (`void user;`). + - **Search results that clear when the box is emptied:** don't clear them in the effect — show + `query ? results : []` and let the effect only set state when the answer comes. + - **Time:** `useNow()` in client components (re-renders every minute); server components may + call `Date.now()` with the disable comment that says why (one render per request). + - **Navigation:** `useRouter().push()`; `hardNavigate()` (`lib/navigation.ts`) only where the + whole app must start again (signing out, impersonation, the 2FA redirect in `lib/api.ts`); + `window.location.assign(url)` for payment providers. + - The one deliberate exception is `useAnchorRect` (events page): measuring the DOM in + `useLayoutEffect` before paint. - `eslint-config-next` 16's bundled plugins (react, import, jsx-a11y) don't list ESLint 10 as a peer yet; they work, and npm notes the override. Revisit when they publish ESLint 10 support. @@ -645,6 +658,34 @@ Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026 `utils/webhooks.js`; `tests/webhooks.test.js` fails if an example and `buildPayload` differ in shape. +## v1 removed (2.0) + +- `/api/…` answers **410** `API_V1_REMOVED` (`v1Removed` in `src/v2/links.ts`), except what outside + senders still use: `/api/webhooks/yoco|payfast|whatsapp` (`routes/webhookRoutes.js`, before the + JSON parser), WAWP's oldest `/api/whatsapp/webhook` and a mail app's one-click POST to + `/api/privacy/unsubscribe/:token/one-click` (`legacyV1Router`), and the 308s for links in sent + messages (`legacyLinkRedirects`). `/docs` redirects to `/docs/v2`. +- Only three v1 route files are left: `webhookRoutes.js`, and `dashboardRoutes.js` / + `savedFilterRoutes.js`, whose handlers v2 runs as routers. The controllers stay — `v1Route` runs + them behind v2 routes. +- **Path lists name v2 paths:** `hub/readOnly.js` (add any new "create" route there, with a test in + `tests/hub.test.js`, which also checks each pattern is a real route), `ALLOWED_WRITES` in + `utils/impersonation.js`. +- **Campus scope test** is `tests/v2CampusScope.test.ts`: every staff/supervisor v2 route has a + marked middleware (`scopeEvent`, `scopeBody`, `scopeList`, `campusIndependent`…) or is listed in + `CHECKED_IN_HANDLER` because its service checks campuses itself. +- e2e calls v2 only: `v2(page, role, method, url, body)` in `e2e/fixtures.ts` returns `data`. + Playwright waits for `/api/v2/setup/needed`. + +## Passwords (2.0) + +- `src/config/auth.js`: `hashPassword` is Argon2id (`@node-rs/argon2`, 19 MiB, 2 passes, 1 lane — + OWASP's minimum; prebuilt binaries, nothing to compile). `comparePassword` checks Argon2 and the + bcrypt hashes from before 2.0 (`bcryptjs` stays for that). `needsRehash` is true for bcrypt or + weaker Argon2 settings; `logIn` (`services/auth.ts`) saves a new hash after a right password. +- Raising the settings later: change `ARGON2` — everyone is re-hashed at their next sign-in. + Tests: `tests/passwords.test.js`, and the re-hash in `tests/accountEnumeration.test.ts`. + ## Known gaps / follow-ups - WhatsApp STOP only works once someone pastes the webhook URL from Site settings → WhatsApp diff --git a/apps/events/docs/ROADMAP-v2.md b/apps/events/docs/ROADMAP-v2.md index 56133b3..78dee06 100644 --- a/apps/events/docs/ROADMAP-v2.md +++ b/apps/events/docs/ROADMAP-v2.md @@ -20,8 +20,8 @@ when all of it is in (decided 2026-10-30): | 1 | AI proxy: key, metering in rand, caps, markup, usage views; model list with prices (Sonnet 5.5 default) | Hub 1.6.0 – 1.6.1 (`events-hub`) | ✅ tagged; real Claude calls tested 2026-10-30 | | 2 | AI plumbing: `/api/v2/ai/status`, usage, Site settings → AI, ``, `useAiStatus()`, `AiCall` log, Anthropic operator entry | `release/2.0` | ✅ committed (WIP) | | 3 | The five helpers (§15) with their buttons, an eval set, privacy notice text | `release/2.0` | ✅ committed (WIP); eval 19/19 through a local Hub (2026-10-30) | -| 4 | v1 removed (webhook paths and old message links keep working); clean-ups: Argon2id passwords with rehash-on-login, `node-fetch` gone, React Compiler lint rules back to errors | `release/2.0` | ✅ v1, passwords, `node-fetch` (2026-11-02); lint rules in progress | -| 5 | Migration guide (`MIGRATING-TO-2.md`), docs | `release/2.0` | guide ✅ (2026-11-02); docs in progress | +| 4 | v1 removed (webhook paths and old message links keep working); clean-ups: Argon2id passwords with rehash-on-login, `node-fetch` gone, React Compiler lint rules back to errors | `release/2.0` | ✅ (2026-11-02) | +| 5 | Migration guide (`MIGRATING-TO-2.md`), docs | `release/2.0` | ✅ guide and docs (2026-11-02); 2.0.0 WHATS-NEW drafted | | 6 | Marketing site: Cross Code with a Cross Events page (§17) | its own repo | to do — repo, domain, hosting, prices and contact route still to decide | The full version list is in [HANDOVER.md](./HANDOVER.md) and the [build order](#suggested-build-order) below. diff --git a/apps/events/frontend/eslint.config.mjs b/apps/events/frontend/eslint.config.mjs index d5eb35b..3fa5d64 100644 --- a/apps/events/frontend/eslint.config.mjs +++ b/apps/events/frontend/eslint.config.mjs @@ -8,16 +8,13 @@ const eslintConfig = defineConfig([ ...nextVitals, ...nextTs, { - // React Compiler-era rules that eslint-plugin-react-hooks 7 (with Next 16) turns on as - // errors. They flag patterns the app uses on purpose and that work (mostly loading data in - // useEffect), so they're warnings while the code is moved off them screen by screen — - // see HANDOVER, "Next.js 16". New code should follow them. + // The React Compiler rules (set-state-in-effect, purity, immutability, refs, + // static-components) are errors, as eslint-plugin-react-hooks 7 sets them (back on in 2.0). + // Loading data or reading the browser in an effect: useExternalEffect; state that follows + // other state: useStateSync (both in lib/hooks.ts) — see HANDOVER, "Next.js 16". rules: { - "react-hooks/set-state-in-effect": "warn", - "react-hooks/purity": "warn", - "react-hooks/immutability": "warn", - "react-hooks/static-components": "warn", - "react-hooks/refs": "warn", + // Those two take deps like useEffect; check them the same way. + "react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^(useExternalEffect|useStateSync)$" }], }, }, globalIgnores([".next/**", ".next-*/**", "out/**", "build/**", "next-env.d.ts", "src/lib/api-v2/schema.d.ts"]), diff --git a/apps/events/frontend/src/app/activate-account/page.tsx b/apps/events/frontend/src/app/activate-account/page.tsx index e9d5e9f..334e1bc 100644 --- a/apps/events/frontend/src/app/activate-account/page.tsx +++ b/apps/events/frontend/src/app/activate-account/page.tsx @@ -9,6 +9,7 @@ import { appName } from "@/lib/siteConfig"; import { ShieldCheck } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { apiV2Data } from "@/lib/apiV2"; +import { hardNavigate } from "@/lib/navigation"; function ActivateAccountContent() { const search = useSearchParams(); @@ -34,7 +35,7 @@ function ActivateAccountContent() { // dashboard fresh so the new session is picked up. if (data?.token) saveToken(data.token); setStatus("Your account is now active. Redirecting…"); - setTimeout(() => { window.location.href = "/dashboard"; }, 1500); + setTimeout(() => hardNavigate("/dashboard"), 1500); } catch (err) { setStatus(errorMessage(err) || "Activation failed. The link may have expired."); } finally { diff --git a/apps/events/frontend/src/app/campus/[slug]/page.tsx b/apps/events/frontend/src/app/campus/[slug]/page.tsx index b7db1b8..e4026e0 100644 --- a/apps/events/frontend/src/app/campus/[slug]/page.tsx +++ b/apps/events/frontend/src/app/campus/[slug]/page.tsx @@ -43,6 +43,8 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s if (!campus) notFound(); const events = await apiFetchListForPrerender(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }); + // A server component renders once per request (or revalidation): this is that render's time. + // eslint-disable-next-line react-hooks/purity const now = Date.now(); const upcoming = (events || []) .filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now) diff --git a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx index eff96bd..1f32230 100644 --- a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx @@ -9,6 +9,7 @@ import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@ import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const ACTION_LABELS: Record = { refund_created: "Refund created", @@ -231,7 +232,7 @@ export default function AdminAuditLogPage() { }, [token, buildQuery, setError]); // load changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes. - useEffect(() => { if (token) load(1); }, [token, load]); + useExternalEffect(() => { if (token) load(1); }, [token, load]); return (
diff --git a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx index 12feb0e..de7776b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/cashup/[id]/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useCallback, useEffect, useMemo, useState } from "react"; +import React, { useCallback, useMemo, useState } from "react"; import { useParams } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { fetchEvent } from "@/lib/api"; @@ -11,6 +11,7 @@ import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { createCost, updateCost, deleteCost } from "@/lib/eventSetup"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const METHOD_LABELS: Record = { cash: "Cash", card: "Card", eft: "EFT", other: "Other" }; const METHODS: CashupMethod[] = ["cash", "card", "eft", "other"]; @@ -55,7 +56,7 @@ export default function EventCashupPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); return (
@@ -317,7 +318,7 @@ function CashByUserSection({ eventId, token, onCashSummaryChange }: { }, [eventId, token, onCashSummaryChange]); // onCashSummaryChange is a state setter in the parent, so this only reruns when the event/token change. - useEffect(load, [load]); + useExternalEffect(() => load(), [load]); const rows = data?.rows || []; const sumOf = (m: "cash" | "card" | "eft" | "other", key: "total" | "count") => @@ -947,7 +948,7 @@ function ReconciliationTab({ eventId, token, data, busy, setBusy, setError, onCh // CashByUserSection below; when there is one, cash on hand is whatever wasn't deposited. const [cashSummary, setCashSummary] = useState<{ actualTotal: number | null; denominations: PersonDenom[] }>({ actualTotal: null, denominations: [] }); - useEffect(() => { setLines(initialLines); }, [initialLines]); + useExternalEffect(() => { setLines(initialLines); }, [initialLines]); const setLine = (method: CashupMethod, next: SettlementInput) => setLines(prev => ({ ...prev, [method]: next })); diff --git a/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx b/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx index 816706a..fe17edd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/corrections/page.tsx @@ -12,6 +12,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { AttendeeFormModal, type AttendeeFormDef } from "@/components/shared/AttendeeFormModal"; import type { Event } from "@/types"; +import { useExternalEffect } from "@/lib/hooks"; // GET /api/v2/corrections/events/{id} (services/corrections.ts) type CorrectionTicket = { @@ -265,7 +266,7 @@ function CorrectionsContent() { } }, [token, eventId, setMessage]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); useEffect(() => { if (!eventId) return; fetchEvent(eventId, { authToken: token || undefined }) diff --git a/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx b/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx index 49d1f5a..159803e 100644 --- a/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/data-requests/page.tsx @@ -9,6 +9,7 @@ import { Inbox, AlertTriangle } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type RequestType = "access" | "correction" | "deletion"; type RequestStatus = "open" | "completed" | "rejected" | "cancelled"; @@ -144,10 +145,9 @@ export default function DataRequestsPage() { // Search once typing pauses; a new search or tab starts at page 1. useEffect(() => { - const t = setTimeout(() => setSearch(searchInput.trim()), 350); + const t = setTimeout(() => { setSearch(searchInput.trim()); setPage(1); }, 350); return () => clearTimeout(t); }, [searchInput]); - useEffect(() => { setPage(1); }, [view, search]); const [msg, setMsg] = useDismissingState(null); const load = useCallback(async () => { @@ -163,7 +163,7 @@ export default function DataRequestsPage() { setMsg({ type: "err", text: errorMessage(e) || "Could not load requests." }); } }, [token, view, page, search, setMsg]); - useEffect(() => { setRequests(null); load(); }, [load]); + useExternalEffect(() => { setRequests(null); load(); }, [load]); return (
@@ -181,7 +181,7 @@ export default function DataRequestsPage() {
{(["open", "closed"] as const).map(v => ( - ))} diff --git a/apps/events/frontend/src/app/dashboard/admin/page.tsx b/apps/events/frontend/src/app/dashboard/admin/page.tsx index f2f9e11..6a5ab55 100644 --- a/apps/events/frontend/src/app/dashboard/admin/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/page.tsx @@ -19,6 +19,7 @@ import { CampusFilter } from "@/components/shared/CampusFilter"; import { TodayPanel } from "@/components/dashboard/TodayPanel"; import { CommandPaletteButton } from "@/components/shared/CommandPalette"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`; const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`; @@ -108,7 +109,7 @@ export default function AdminDashboardPage() { } }, [token, campus, setPaymentStats, setOverview]); - useEffect(() => { + useExternalEffect(() => { if (!token) return; loadStats(); }, [token, loadStats]); diff --git a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx index becd3b9..047081b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/registrations/page.tsx @@ -13,6 +13,7 @@ import { RegistrationBulkBar } from "@/components/admin/RegistrationBulkBar"; import { SavedFilters } from "@/components/shared/SavedFilters"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const STATUS_OPTIONS = ["pending", "confirmed", "partial_paid", "paid", "cancelled"] as const; @@ -60,7 +61,8 @@ export default function AdminRegistrationsPage() { // Deep links (the dashboard's "Waiting for you" list and the Ctrl+K palette): ?q=, ?status=, ?event=. // A search by reference may be for a past event's registration, so past events are included then. - useEffect(() => { + // Deep links (the command palette, other pages): read the URL once. + useExternalEffect(() => { const params = new URLSearchParams(window.location.search); const q = params.get("q"); if (q) { setQuery(q); setIncludePastEvents(true); } @@ -103,11 +105,11 @@ export default function AdminRegistrationsPage() { } catch {} }, [token, includePastEvents, includeInactiveEvents]); - useEffect(() => { + useExternalEffect(() => { loadRegistrations(); }, [loadRegistrations]); - useEffect(() => { + useExternalEffect(() => { loadEvents(); }, [loadEvents]); diff --git a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx index 1d6ba5a..bd7aac9 100644 --- a/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/settings/page.tsx @@ -23,6 +23,7 @@ import { mapsSearchUrl } from "@/lib/maps"; import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { uploadImage } from "@/lib/eventSetup"; +import { useExternalEffect } from "@/lib/hooks"; type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai"; @@ -896,7 +897,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token]); - useEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]); + useExternalEffect(() => { if (active) fetchConfig(); }, [fetchConfig, active]); const fetchStatus = useCallback(async () => { if (!token || step !== 3) return; @@ -911,7 +912,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token, step, fetchConfig]); - useEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]); + useExternalEffect(() => { if (active && step === 3) fetchStatus(); }, [step, fetchStatus, active]); // Auto-poll status when not stable — only while this tab is active. useEffect(() => { @@ -931,7 +932,7 @@ function WhatsAppTab({ active }: { active: boolean }) { } }, [token]); - useEffect(() => { + useExternalEffect(() => { if (active && status === "SCAN_QR_CODE") { fetchQr(); } else { setQrSrc(null); } }, [status, fetchQr, active]); diff --git a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx index ad8adf3..9c4e57b 100644 --- a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx @@ -13,6 +13,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { useCampuses } from "@/hooks/useCampuses"; import { SavedFilters } from "@/components/shared/SavedFilters"; import { apiV2Data, apiV2 } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; interface UserItem { id: string; @@ -60,7 +61,7 @@ export default function AdminUsersPage() { const [activeFilter, setActiveFilter] = useState<"" | "true" | "false">(""); // ?q= (the Ctrl+K palette links here with a person's email). - useEffect(() => { + useExternalEffect(() => { const q = new URLSearchParams(window.location.search).get("q"); if (q) { setQuery(q); setDebouncedQuery(q); } }, []); @@ -113,7 +114,7 @@ export default function AdminUsersPage() { // Initial load, and back to page 1 whenever a filter or the page size changes // (loadUsers is recreated when any of them do). - useEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]); + useExternalEffect(() => { if (token) loadUsers(1); }, [token, loadUsers]); const goToPage = (p: number) => loadUsers(p); diff --git a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx index b849e0b..16e9591 100644 --- a/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/event-tickets/page.tsx @@ -14,6 +14,7 @@ import type { Event, Ticket as TicketRecord } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; function EventTicketsContent() { const { token, user } = useAuth(); @@ -60,7 +61,8 @@ function EventTicketsContent() { }, [token, setError]); // No event in the URL: default to the first upcoming one once the list arrives. - useEffect(() => { + // No event in the URL: pick the first and put it there. + useExternalEffect(() => { if (paramEventId || events.length === 0) return; setEventId(events[0].id); router.replace( @@ -71,7 +73,7 @@ function EventTicketsContent() { }, [events, paramEventId, router, selectedUserId]); // Sync params → state (setting the value it already has is a no-op) - useEffect(() => { + useStateSync(() => { if (paramEventId) setEventId(paramEventId); if (paramUserId) setSelectedUserId(paramUserId); }, [paramEventId, paramUserId]); diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx index 22c43b6..639e2d2 100644 --- a/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx @@ -19,6 +19,7 @@ import { FAMILY_QR_PREFIX, QR_PREFIX, deviceId, loadOffline, offlineCheckIn, saveOffline, stickerAlert, suggestRoom, type CheckInResult, type KidsBoard, type KidsFamily, type OfflineState, } from "@/lib/kids"; +import { useExternalEffect } from "@/lib/hooks"; type Tab = "in" | "out" | "rooms"; type Msg = { type: "ok" | "err"; text: string } | null; @@ -78,7 +79,7 @@ export default function KidsDeskPage() { } }, [token, eventId, sessionId, working]); - useEffect(() => { + useExternalEffect(() => { setBoard(null); setFamily(null); setResult(null); diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx index 4c9996b..5bbb720 100644 --- a/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useCallback, useEffect, useState } from "react"; +import React, { useCallback, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { errorMessage } from "@/lib/utils"; import { useVisiblePolling } from "@/hooks/useVisiblePolling"; @@ -11,6 +11,7 @@ import { KidsEventPicker } from "@/components/kids/KidsEventPicker"; import { RoomBoard, RoomStatusBadges } from "@/components/kids/RoomBoard"; import type { KidsBoard } from "@/lib/kids"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const ROOM_KEY = "hope_events_kids_room"; @@ -24,7 +25,7 @@ export default function KidsRoomsPage() { const [error, setError] = useState(null); const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); - useEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []); + useExternalEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []); const load = useCallback(async (log = false) => { if (!token || !eventId) return; @@ -37,7 +38,7 @@ export default function KidsRoomsPage() { } }, [token, eventId, sessionId]); - useEffect(() => { load(true); }, [load]); + useExternalEffect(() => { load(true); }, [load]); useVisiblePolling(() => { load(); }, 5000, !!token && !!eventId); const pickRoom = (id: string) => { diff --git a/apps/events/frontend/src/app/dashboard/staff/page.tsx b/apps/events/frontend/src/app/dashboard/staff/page.tsx index d987b01..6530c2d 100644 --- a/apps/events/frontend/src/app/dashboard/staff/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/page.tsx @@ -13,6 +13,7 @@ import { CampusScopeNote } from "@/components/shared/CampusFilter"; import { TodayPanel } from "@/components/dashboard/TodayPanel"; import { CommandPaletteButton } from "@/components/shared/CommandPalette"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const QUICK_ACTIONS = [ { href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode }, @@ -63,7 +64,7 @@ export default function StaffDashboardPage() { } }, [token, setStats, setRecentScans]); - useEffect(() => { + useExternalEffect(() => { if (!token) return; loadStats(); }, [token, loadStats]); diff --git a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx index 2f7a5f2..996567e 100644 --- a/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/ticket-scanning/page.tsx @@ -16,6 +16,7 @@ import { activeSessions, currentSessionLabel, formatSessionWhen, sessionLabel } import { BackLink } from "@/components/shared/BackLink"; import { apiV2, apiV2Data } from "@/lib/apiV2"; import { listSections } from "@/lib/eventSetup"; +import { useStateSync } from "@/lib/hooks"; // What the confirm step needs, from GET /api/v2/checkin/{qrCode}. Offline scans build the // same shape from the downloaded ticket list. @@ -109,7 +110,6 @@ export default function TicketScanningPage() { const selectedEvent = useMemo(() => allEvents.find(ev => ev.id === selectedEventId) || null, [allEvents, selectedEventId]); const eventSessions = useMemo(() => selectedEvent?.scheduleType === "sessions" ? activeSessions(selectedEvent.sessions) : [], [selectedEvent]); - useEffect(() => { setSelectedSessionId("auto"); }, [selectedEventId]); const sessionParam = selectedEventId !== "all" && selectedSessionId !== "auto" ? selectedSessionId : null; useEffect(() => { @@ -133,13 +133,16 @@ export default function TicketScanningPage() { }, [selectedEventId, token]); // In offline mode the event and section are fixed to the locked scope. - useEffect(() => { + // An offline lock fixes the event and section this device scans for. + useStateSync(() => { if (!offline.lock) return; setSelectedEventId(offline.lock.eventId); + setSelectedSessionId("auto"); }, [offline.lock]); - useEffect(() => { - if (!offline.lock) return; - setSelectedSectionId(offline.lock.sectionId || "all"); + // Again when the sections load (the picker needs the locked one in its list). + useStateSync(() => { + void sections; + if (offline.lock) setSelectedSectionId(offline.lock.sectionId || "all"); }, [offline.lock, sections]); // Bug fix: stop the scanner when the event or section filter changes so stale scan @@ -377,7 +380,7 @@ export default function TicketScanningPage() { className="w-full sm:w-72" events={pickerEvents} value={selectedEventId === "all" ? "" : selectedEventId} - onChange={id => setSelectedEventId(id || "all")} + onChange={id => { setSelectedEventId(id || "all"); setSelectedSessionId("auto"); }} emptyLabel="All events" graceHours={12} disabled={!!offline.lock} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx index 8eebc2d..3cb4f0a 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/allocations/page.tsx @@ -12,6 +12,7 @@ import type { Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null }; type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] }; @@ -115,7 +116,7 @@ export default function AllocationsPage() { setError(errorMessage(e) || "Failed to load allocations"); } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const current = board?.sets.find(s => s.id === setId) || null; const groupOf = useMemo(() => new Map((current?.assignments || []).map(a => [a.attendeeId, a.groupId])), [current]); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx index 5e4b3ba..1dea102 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -21,6 +21,7 @@ import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRe import { EventPicker } from "@/components/shared/EventPicker"; import { AttendeeFormModal, formsStillNeeded } from "@/components/shared/AttendeeFormModal"; import { apiV2, apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" }; @@ -1103,7 +1104,7 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo, onF }, [token, eventId]); // Again when the registration changes: its tickets may have just been issued. - useEffect(() => { load(); }, [load, registration]); + useExternalEffect(() => { void registration; load(); }, [load, registration]); if (!registration) { return ( @@ -1572,7 +1573,8 @@ function SendTicketsModal({ open, onClose, token, registration }: { const [localError, setLocalError] = useDismissingState(""); const [localInfo, setLocalInfo] = useState(""); - useEffect(() => { + // Each time it opens: start from the registration's details. + useStateSync(() => { if (open && registration) { setPhone(registration.user?.phoneNumber || ""); setEmail(registration.user?.email?.endsWith("@guest.local") ? "" : registration.user?.email || ""); @@ -1706,7 +1708,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded const [saving, setSaving] = useState(false); const [localError, setLocalError] = useDismissingState(""); - useEffect(() => { + useStateSync(() => { if (open) { setAmount(""); setReason(""); setLocalError(""); } }, [open, setLocalError]); @@ -1842,7 +1844,7 @@ function DoorRefundPanel({ token, eventId, setInfo }: { } }, [token, eventId]); - useEffect(() => { + useExternalEffect(() => { load(); }, [load]); @@ -2004,7 +2006,7 @@ function NewAttendeeModal({ open, onClose, seed, onConfirm }: { const [err, setErr] = useState(""); // Pre-fill name from whatever was typed in search - useEffect(() => { + useStateSync(() => { if (open) { setName(seed || ""); setEmail(""); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx index 03c4450..efa2bef 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/attendance/page.tsx @@ -12,6 +12,7 @@ import type { AttendanceRegister, AttendanceRow, Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; +import { useExternalEffect, useNow } from "@/lib/hooks"; type Filter = "all" | "completed" | "not_completed" | "missed_recent"; @@ -65,12 +66,13 @@ function AttendancePageInner() { setBusy(false); } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const columns = useMemo(() => (reg?.columns || []).filter(c => showCancelled || !c.cancelled), [reg, showCancelled]); const multi = reg?.event.scheduleType === "sessions"; // Sessions already held (for "missed the last two"). - const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < Date.now()).map(c => c.id), [reg]); + const now = useNow(); + const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < now).map(c => c.id), [reg, now]); const rows = useMemo(() => { const q = query.trim().toLowerCase(); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx index ff74667..79ca028 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/bundles/page.tsx @@ -11,6 +11,7 @@ import { BackLink } from "@/components/shared/BackLink"; import type { BundleGroupPricing, BundleKind, EventBundle } from "@/types"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] }; type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] }; @@ -108,7 +109,7 @@ export default function BundlesPage() { }, [token, canView, setError]); // Start on the next upcoming event (or the latest one). - useEffect(() => { + useStateSync(() => { if (!allEvents.some(e => e.id === eventId)) setEventId(defaultEventId(allEvents)); }, [allEvents, eventId]); @@ -127,7 +128,7 @@ export default function BundlesPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const toggleActive = async (b: EventBundle) => { try { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx index 426bfe2..57d17dd 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/consent/page.tsx @@ -13,6 +13,7 @@ import type { Event, ConsentRow, MedicalRow } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const STATUS_STYLE: Record = { @@ -70,7 +71,7 @@ export default function ConsentTrackerPage() { } }, [token, eventId, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const rows = useMemo(() => { const all = data?.rows || []; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx index 84babee..721dbc7 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/coupons/page.tsx @@ -9,6 +9,7 @@ import { TicketPercent, Plus, X, Search, Pencil, Power, Users, CalendarClock, Li import { errorMessage } from "@/lib/utils"; import { BackLink } from "@/components/shared/BackLink"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type CouponType = "percent" | "fixed" | "comp"; type Role = "user" | "staff" | "supervisor" | "admin"; @@ -176,7 +177,7 @@ export default function CouponsPage() { } }, [token, setError]); - useEffect(() => { if (token && canView) load(); }, [token, canView, load]); + useExternalEffect(() => { if (token && canView) load(); }, [token, canView, load]); // Codes that can still be used first; off, expired and used-up ones only when asked for. const visible = useMemo(() => { @@ -422,7 +423,10 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [userQuery, setUserQuery] = useState(""); - const [userResults, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); + const [foundUsers, setUserResults] = useState<{ id: string; name: string; email: string }[]>([]); + const searchingUsers = d.restrictTo === "users" && userQuery.trim().length >= 2; + // Only while there's a search (a shorter query clears the list without another render). + const userResults = searchingUsers ? foundUsers : []; const [eventQuery, setEventQuery] = useState(""); const [showPast, setShowPast] = useState(false); const set = (key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value })); @@ -443,7 +447,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { const scopedEvents = useMemo(() => events.filter(e => d.eventIds.includes(e.id)), [events, d.eventIds]); useEffect(() => { - if (d.restrictTo !== "users" || userQuery.trim().length < 2) { setUserResults([]); return; } + if (!searchingUsers) return; const t = setTimeout(async () => { try { const res = await (apiV2Data("get", "/users", { query: { search: userQuery.trim(), limit: "8" }, authToken: token }) as Promise<{ data: { id: string; name: string; email: string }[] }>); @@ -451,7 +455,7 @@ function CouponModal({ token, events, couponId, initial, onClose, onSaved }: { } catch { setUserResults([]); } }, 300); return () => clearTimeout(t); - }, [userQuery, d.restrictTo, token]); + }, [userQuery, searchingUsers, token]); const toggleEvent = (id: string) => { const eventIds = d.eventIds.includes(id) ? d.eventIds.filter(x => x !== id) : [...d.eventIds, id]; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx index 1c3bda0..3499e21 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/email-attendees/page.tsx @@ -16,6 +16,7 @@ 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'; @@ -211,10 +212,12 @@ function EmailAttendeesPageInner() { }, [token, setError]); // Reload when the signed-in user changes too (e.g. after an impersonation switch). - useEffect(() => { loadEvents(); }, [user, loadEvents]); + useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]); + const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]); + const [loadingUsers, setLoadingUsers] = useState(false); // Load users for broadcasts - useEffect(() => { + useExternalEffect(() => { const run = async () => { try { if (!token) return; @@ -236,7 +239,7 @@ function EmailAttendeesPageInner() { // Form state const [eventId, setEventId] = useState(preselectEventId); - useEffect(() => { + useStateSync(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]); @@ -245,8 +248,6 @@ function EmailAttendeesPageInner() { const [showInfo, setShowInfo] = useState(false); // Broadcasts state - const [users, setUsers] = useState<{id:string;name:string;email:string;pref:string}[]>([]); - const [loadingUsers, setLoadingUsers] = useState(false); const [selectedUserIds, setSelectedUserIds] = useState([]); const [broadcastEventId, setBroadcastEventId] = useState(""); const [broadcastSubject, setBroadcastSubject] = useState(""); @@ -291,7 +292,7 @@ function EmailAttendeesPageInner() { } }, [token]); - useEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]); + useExternalEffect(() => { if (tab === 'scheduled') loadScheduled(); }, [tab, loadScheduled]); const openEdit = (job: ScheduledJob) => { setEditing(job); @@ -353,7 +354,8 @@ function EmailAttendeesPageInner() { // Event helper to prefill templates const currentEvent = useMemo(() => (events || []).find(e => e.id === eventId), [events, eventId]); - useEffect(() => { + // A template fills in the subject and message, unless they were typed over. + useStateSync(() => { const title = currentEvent?.title || 'the event'; if (templateKey === 'payment_reminder') { if (!subjectDirty) setSubject(`Payment reminder: ${title}`); @@ -1025,7 +1027,7 @@ With gratitude`); const [promoEventId, setPromoEventId] = React.useState(''); // Compute defaults when event changes or finalHours change - React.useEffect(() => { + useStateSync(() => { if (!currentEvent) { setPreWhen(''); setFinalWhen(''); setThanksWhen(''); setPromoWhen(''); return; } try { const start = new Date(currentEvent.startDate); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx index 90ada17..af514e7 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/event-options/page.tsx @@ -11,6 +11,7 @@ import type { Event, EventOption } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { createTicketOption, updateTicketOption, deleteTicketOption } from "@/lib/eventSetup"; +import { useExternalEffect } from "@/lib/hooks"; // Format a Date (or date-like input) to the value expected by // This returns local time (browser timezone) as YYYY-MM-DDTHH:mm @@ -34,14 +35,17 @@ function EarlyBirdTiersEditor({ option, onSave }: { option: EventOption; onSave: const [open, setOpen] = React.useState(false); const [saving, setSaving] = React.useState(false); - React.useEffect(() => { + // Start the rows again whenever another option (or a fresh copy of its tiers) comes in — set + // while rendering, React's way to reset state from a prop without an effect. + const [rowsFrom, setRowsFrom] = React.useState(undefined); + if (rowsFrom !== option?.earlyBirdTiers) { + setRowsFrom(option?.earlyBirdTiers); const tiers = Array.isArray(option?.earlyBirdTiers) ? option.earlyBirdTiers : []; - const normalized = tiers + setRows(tiers .slice() .sort((a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime() || (a.order || 0) - (b.order || 0)) - .map((t, i) => ({ id: t.id, deadline: toLocalDateTimeInputValue(t.deadline), price: String(t.price ?? ''), order: typeof t.order === 'number' ? t.order : i })); - setRows(normalized); - }, [option?.id, option?.earlyBirdTiers]); + .map((t, i) => ({ id: t.id, deadline: toLocalDateTimeInputValue(t.deadline), price: String(t.price ?? ''), order: typeof t.order === 'number' ? t.order : i }))); + } const addRow = () => { setRows((r) => [...r, { deadline: '', price: '', order: (r.length || 0) }]); @@ -120,7 +124,10 @@ function EventOptionsContent() { const [events, setEvents] = useState([]); const [selectedEventId, setSelectedEventId] = useState(""); - const [options, setOptions] = useState([]); + const options = useMemo(() => { + const ev = events.find(e => e.id === selectedEventId); + return ev ? ev.options || ev.eventOptions || [] : []; + }, [selectedEventId, events]); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); @@ -134,24 +141,16 @@ function EventOptionsContent() { } }, [token]); - useEffect(() => { loadEvents(); }, [loadEvents]); + useExternalEffect(() => { loadEvents(); }, [loadEvents]); // Preselect event from query (?eventId=) - useEffect(() => { + useExternalEffect(() => { const q = search?.get("eventId"); if (!q) return; // if events already loaded, ensure it exists then set; otherwise, set directly and let options hook handle setSelectedEventId(q); }, [search]); - useEffect(() => { - const ev = events.find(e => e.id === selectedEventId); - if (ev) { - setOptions(ev.options || ev.eventOptions || []); - } else { - setOptions([]); - } - }, [selectedEventId, events]); const [newOpt, setNewOpt] = useState({ name: "", price: "", isMainTicket: false }); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx index bbd5222..1094701 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx @@ -26,6 +26,7 @@ import { AiEventDraft, type AiEventDraftFields } from "@/components/events/AiEve import { AiImprove } from "@/components/shared/AiImprove"; import { apiV2, apiV2Data } from "@/lib/apiV2"; import { createTicketOption, updateTicketOption, listSections, createSection, updateSection, deleteSection, listAttachments, uploadAttachment, deleteAttachment, uploadImage } from "@/lib/eventSetup"; +import { useExternalEffect, useStateSync, useNow } from "@/lib/hooks"; // ─── helpers ──────────────────────────────────────────────────────────────── @@ -513,7 +514,7 @@ function SectionsManager({ eventId }: { eventId: string }) { setEventOptions(evFull?.eventOptions || []); } catch {} finally { setLoading(false); } }, [eventId, token]); - useEffect(() => { if (eventId) load(); }, [eventId, load]); + useExternalEffect(() => { if (eventId) load(); }, [eventId, load]); const create = async () => { if (!newName.trim() || !token) return; @@ -597,7 +598,7 @@ function AttachmentsManager({ eventId }: { eventId: string }) { const load = useCallback(async () => { setItems(await listAttachments(eventId)); }, [eventId]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const upload: React.ChangeEventHandler = async e => { const file = e.target.files?.[0]; @@ -652,8 +653,9 @@ type NotifyUser = { id: string; name: string; email: string }; function useAnchorRect(anchorRef: React.RefObject, active: boolean) { const [rect, setRect] = useState<{ top: number; left: number; width: number; bottom: number } | null>(null); + // Measured before paint (useLayoutEffect), so the dropdown never shows in the wrong place. useLayoutEffect(() => { - if (!active) { setRect(null); return; } + if (!active) return; const update = () => { const el = anchorRef.current; if (!el) return; @@ -669,7 +671,7 @@ function useAnchorRect(anchorRef: React.RefObject, active: b }; }, [anchorRef, active]); - return rect; + return active ? rect : null; } /** Presentational picker — pure controlled component, no API persistence of its own. @@ -681,15 +683,16 @@ function NotifyRecipientsPicker({ selected, onChange, disabled }: { selected: No const [searching, setSearching] = useState(false); const anchorRef = useRef(null); - const visibleResults = results.filter(u => !selected.some(s => s.id === u.id)); + // Only while there's a search (clearing the box clears the list without another render). + const visibleResults = (search.trim() ? results : []).filter(u => !selected.some(s => s.id === u.id)); const dropdownOpen = visibleResults.length > 0; const rect = useAnchorRect(anchorRef, dropdownOpen); useEffect(() => { - if (!search.trim()) { setResults([]); return; } + if (!search.trim()) return; let cancelled = false; - setSearching(true); const t = setTimeout(async () => { + setSearching(true); try { const res = await (apiV2Data("get", "/users", { query: { search: search.trim(), limit: "10" }, authToken: token }) as Promise>); if (!cancelled) setResults(Array.isArray(res?.data) ? res.data : []); @@ -947,15 +950,17 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP // A campus-scoped person's new event starts at their (first) campus — they can't make // events for all campuses — with that campus's default location if the field is still default. - useEffect(() => { - if (mode !== "create" || !campusInfo.scoped || !campusInfo.campuses.length) return; + // (Keyed on the first campus's id: the campus list is a new array each render.) + const firstCampusId = campusInfo.scoped ? campusInfo.campuses[0]?.id : undefined; + const firstCampusLocation = campusInfo.scoped ? campusInfo.campuses[0]?.defaultLocation : undefined; + useStateSync(() => { + if (mode !== "create" || !firstCampusId) return; setDraft(d => { if (d.campusId) return d; - const first = campusInfo.campuses[0]; const isDefault = !d.location.trim() || d.location === (settings.org_address || ""); - return { ...d, campusId: first.id, ...(first.defaultLocation && isDefault ? { location: first.defaultLocation } : {}) }; + return { ...d, campusId: firstCampusId, ...(firstCampusLocation && isDefault ? { location: firstCampusLocation } : {}) }; }); - }, [mode, campusInfo.scoped, campusInfo.campuses, settings.org_address]); + }, [mode, firstCampusId, firstCampusLocation, settings.org_address]); // Series to choose from (Basic Details). const [seriesList, setSeriesList] = useState([]); @@ -1174,7 +1179,7 @@ function EventModal({ mode, event: ev, source, onClose, onSuccess }: EventModalP // user directly edits that option's price — then it becomes independent). A copy keeps its // own option prices. ── const [mainPriceTouched, setMainPriceTouched] = useState(cloning); - useEffect(() => { + useStateSync(() => { if (mode !== "create" || mainPriceTouched) return; setOptions(prev => { if (prev.length === 0 || prev[0].price === draft.price) return prev; @@ -2064,7 +2069,7 @@ export default function ManageEventsPage() { }, [token, setError]); // Reload when the signed-in user changes too (e.g. after an impersonation switch). - useEffect(() => { loadEvents(); }, [user, loadEvents]); + useExternalEffect(() => { void user; loadEvents(); }, [user, loadEvents]); const [modalMode, setModalMode] = useState<"create" | "edit" | null>(null); const [editingEvent, setEditingEvent] = useState(null); @@ -2074,7 +2079,7 @@ export default function ManageEventsPage() { const [search, setSearch] = useState(""); const [campus, setCampus] = useState(""); const isAdmin = user?.role === "admin"; - const now = Date.now(); + const now = useNow(); const filtered = useMemo(() => events.filter(ev => { if (!showInactive && ev.isActive === false) return false; @@ -2109,7 +2114,7 @@ export default function ManageEventsPage() { // Deep links (the Ctrl+K palette): ?edit= opens that event, ?new=1 a new one. const deepLinked = useRef(false); - useEffect(() => { + useExternalEffect(() => { if (deepLinked.current || !token) return; deepLinked.current = true; const params = new URLSearchParams(window.location.search); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx index b5e169d..2f7cd2f 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/forms/page.tsx @@ -12,6 +12,7 @@ import type { Event, EventForm, FormResponse, Registration, User } from "@/types import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2, apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync, useNow } from "@/lib/hooks"; type FormFieldType = 'yes_no' | 'text' | 'date' | 'numeric' | 'statement' | 'paragraph' | 'rating' | 'multiple_choice'; @@ -176,7 +177,7 @@ export default function FormsBrowserPage() { setAllEvents(Array.isArray(sorted) ? sorted : []); } catch {} }, [token]); - useEffect(() => { loadEvents(); }, [loadEvents]); + useExternalEffect(() => { loadEvents(); }, [loadEvents]); useEffect(() => { if (!token) return; @@ -199,8 +200,8 @@ export default function FormsBrowserPage() { const isAdmin = user?.role === "admin"; + const now = useNow(); const events = useMemo(() => { - const now = Date.now(); return allEvents.filter(ev => { if (!evIncludeInactive && ev.isActive === false) return false; if (!evIncludePast) { @@ -209,7 +210,7 @@ export default function FormsBrowserPage() { } return true; }); - }, [allEvents, evIncludePast, evIncludeInactive]); + }, [allEvents, evIncludePast, evIncludeInactive, now]); const search = async (append = false) => { if (!token) return; @@ -317,7 +318,7 @@ export default function FormsBrowserPage() { } }, [setError]); - useEffect(() => { + useExternalEffect(() => { if (mode === 'manage' && selectedEventId && selectedEventId !== formLoadedFor) { loadFormForEvent(selectedEventId); } @@ -359,11 +360,11 @@ export default function FormsBrowserPage() { } }, [token]); - useEffect(() => { + useStateSync(() => { if (mode === 'fill') setFillEventId(prev => prev || selectedEventId || ""); }, [mode, selectedEventId]); - useEffect(() => { + useExternalEffect(() => { if (mode !== 'fill') return; if (fillEventId) loadRegsForEvent(fillEventId); setFillRegistrationId(""); setFillRegistration(null); setExistingResponses([]); setFillForm({ isRequired: false, fields: [] }); @@ -393,7 +394,8 @@ export default function FormsBrowserPage() { }, [fillRegistration]); const [editableResponses, setEditableResponses] = useState<{ answers: Record }[]>([]); - useEffect(() => { + // One editable set of answers per main ticket, started from what was saved. + useStateSync(() => { if (mode !== 'fill') return; const fields = (fillForm.fields || []).filter(f => f.type !== 'statement' && f.type !== 'paragraph'); const mapped: { answers: Record }[] = (existingResponses || []).map((r)=>{ diff --git a/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx index de626d7..30ab781 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx @@ -9,6 +9,7 @@ import { Baby, Plus, Trash2 } from "lucide-react"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type Room = { id: string; name: string; capacity: number | null; minAge: number | null; maxAge: number | null; ratio: number | null; order: number }; type Settings = { @@ -48,7 +49,7 @@ export default function KidsSetupPage() { setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" }); } }, [token, eventId, setMsg]); - useEffect(() => { setS(null); load(); }, [load]); + useExternalEffect(() => { setS(null); load(); }, [load]); const run = async (fn: () => Promise, ok: string) => { setBusy(true); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx index d9125d2..e778767 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx @@ -19,6 +19,7 @@ import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; import { AttendeeFormModal, type AttendeeFormDef } from "@/components/shared/AttendeeFormModal"; +import { useExternalEffect } from "@/lib/hooks"; // ─── Pricing helpers ───────────────────────────────────────────────────────── @@ -264,7 +265,7 @@ export default function ManualRegistrationPage() { })(); }, [token]); - useEffect(() => { + useExternalEffect(() => { const ev = events.find(e => e.id === selectedEventId); if (ev) { const opts = ev.options || ev.eventOptions || []; @@ -287,7 +288,7 @@ export default function ManualRegistrationPage() { // The events list doesn't carry bundle deals or places per session; the single-event // response does. const [fullEvent, setFullEvent] = useState(null); - useEffect(() => { + useExternalEffect(() => { if (!selectedEventId) { setBundles([]); setFullEvent(null); return; } let cancelled = false; fetchEvent(selectedEventId, { authToken: token || undefined }) @@ -298,7 +299,6 @@ export default function ManualRegistrationPage() { // "Pick sessions" options: the sessions chosen per quantity key. const [picks, setPicks] = useState>({}); - useEffect(() => { setPicks({}); }, [selectedEventId]); const pickOpt = (optionId: string) => { const o = (fullEvent?.eventOptions || []).find(x => x.id === optionId); return fullEvent && o && isPickOption(fullEvent, o) ? o : null; @@ -444,7 +444,7 @@ export default function ManualRegistrationPage() {
1) Choose event
- + { setSelectedEventId(id); setPicks({}); }} placeholder="Select an event" /> {selectedEventId && (
{(() => { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx index 179eea3..17e0e86 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/offline-scans/page.tsx @@ -11,6 +11,7 @@ import type { Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; type Lock = { id: string; sectionName: string | null; deviceName: string | null; user: { name: string }; lockedAt: string; snapshotAt: string | null; lastSyncAt: string | null }; type Report = { @@ -65,7 +66,7 @@ export default function OfflineScansPage() { setError(errorMessage(e) || "Failed to load offline scanning"); } }, [token, eventId, onlyOpen, setError]); - useEffect(() => { load(); }, [load]); + useExternalEffect(() => { load(); }, [load]); const forceRelease = async (l: Lock) => { try { diff --git a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx index e587d77..0d95bfd 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx @@ -19,6 +19,7 @@ import { CampusFilter, CampusScopeNote } from "@/components/shared/CampusFilter" import { TodayPanel } from "@/components/dashboard/TodayPanel"; import { CommandPaletteButton } from "@/components/shared/CommandPalette"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect } from "@/lib/hooks"; const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`; const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`; @@ -107,7 +108,7 @@ export default function SupervisorDashboardPage() { } }, [token, campus, setScanStats, setPaymentStats, setRecentScans, setOverview]); - useEffect(() => { + useExternalEffect(() => { if (!token) return; loadStats(); }, [token, loadStats]); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx index daf2b0a..1b1dfc7 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/payments/page.tsx @@ -15,6 +15,7 @@ import { useOnlinePayments } from "@/lib/onlinePayments"; import { WaitingForPayment } from "@/components/payments/WaitingForPayment"; import { EventPicker } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; +import { useExternalEffect, useStateSync } from "@/lib/hooks"; // A donation is never mutated once created — assigning it to a registration creates a separate // "leg" Payment row (isDonation:false, originalPaymentId -> the donation, amount > 0) instead. @@ -99,7 +100,7 @@ function UserSearchField({ allUsers, value, onChange, placeholder = "Search by n const ref = useRef(null); // Sync display name when value changes externally (e.g. pre-fill from metadata) - useEffect(() => { + useStateSync(() => { const u = allUsers.find(u => String(u.id) === String(value)); setQuery(u?.name || ""); }, [value, allUsers]); @@ -208,7 +209,7 @@ function PaymentsContent() { } }, [token, setError]); - useEffect(() => { loadPayments(); }, [loadPayments]); + useExternalEffect(() => { loadPayments(); }, [loadPayments]); // Registrations still owing (not paid or cancelled), for the dropdowns. GET /api/v2/registrations // embeds each registration's `payments`, so balances come from that in one pass. Refunds load @@ -230,10 +231,12 @@ function PaymentsContent() { } }, [token]); - useEffect(() => { loadRegistrations(); }, [loadRegistrations]); + useExternalEffect(() => { loadRegistrations(); }, [loadRegistrations]); + const [allUsers, setAllUsers] = useState([]); + const [loadingUsers, setLoadingUsers] = useState(false); // Load all users for Refund section - useEffect(() => { + useExternalEffect(() => { (async () => { if (!token) return; try { @@ -259,8 +262,6 @@ function PaymentsContent() { // Backdate field const [paidAtLocal, setPaidAtLocal] = useState(""); // Users for Refund section (load all users with supervisor rights) - const [allUsers, setAllUsers] = useState([]); - const [loadingUsers, setLoadingUsers] = useState(false); // New: user selection states for split dropdowns const [selectedUserId, setSelectedUserId] = useState(""); @@ -288,7 +289,7 @@ function PaymentsContent() { return outstandingRegs.filter((r) => (String(r.user?.id || r.userId) === String(linkUserId))); }, [outstandingRegs, linkUserId]); - useEffect(() => { + useStateSync(() => { if (!linkRegistrationId) return; const out = regOutstanding[linkRegistrationId]?.outstanding ?? 0; setLinkAmount(out > 0 ? out.toFixed(2) : ""); @@ -355,13 +356,13 @@ function PaymentsContent() { } }; - useEffect(() => { + useStateSync(() => { const regQ = search?.get("registrationId"); if (regQ) setRegistrationId(regQ); }, [search]); // If a registration is preselected via query, infer and set its user - useEffect(() => { + useStateSync(() => { if (!registrationId) return; const reg = registrations.find((r) => String(r.id) === String(registrationId)); const uid = reg?.user?.id || reg?.userId; @@ -381,7 +382,7 @@ function PaymentsContent() { })(); }, [token, eventsIncludeInactive]); - useEffect(() => { + useStateSync(() => { // Keep inputs sensible when toggling donation if (isDonation) { setRegistrationId(""); @@ -455,7 +456,7 @@ function PaymentsContent() { setTxLoading(false); } }, [token]); - useEffect(() => { loadUnreconciled(); }, [loadUnreconciled]); + useExternalEffect(() => { loadUnreconciled(); }, [loadUnreconciled]); // Inline reconcile form state per-row const [reconcileForm, setReconcileForm] = useState<{ txId: string | null; type: 'reg' | 'don' | null; userId: string; registrationId: string; eventId: string; submitting: boolean }>({ txId: null, type: null, userId: '', registrationId: '', eventId: '', submitting: false }); @@ -883,7 +884,7 @@ function RefundSection({ allUsers, onDone }: RefundSectionProps) { const [payments, setPayments] = useState([]); const [regs, setRegs] = useState([]); const [loadingUser, setLoadingUser] = useState(false); - useEffect(() => { + useExternalEffect(() => { setPayments([]); setRegs([]); if (!userId || !token) return; let cancelled = false; @@ -903,14 +904,15 @@ function RefundSection({ allUsers, onDone }: RefundSectionProps) { const paymentsForUser = useMemo(() => payments.filter(p => (p.amount || 0) > 0), [payments]); - useEffect(() => { - // Reset dependent fields on changes + useStateSync(() => { + // Another person or refund type: start the dependent fields again. + void userId; void target; setPaymentId(""); setRegistrationId(""); setAmount(""); }, [userId, target]); - useEffect(() => { + useStateSync(() => { // If a payment selected, default amount and refund method to that payment's own — // still editable, but staff shouldn't have to remember to change it manually. if (target === 'payment') { @@ -1175,8 +1177,6 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi const [sponsorshipsOnly, setSponsorshipsOnly] = useState(false); const [err, setErr] = useState(null); - useEffect(() => { setRegistrationId(""); setPaymentId(""); }, [userId]); - useEffect(() => { setPaymentId(""); }, [registrationId]); // Registrations for the selected user that can actually receive a donation: an outstanding // balance to apply it to, and an event that isn't closed. @@ -1247,8 +1247,9 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi // Default to "apply as much as needed" whenever a new donation is picked — the common // case needs no typing, but the field stays editable for a deliberate partial allocation. - useEffect(() => { + useStateSync(() => { setAmountStr(maxAllocatable > 0 ? maxAllocatable.toFixed(2) : ""); + // Only when another donation is picked, not as the amounts move. // eslint-disable-next-line react-hooks/exhaustive-deps }, [paymentId]); @@ -1282,13 +1283,13 @@ function DonationAssignSection({ payments, allUsers, registrations, regOutstandi {err &&
{err}
}
- + { setUserId(uid); setRegistrationId(""); setPaymentId(""); }} />