WIP 2.0.0: React Compiler lint rules back to errors; docs

- The 192 places the rules flagged are fixed and the rules are errors
  again (npx eslint src: nothing). lib/hooks.ts: useStateSync (state
  that follows other state, set while rendering), useExternalEffect
  (API loads and browser reads), useNow; lib/navigation.ts hardNavigate
  for full reloads after sign-out or identity switches; other pages use
  the router. Resets moved into the handlers that cause them.
- The banner shows and hides at its times on open pages.
- HANDOVER, roadmap, README, FEATURES, SETTINGS, CHANGELOG updated;
  2.0.0 section drafted in WHATS-NEW.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 17:45:25 +02:00
co-authored by Claude Opus 5.5
parent 3f59164ab2
commit abd2c36e97
102 changed files with 613 additions and 354 deletions
@@ -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 {
@@ -43,6 +43,8 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
if (!campus) notFound();
const events = await apiFetchListForPrerender<Event>(`/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)
@@ -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<string, string> = {
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 (
<div className="max-w-6xl mx-auto w-full p-6">
@@ -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<CashupMethod, string> = { 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 (
<div className="max-w-4xl mx-auto space-y-4">
@@ -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 }));
@@ -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<Event>(eventId, { authToken: token || undefined })
@@ -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<Msg>(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 (
<div className="max-w-4xl mx-auto w-full">
@@ -181,7 +181,7 @@ export default function DataRequestsPage() {
<div className="flex flex-wrap items-center gap-2 mb-4">
{(["open", "closed"] as const).map(v => (
<button key={v} onClick={() => setView(v)} aria-pressed={view === v} className={`px-3 py-1.5 rounded-lg text-sm font-medium ${view === v ? "bg-brand-600 text-white" : "bg-white border text-gray-700 hover:bg-gray-50"}`}>
<button key={v} onClick={() => { setView(v); setPage(1); }} aria-pressed={view === v} className={`px-3 py-1.5 rounded-lg text-sm font-medium ${view === v ? "bg-brand-600 text-white" : "bg-white border text-gray-700 hover:bg-gray-50"}`}>
{v === "open" ? `Open${openCount ? ` (${openCount})` : ""}` : "Closed"}
</button>
))}
@@ -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]);
@@ -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]);
@@ -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]);
@@ -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);
@@ -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]);
@@ -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);
@@ -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<string | null>(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) => {
@@ -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]);
@@ -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}
@@ -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]);
@@ -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("");
@@ -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();
@@ -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 {
@@ -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<ConsentRow["status"], { label: string; cls: string }> = {
@@ -70,7 +71,7 @@ export default function ConsentTrackerPage() {
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const rows = useMemo(() => {
const all = data?.rows || [];
@@ -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<string | null>(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 = <K extends keyof Draft>(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];
@@ -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<string>(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<string[]>([]);
const [broadcastEventId, setBroadcastEventId] = useState<string>("");
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<string>('');
// 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);
@@ -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 <input type="datetime-local">
// 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<unknown>(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<Event[]>([]);
const [selectedEventId, setSelectedEventId] = useState<string>("");
const [options, setOptions] = useState<EventOption[]>([]);
const options = useMemo<EventOption[]>(() => {
const ev = events.find(e => e.id === selectedEventId);
return ev ? ev.options || ev.eventOptions || [] : [];
}, [selectedEventId, events]);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(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 });
@@ -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<HTMLInputElement> = 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<HTMLElement | null>, 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<HTMLElement | null>, 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<HTMLDivElement>(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<Paginated<NotifyUser>>);
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<EventSeries[]>([]);
@@ -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<Event | null>(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=<eventId> 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);
@@ -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<string,string> }[]>([]);
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<string,string> }[] = (existingResponses || []).map((r)=>{
@@ -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<unknown>, ok: string) => {
setBusy(true);
@@ -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<Event | null>(null);
useEffect(() => {
useExternalEffect(() => {
if (!selectedEventId) { setBundles([]); setFullEvent(null); return; }
let cancelled = false;
fetchEvent<Event>(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<Record<string, string[]>>({});
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() {
<div className="grid md:grid-cols-2 gap-6">
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="text-lg font-semibold mb-3">1) Choose event</div>
<EventPicker className="w-full" events={events} value={selectedEventId} onChange={setSelectedEventId} placeholder="Select an event" />
<EventPicker className="w-full" events={events} value={selectedEventId} onChange={id => { setSelectedEventId(id); setPicks({}); }} placeholder="Select an event" />
{selectedEventId && (
<div className="mt-3 text-xs text-gray-600">
{(() => {
@@ -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 {
@@ -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]);
@@ -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<HTMLDivElement>(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<User[]>([]);
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<string>("");
// Users for Refund section (load all users with supervisor rights)
const [allUsers, setAllUsers] = useState<User[]>([]);
const [loadingUsers, setLoadingUsers] = useState(false);
// New: user selection states for split dropdowns
const [selectedUserId, setSelectedUserId] = useState<string>("");
@@ -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<Payment[]>([]);
const [regs, setRegs] = useState<Registration[]>([]);
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<string | null>(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 && <div className="p-2 mb-2 text-xs bg-red-50 text-red-700 border rounded">{err}</div>}
<div className="grid gap-2">
<label className="text-xs text-gray-600">1. User</label>
<UserSearchField allUsers={allUsers} value={userId} onChange={setUserId} />
<UserSearchField allUsers={allUsers} value={userId} onChange={uid => { setUserId(uid); setRegistrationId(""); setPaymentId(""); }} />
<label className="text-xs text-gray-600 mt-2">2. Registration</label>
<select
className="w-full max-w-full border rounded px-3 py-2 text-sm truncate"
value={registrationId}
onChange={e => setRegistrationId(e.target.value)}
onChange={e => { setRegistrationId(e.target.value); setPaymentId(""); }}
disabled={!userId}
>
<option value="">Select registration…</option>
@@ -11,6 +11,7 @@ import { CampusBadge } from "@/components/shared/CampusFilter";
import { SeasonPassesPanel } from "@/components/series/SeasonPassesPanel";
import type { EventSeries } from "@/types";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect, useNow } from "@/lib/hooks";
type Draft = { id?: string; name: string; slug: string; description: string; picture: string };
const blank: Draft = { name: "", slug: "", description: "", picture: "" };
@@ -62,6 +63,7 @@ export default function SeriesPage() {
const [list, setList] = useState<EventSeries[]>([]);
const [error, setError] = useState<string | null>(null);
const now = useNow();
const [notice, setNotice] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [saving, setSaving] = useState(false);
@@ -74,7 +76,7 @@ export default function SeriesPage() {
setError(errorMessage(e) || "Couldn't load the series");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const save = async () => {
if (!draft) return;
@@ -105,7 +107,6 @@ export default function SeriesPage() {
}
};
const now = Date.now();
return (
<div className="max-w-4xl mx-auto w-full p-6">
@@ -11,6 +11,7 @@ import { HandHeart } from "lucide-react";
import { hoursText, type HoursRow, type RosterEvent } from "@/lib/volunteers";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Settings = {
event: { id: string; title: string; volunteerOptionId: string | null };
@@ -56,9 +57,9 @@ export default function VolunteerRostersPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" });
}
}, [token, eventId, setMsg]);
useEffect(() => { loadSettings(); }, [loadSettings]);
useExternalEffect(() => { loadSettings(); }, [loadSettings]);
useEffect(() => {
useExternalEffect(() => {
if (!token || tab !== "hours") return;
setHours(null);
(apiV2Data("get", "/volunteering/hours", { query: { eventId: !hoursAll && eventId ? eventId : undefined }, authToken: token }) as Promise<HoursRow[]>)
@@ -14,6 +14,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 Entry = {
id: string;
@@ -80,7 +81,7 @@ export default function WaitlistPage() {
setBusy(false);
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
const act = async (id: string, action: "offer" | "move" | "remove", body: { direction?: "up" | "down" } = {}) => {
setBusy(true);
@@ -1,6 +1,6 @@
"use client";
import React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
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";
@@ -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";
// Attendee with preference info
type Attendee = { id: string; name: string; phone: string; pref: string };
@@ -222,7 +223,7 @@ function WAAutomationsPanel({ events, token, onInfo, onError }: { events: Event[
const [promoWhen, setPromoWhen] = React.useState<string>("");
const [promoEventId, setPromoEventId] = React.useState<string>("");
React.useEffect(() => {
useStateSync(() => {
if (!currentEvent) { setPreWhen(""); setFinalWhen(""); setThanksWhen(""); setPromoWhen(""); return; }
try {
const start = new Date(currentEvent.startDate);
@@ -394,13 +395,14 @@ function WhatsAppAttendeesPageInner() {
// ── Attendees tab ──────────────────────────────────────────────────────────
const [eventId, setEventId] = useState<string>(preselectEventId);
useEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
useExternalEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<TemplateKey>("custom");
const [messageKind, setMessageKind] = useState<MessageKind>("update");
const [message, setMessage] = useState("");
// Set once the supervisor edits the message, so picking a template doesn't overwrite it.
// A ref, not state: it only gates the template effect below and is never rendered.
const messageDirtyRef = useRef(false);
// Typed over (or drafted with AI): a template no longer replaces it.
const [messageDirty, setMessageDirty] = useState(false);
const [status, setStatus] = useState<StatusFilter>("any");
const [groupId, setGroupId] = useState("");
const [attendees, setAttendees] = useState<Attendee[]>([]);
@@ -414,16 +416,16 @@ function WhatsAppAttendeesPageInner() {
const currentEvent = useMemo(() => (events || []).find((e) => e.id === eventId), [events, eventId]);
useEffect(() => {
useStateSync(() => {
const title = currentEvent?.title || "the event";
if (templateKey === "payment_reminder") {
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
if (!messageDirty) setMessage(`Hi {{name}}\n\nFriendly reminder: you have an outstanding balance for ${title}.\n\nPlease settle your balance to secure your tickets. Thank you!`);
} else if (templateKey === "event_reminder") {
if (!messageDirtyRef.current) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
if (!messageDirty) setMessage(`Hi {{name}}\n\nA quick reminder about ${title}.\nStart: {{event.start}}\n\nWe look forward to seeing you!`);
} else if (templateKey === "tickets") {
messageDirtyRef.current = false; setMessage("");
setMessageDirty(false); setMessage("");
}
}, [templateKey, currentEvent]);
}, [templateKey, currentEvent, messageDirty]);
useEffect(() => {
const run = async () => {
@@ -473,7 +475,7 @@ function WhatsAppAttendeesPageInner() {
};
const resetAttendeesForm = () => {
setTemplateKey("custom"); setMessageKind("update"); setMessage(""); messageDirtyRef.current = false;
setTemplateKey("custom"); setMessageKind("update"); setMessage(""); setMessageDirty(false);
setStatus("any"); setScheduledAtLocal(""); setPreviewCount(null); setPreviewSample(null);
setSelectedAttendeeIds(attendees.map((a) => a.id));
};
@@ -562,7 +564,7 @@ function WhatsAppAttendeesPageInner() {
} catch { } finally { setLoadingScheduled(false); }
}, [token]);
useEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]);
useExternalEffect(() => { if (tab === "scheduled") loadScheduled(); }, [tab, loadScheduled]);
const saveEdit = async () => {
if (!editing) return;
@@ -719,13 +721,13 @@ function WhatsAppAttendeesPageInner() {
{templateKey !== "tickets" ? (
<div>
<div className="mb-2">
<AiDraftMessage channel="whatsapp" eventId={eventId || undefined} onUse={d => { setMessage(d.body); messageDirtyRef.current = true; }} />
<AiDraftMessage channel="whatsapp" eventId={eventId || undefined} onUse={d => { setMessage(d.body); setMessageDirty(true); }} />
</div>
<label className="block text-xs text-gray-600 mb-1">Message</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={8} value={message}
onChange={(e) => { setMessage(e.target.value); messageDirtyRef.current = true; }}
onChange={(e) => { setMessage(e.target.value); setMessageDirty(true); }}
placeholder="Write your WhatsApp message to attendees..." />
<AiImprove text={message} onChange={t => { setMessage(t); messageDirtyRef.current = true; }} where="message" />
<AiImprove text={message} onChange={t => { setMessage(t); setMessageDirty(true); }} where="message" />
</div>
) : (
<div className="p-3 border rounded bg-gray-50 text-sm text-gray-700">
@@ -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 { QrImage } from "@/components/shared/QrImage";
import { ChildForm, type ChildInput } from "@/components/kids/ChildForm";
import { FAMILY_QR_PREFIX, type KidsAdult, type KidsChild, type KidsFamily } from "@/lib/kids";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type ActiveCode = { code: string; qr: string; event: { id: string; title: string }; children: { name: string; room: string | null; checkedInAt: string }[] };
type Mine = { family: KidsFamily | null; qrToken: string | null; codes: ActiveCode[]; pages: { id: string; message: string; createdAt: string }[] };
@@ -37,7 +38,7 @@ export default function MyKidsPage() {
}
}, [token, setMsg]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// Codes and pages change while children are checked in.
useVisiblePolling(() => { if (data?.codes.length) load(); }, 15000, !!token);
@@ -22,6 +22,7 @@ import { MyCertificates } from "@/components/events/MyCertificates";
import { isPickOption } from "@/lib/sessions";
import type { Event, EventOption, Payment, Registration, RegistrationOption, Ticket as TicketRecord } from "@/types";
import { ModalOverlay } from "@/components/shared/ModalOverlay";
import { useExternalEffect, useNow } from "@/lib/hooks";
// Helper formatters
const formatRand = (n: number) => `R ${n.toFixed(2)}`;
@@ -35,12 +36,13 @@ const isEventOver = (ev: EventStatusFields | null | undefined) =>
// Status badge for an event, shown wherever an event title is displayed on this page.
// Precedence when more than one applies: Closed > Past > Inactive.
function EventStatusBadge({ event }: { event: EventStatusFields | null | undefined }) {
const now = useNow();
if (!event) return null;
let label: string | null = null;
let className = '';
if (event.cashupStatus === 'closed') {
label = 'Closed'; className = 'bg-rose-50 text-rose-700';
} else if (event.endDate && new Date(event.endDate).getTime() < Date.now()) {
} else if (event.endDate && new Date(event.endDate).getTime() < now) {
label = 'Past'; className = 'bg-amber-50 text-amber-700';
} else if (event.isActive === false) {
label = 'Inactive'; className = 'bg-gray-100 text-gray-500';
@@ -369,7 +371,7 @@ export default function UserDashboardPage() {
const activeBill = activeRegId ? billing[activeRegId] : undefined;
// When a registration is opened, determine whether its event has attendee forms
useEffect(() => {
useExternalEffect(() => {
setActiveEventHasForm(null);
if (!activeRegId) return;
const ar = registrations.find(r => r.id === activeRegId);
@@ -10,6 +10,7 @@ import { errorMessage } from "@/lib/utils";
import type { Paginated } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
interface PaymentItem {
id: string;
@@ -98,7 +99,7 @@ export default function UserPaymentsPage() {
}, [token, buildQuery, setError]);
// loadPayments changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes.
useEffect(() => { if (token) loadPayments(1); }, [token, loadPayments]);
useExternalEffect(() => { if (token) loadPayments(1); }, [token, loadPayments]);
const goToPage = (p: number) => loadPayments(p);
@@ -1,6 +1,6 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import React, { useCallback, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { API_BASE } from "@/lib/api";
@@ -9,6 +9,7 @@ import { Megaphone, Download, PencilLine, Trash2, ListChecks, type LucideIcon }
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";
@@ -88,7 +89,7 @@ export default function PrivacyCentrePage() {
setLoadError(errorMessage(e) || "Could not load your privacy settings.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// ── News & announcements ──────────────────────────────────────────────────
const [newsMsg, setNewsMsg] = useDismissingState<Msg>(null);
@@ -12,6 +12,7 @@ import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { useCampuses } from "@/hooks/useCampuses";
import { apiV2, apiV2Data } from "@/lib/apiV2";
import { useStateSync } from "@/lib/hooks";
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
@@ -25,6 +26,25 @@ const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | nu
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
// Shared bits of the page (outside the component, so they aren't new components each render).
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
<div className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof User; title: string; tone?: "brand" | "amber" | "red" }) => {
const toneCls = tone === "amber" ? "bg-amber-50 text-amber-600" : tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600";
return (
<div className="flex items-center gap-2 mb-4">
<div className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${toneCls}`}>
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
</div>
);
};
export default function UserProfilePage() {
const { user, token, logout, updateToken } = useAuth();
const router = useRouter();
@@ -45,7 +65,7 @@ export default function UserProfilePage() {
const hasValidPhone = isValidZAPhone(phone);
useEffect(() => {
useStateSync(() => {
if (user) {
setName(user.name || "");
setEmail(user.email || "");
@@ -177,7 +197,7 @@ export default function UserProfilePage() {
// Admins and supervisors must keep 2FA on; they can only change the channel.
const tfRequired = !!user?.twoFactorRequired;
useEffect(() => {
useStateSync(() => {
if (user) {
setTfEnabled(!!user.twoFactorEnabled);
setTfMethod(user.twoFactorMethod || "email");
@@ -284,25 +304,9 @@ export default function UserProfilePage() {
};
// ── Shared helpers ────────────────────────────────────────────────────────
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
<div className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof User; title: string; tone?: "brand" | "amber" | "red" }) => {
const toneCls = tone === "amber" ? "bg-amber-50 text-amber-600" : tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600";
return (
<div className="flex items-center gap-2 mb-4">
<div className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${toneCls}`}>
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
</div>
);
};
return (
<div className="max-w-4xl mx-auto w-full">
@@ -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 { formatDate } from "@/lib/date";
@@ -9,6 +9,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { CheckCircle2, HandHeart, QrCode, Repeat } from "lucide-react";
import type { CoverRequest, MySlot, Roster, ServingEvent } from "@/lib/volunteers";
import { apiV2Data } from "@/lib/apiV2";
import { useExternalEffect } from "@/lib/hooks";
type Mine = { slots: MySlot[]; cover: CoverRequest[]; events: ServingEvent[] };
type Msg = { type: "ok" | "err"; text: string } | null;
@@ -32,9 +33,9 @@ export default function ServingPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load your shifts" });
}
}, [token, setMsg]);
useEffect(() => { load(); }, [load]);
useExternalEffect(() => { load(); }, [load]);
// ?event=<id>: the sign-up link a supervisor shares (works for hidden events too).
useEffect(() => {
useExternalEffect(() => {
const wanted = new URLSearchParams(window.location.search).get("event");
if (wanted) setOpenEvent(wanted);
}, []);
@@ -47,7 +48,7 @@ export default function ServingPage() {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the roles" });
}
}, [token, setMsg]);
useEffect(() => { loadRoster(openEvent); }, [openEvent, loadRoster]);
useExternalEffect(() => { loadRoster(openEvent); }, [openEvent, loadRoster]);
const call = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
+3 -1
View File
@@ -33,7 +33,9 @@ type Event = {
export default async function EventsPage() {
const events = await apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } });
const now = Date.now();
// 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 => {
if (e.cashupStatus === "closed") return false;
const t = new Date(e.endDate || e.startDate).getTime();
@@ -1,6 +1,6 @@
"use client";
import { Suspense, useEffect, useMemo, useState } from "react";
import { Suspense, useMemo, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
@@ -10,6 +10,7 @@ import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { ApiError } from "@/lib/api";
import { apiV2Data } from "@/lib/apiV2";
import { PrivacyNoticeSection, type PublicNotice } from "@/components/shared/PrivacyNoticeSection";
import { useExternalEffect } from "@/lib/hooks";
const fmtDate = (d: string) => new Date(d).toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric" });
@@ -26,7 +27,7 @@ function PrivacyNotice() {
const sectionIds = useMemo(() => (notice?.sections || []).map(s => s.id), [notice]);
const activeId = useScrollSpy(sectionIds);
useEffect(() => {
useExternalEffect(() => {
setNotice(null);
setError(null);
(apiV2Data("get", "/privacy/notice", { query: { version: versionParam || undefined } }) as Promise<PublicNotice>)
+3 -1
View File
@@ -52,7 +52,9 @@ export default async function HomePage() {
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
getOrgName(),
]);
const now = Date.now();
// 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 => {
const t = new Date(e.endDate || e.startDate).getTime();
return !isNaN(t) && t > now;
@@ -13,6 +13,8 @@ import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload,
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
import { analyticsSessionId } from "@/lib/analytics";
import { errorMessage } from "@/lib/utils";
import { useStateSync, useExternalEffect } from "@/lib/hooks";
import { useRouter } from "next/navigation";
// Tiered low-stock threshold — mirrors events/[id]/page.tsx
function lowStockThreshold(stockLimit: number): number {
@@ -381,6 +383,7 @@ function DonationPicker({
}
export default function RegisterForm({ event: baseEvent }: { event: RegisterEvent }) {
const router = useRouter();
const { token, user } = useAuth();
const online = useOnlinePayments();
const eventId = baseEvent.id;
@@ -390,18 +393,6 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
const [waitlistToken, setWaitlistToken] = useState<string | null>(null);
const [offer, setOffer] = useState<WaitlistOffer | null>(null);
const [offerError, setOfferError] = useState<string | null>(null);
useEffect(() => {
const t = new URLSearchParams(window.location.search).get("waitlist");
if (!t) return;
(apiV2Data("get", "/waitlist/claims/{token}", { params: { token: t } }) as Promise<WaitlistOffer & { status: string }>)
.then(res => {
if (res.status !== "offered") { setOfferError("This waitlist offer has expired."); return; }
setWaitlistToken(t);
setOffer(res);
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
})
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const event = useMemo<RegisterEvent>(() => {
const priced = withLatePrices(baseEvent);
if (!offer) return priced;
@@ -433,6 +424,19 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
});
return initial;
});
// A waitlist offer link (?waitlist=…): load the offer and book its places.
useExternalEffect(() => {
const t = new URLSearchParams(window.location.search).get("waitlist");
if (!t) return;
(apiV2Data("get", "/waitlist/claims/{token}", { params: { token: t } }) as Promise<WaitlistOffer & { status: string }>)
.then(res => {
if (res.status !== "offered") { setOfferError("This waitlist offer has expired."); return; }
setWaitlistToken(t);
setOffer(res);
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
})
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const [error, setError] = useState<string | null>(null);
const [creatingRegistration, setCreatingRegistration] = useState(false);
const [coupon, setCoupon] = useState<AppliedCoupon | null>(null);
@@ -474,7 +478,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
const choosing = choosesSessions(event);
const pickFor = (opt: EventOption) => isPickOption(event, opt);
// A waitlist offer for one session: that session is ticked for them.
useEffect(() => {
useStateSync(() => {
if (!offer?.sessionId) return;
const key = offer.variantId ? `${offer.eventOptionId}:${offer.variantId}` : offer.eventOptionId;
setPicks(p => ({ ...p, [key]: [offer.sessionId as string] }));
@@ -569,7 +573,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
setError(null);
setCreatingRegistration(true);
const res = await register({ waitlistToken });
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent(Math.max(0, res.balance).toFixed(2))}`;
router.push(`/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent(Math.max(0, res.balance).toFixed(2))}`);
} catch (e) {
setError(errorMessage(e) || "Registration failed");
} finally {
@@ -581,7 +585,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
if (isLoggedIn) {
if (!token) {
setError("Session expired — please log in again.");
window.location.href = `/login?redirect=/register/${eventId}`;
router.push(`/login?redirect=/register/${eventId}`);
return;
}
try {
@@ -613,7 +617,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
if (!showGuestForm) {
setError("Please log in to register for this event.");
window.location.href = `/login?redirect=/register/${eventId}`;
router.push(`/login?redirect=/register/${eventId}`);
return;
}
@@ -627,9 +631,9 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
{
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
if (hasForm) {
window.location.href = `/forms?registrationId=${encodeURIComponent(res.id)}`;
router.push(`/forms?registrationId=${encodeURIComponent(res.id)}`);
} else {
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`;
router.push(`/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`);
}
}
} catch (e) {
@@ -15,6 +15,7 @@ import { ModalOverlay } from "@/components/shared/ModalOverlay";
import { EventPicker } from "@/components/shared/EventPicker";
import { apiV2Data, apiV2 } from "@/lib/apiV2";
import { toAuthResponse } from "@/contexts/AuthContext";
import { useExternalEffect, useStateSync } from "@/lib/hooks";
// ─── Types ────────────────────────────────────────────────────────────────────
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
@@ -220,7 +221,7 @@ export default function SelfServicePage() {
// The events list doesn't carry bundle deals or places per session; the single-event
// response does.
const [kioskFull, setKioskFull] = useState<Event | null>(null);
useEffect(() => {
useExternalEffect(() => {
if (!selectedEventId) { setKioskBundles([]); setKioskFull(null); return; }
let cancelled = false;
fetchEvent<Event>(selectedEventId, { authToken: supervisorToken || undefined })
@@ -231,7 +232,6 @@ export default function SelfServicePage() {
// "Pick sessions" options: the sessions chosen per quantity key.
const [picks, setPicks] = useState<Record<string, string[]>>({});
useEffect(() => { setPicks({}); }, [selectedEventId]);
const pickOpt = (optionId: string) => {
const o = (kioskFull?.eventOptions || []).find(x => x.id === optionId);
return kioskFull && o && isPickOption(kioskFull, o) ? o : null;
@@ -417,6 +417,7 @@ export default function SelfServicePage() {
setShowChangeModal(false);
setScreen("setup");
setSelectedEventId("");
setPicks({});
resetForm();
} catch (err) {
setChangeError(errorMessage(err) || "Incorrect password.");
@@ -613,7 +614,6 @@ export default function SelfServicePage() {
setShowVisitorPassword(false);
setEmailMatch(null);
setPhoneMatch(null);
appliedMatchIdRef.current = null;
setShowUpdateConfirm(false);
setLookupMessage(null);
setFormError(null);
@@ -683,18 +683,19 @@ export default function SelfServicePage() {
// object identity instead of id made it re-fire and stomp every field — including
// ones the operator had already deliberately edited — back to the account's
// original values on every unrelated tap.
const appliedMatchIdRef = useRef<string | null>(null);
useEffect(() => {
if (!matchedAccount || appliedMatchIdRef.current === matchedAccount.id) return;
appliedMatchIdRef.current = matchedAccount.id;
// Fill the form in once per matched account (not again when the same account comes back as a
// new object, which would undo what the visitor typed). Starting over clears the match.
useStateSync(() => {
if (!matchedAccount) return;
setVisitorName(matchedAccount.name);
if (matchedAccount.email) setVisitorEmail(matchedAccount.email);
if (matchedAccount.phoneNumber) setVisitorPhone(matchedAccount.phoneNumber);
setNotificationPref(matchedAccount.notificationPreference);
}, [matchedAccount]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [matchedAccount?.id]);
// Existing accounts are linked automatically — never show the "create account" toggle for them
useEffect(() => {
useExternalEffect(() => {
if (accountExists && createAccount) {
setCreateAccount(false);
setVisitorPassword("");
@@ -854,7 +855,7 @@ export default function SelfServicePage() {
) : (
<div>
<label htmlFor="kiosk-event" className="block text-sm font-medium text-gray-700 mb-1">Event</label>
<EventPicker id="kiosk-event" className="w-full text-base" events={events} value={selectedEventId} onChange={setSelectedEventId} placeholder="Select an event" />
<EventPicker id="kiosk-event" className="w-full text-base" events={events} value={selectedEventId} onChange={id => { setSelectedEventId(id); setPicks({}); }} placeholder="Select an event" />
</div>
)}
{selectedEvent && (
@@ -48,6 +48,8 @@ export default async function SeriesPage({ params }: { params: Promise<{ slug: s
if (!series) notFound();
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?series=${encodeURIComponent(series.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)
@@ -17,6 +17,14 @@ const TYPE_LABELS: Record<BannerType, string> = {
danger: "Danger (red)",
};
function toLocalInput(iso: string) {
const d = new Date(iso);
if (isNaN(d.getTime())) return "";
// datetime-local wants "YYYY-MM-DDTHH:MM"
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())}`;
}
export default function SetBannerPage() {
const { user, token, loading } = useAuth();
const router = useRouter();
@@ -51,14 +59,6 @@ export default function SetBannerPage() {
.catch(() => {});
}, []);
function toLocalInput(iso: string) {
const d = new Date(iso);
if (isNaN(d.getTime())) return "";
// datetime-local wants "YYYY-MM-DDTHH:MM"
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 submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;