Merge branch 'main' into release/2.0 (1.52.0, 1.52.1)

# Conflicts:
#	CHANGELOG.md
#	docs/HANDOVER.md
This commit is contained in:
2026-11-02 13:45:28 +02:00
59 changed files with 38657 additions and 1121 deletions
@@ -80,6 +80,10 @@ const ACTION_LABELS: Record<string, string> = {
registrations_bulk: "Bulk action on registrations",
attendance_marked: "Attendance marked",
attendance_unmarked: "Attendance unmarked",
attendee_form_waived: "Attendee form left for later",
tickets_issued_override: "Tickets issued by an admin (correction)",
registration_complimentary: "Balance made complimentary",
checkin_corrected: "Check-in corrected after the fact",
certificate_issued: "Certificate issued",
certificate_revoked: "Certificate revoked",
event_sessions_changed: "Event sessions changed",
@@ -0,0 +1,408 @@
"use client";
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Wrench, AlertTriangle, CheckCircle2, Ticket, FileText } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { useDismissingState } from "@/hooks/useDismissingState";
import { fetchEvent, fetchManagedEvents } from "@/lib/api";
import { apiV2Data } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
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";
// GET /api/v2/corrections/events/{id} (services/corrections.ts)
type CorrectionTicket = {
id: string; qrCode: string; label: string; isMainTicket: boolean; name: string; quantity: number;
sessionIds: string[]; checkedIn: Record<string, number>;
};
type CorrectionRow = {
id: string; status: string; createdAt: string;
user: { id: string; name: string; email: string | null; phoneNumber: string | null };
totalDue: number; paid: number; balance: number; places: number; ticketPlaces: number;
missingTickets: boolean; formsNeeded: number; formWaived: boolean; ticketsReleased: boolean; complimentary: number;
tickets: CorrectionTicket[];
};
type CorrectionEvent = { id: string; title: string; startDate: string; endDate: string; closed: boolean; formRequired: boolean; sessions: { id: string; label: string; startsAt: string }[] };
type Filter = "attention" | "unpaid" | "not_checked_in" | "all";
const WHOLE_EVENT = "event";
const rand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const notCheckedIn = (r: CorrectionRow) => r.tickets.some(t => t.isMainTicket && t.sessionIds.some(s => (t.checkedIn[s] || 0) < t.quantity));
const needsAttention = (r: CorrectionRow) => r.missingTickets || r.formsNeeded > 0 || (r.balance > 0 && r.tickets.length === 0);
/** One registration: what's wrong with it, and the fixes. */
function RegistrationCard({ row, event, form, token, onChanged, onMessage }: {
row: CorrectionRow; event: CorrectionEvent; form: AttendeeFormDef; token: string;
onChanged: () => void; onMessage: (ok: boolean, text: string) => void;
}) {
const [action, setAction] = useState<"none" | "tickets" | "free">("none");
const [skipForm, setSkipForm] = useState(row.formsNeeded > 0);
const [send, setSend] = useState(false);
const [reason, setReason] = useState("");
const [busy, setBusy] = useState(false);
const [showForm, setShowForm] = useState(false);
const unpaid = row.status !== "paid" && !row.ticketsReleased;
const run = async () => {
setBusy(true);
try {
if (action === "free") {
const res = await (apiV2Data("post", "/corrections/registrations/{id}/complimentary", {
params: { id: row.id }, authToken: token, body: { skipForm, send, reason: reason || null },
}) as Promise<{ amount: number; ticketsIssued: number }>);
onMessage(true, `${row.user.name}: ${rand(res.amount)} made complimentary${res.ticketsIssued ? ` — ${res.ticketsIssued} ticket(s) issued` : ""}.`);
} else {
const res = await (apiV2Data("post", "/corrections/registrations/{id}/tickets", {
params: { id: row.id }, authToken: token, body: { skipForm, payLater: unpaid, send, reason: reason || null },
}) as Promise<{ ticketsIssued: number }>);
onMessage(true, `${row.user.name}: ${res.ticketsIssued ? `${res.ticketsIssued} ticket(s) issued` : "tickets are up to date"}${unpaid ? " — the balance is still owed" : ""}.`);
}
setAction("none");
setReason("");
onChanged();
} catch (e) {
onMessage(false, errorMessage(e) || "That didn't work.");
} finally {
setBusy(false);
}
};
const chips: { text: string; tone: string }[] = [];
if (row.missingTickets) chips.push({ text: `Missing tickets (${row.ticketPlaces} of ${row.places})`, tone: "bg-red-50 text-red-700" });
if (row.formsNeeded > 0) chips.push({ text: `${row.formsNeeded} form${row.formsNeeded === 1 ? "" : "s"} to fill in`, tone: "bg-amber-50 text-amber-700" });
if (row.balance > 0) chips.push({ text: `Owes ${rand(row.balance)}`, tone: "bg-orange-50 text-orange-700" });
if (row.formWaived) chips.push({ text: "Form left for later", tone: "bg-gray-100 text-gray-600" });
if (row.ticketsReleased) chips.push({ text: "Tickets issued before payment", tone: "bg-blue-50 text-blue-700" });
if (row.complimentary > 0) chips.push({ text: `Complimentary ${rand(row.complimentary)}`, tone: "bg-emerald-50 text-emerald-700" });
return (
<div className="border rounded-xl bg-white shadow-sm p-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<div className="font-semibold text-gray-900">{row.user.name || "Guest"}</div>
<div className="text-xs text-gray-500 break-all">{[row.user.email, row.user.phoneNumber].filter(Boolean).join(" · ") || "No contact details"}</div>
</div>
<div className="text-right text-xs text-gray-600">
<div><span className="font-medium capitalize">{row.status.replace("_", " ")}</span> · {rand(row.paid)} of {rand(row.totalDue)}</div>
<div className="text-gray-400">#{row.id.slice(0, 8)}</div>
</div>
</div>
{chips.length > 0 && (
<div className="flex flex-wrap gap-1.5 mt-2">
{chips.map(c => <span key={c.text} className={`text-[11px] px-2 py-0.5 rounded-full ${c.tone}`}>{c.text}</span>)}
</div>
)}
<div className="flex flex-wrap gap-2 mt-3">
{row.formsNeeded > 0 && (
<button type="button" onClick={() => setShowForm(true)} className="px-3 py-1.5 text-xs rounded border bg-white hover:bg-gray-50 inline-flex items-center gap-1">
<FileText className="w-3.5 h-3.5" /> Fill in form
</button>
)}
{(row.missingTickets || unpaid || row.formsNeeded > 0) && (
<button type="button" onClick={() => { setAction(action === "tickets" ? "none" : "tickets"); setSkipForm(row.formsNeeded > 0); }} className={`px-3 py-1.5 text-xs rounded border inline-flex items-center gap-1 ${action === "tickets" ? "bg-brand-600 text-white border-brand-600" : "bg-white hover:bg-gray-50"}`}>
<Ticket className="w-3.5 h-3.5" /> {unpaid ? "Issue tickets — pay later" : "Issue tickets"}
</button>
)}
{row.balance > 0 && !event.closed && (
<button type="button" onClick={() => { setAction(action === "free" ? "none" : "free"); setSkipForm(row.formsNeeded > 0); }} className={`px-3 py-1.5 text-xs rounded border ${action === "free" ? "bg-emerald-600 text-white border-emerald-600" : "bg-white hover:bg-gray-50"}`}>
Make it free ({rand(row.balance)})
</button>
)}
</div>
{action !== "none" && (
<div className="mt-3 border rounded-lg p-3 bg-gray-50 space-y-2 text-sm">
<p className="text-xs text-gray-600">
{action === "free"
? `${rand(row.balance)} is written off as a complimentary discount — income stays ${rand(row.paid)} — and the registration is marked paid.`
: unpaid
? `The tickets are issued now. ${rand(row.balance)} is still owed and shows as outstanding until it's paid.`
: "Issues the tickets this registration is missing."}
</p>
{row.formsNeeded > 0 && (
<label className="flex items-center gap-2 text-xs">
<input type="checkbox" checked={skipForm} onChange={e => setSkipForm(e.target.checked)} />
Leave the attendee form for later (otherwise the tickets wait for it)
</label>
)}
<label className="flex items-center gap-2 text-xs">
<input type="checkbox" checked={send} onChange={e => setSend(e.target.checked)} />
Send the tickets to {row.user.name || "the attendee"}
</label>
<label className="block text-xs">
<span className="text-gray-600">Reason (kept in the audit log)</span>
<input className="mt-1 w-full border rounded px-2 py-1.5 text-sm bg-white" value={reason} onChange={e => setReason(e.target.value)} placeholder={action === "free" ? "e.g. Speaker's spouse" : "e.g. Paid at the door, form on paper"} maxLength={500} />
</label>
<div className="flex gap-2">
<button type="button" disabled={busy} onClick={run} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white disabled:opacity-50">{busy ? "Working…" : action === "free" ? "Make it free" : "Issue tickets"}</button>
<button type="button" disabled={busy} onClick={() => setAction("none")} className="px-3 py-1.5 text-xs rounded border bg-white">Cancel</button>
</div>
</div>
)}
{row.tickets.length > 0 && (
<div className="mt-3 space-y-2">
{row.tickets.map(t => <TicketCheckIn key={t.id} ticket={t} event={event} token={token} onChanged={onChanged} onMessage={onMessage} />)}
</div>
)}
{showForm && (
<AttendeeFormModal
registrationId={row.id}
form={form}
needed={row.formsNeeded}
token={token}
attendeeName={row.user.name}
onDone={({ later, ticketsIssued }) => {
setShowForm(false);
onMessage(true, `${row.user.name}: ${later ? "form left for later" : "form saved"}${ticketsIssued ? ` — ${ticketsIssued} ticket(s) issued` : ""}.`);
onChanged();
}}
/>
)}
</div>
);
}
/** A ticket's check-ins per session, with check in / undo whatever the time. */
function TicketCheckIn({ ticket, event, token, onChanged, onMessage }: {
ticket: CorrectionTicket; event: CorrectionEvent; token: string;
onChanged: () => void; onMessage: (ok: boolean, text: string) => void;
}) {
const [busyKey, setBusyKey] = useState<string | null>(null);
const label = (key: string) => key === WHOLE_EVENT ? "Checked in" : (event.sessions.find(s => s.id === key)?.label || "Session");
const change = async (key: string, present: boolean) => {
setBusyKey(key);
try {
await apiV2Data("post", "/corrections/tickets/{id}/check-in", {
params: { id: ticket.id }, authToken: token,
body: { sessionId: key === WHOLE_EVENT ? null : key, present },
});
onMessage(true, `${ticket.name}: ${present ? "checked in" : "check-in undone"}${key === WHOLE_EVENT ? "" : ` for ${label(key)}`}.`);
onChanged();
} catch (e) {
onMessage(false, errorMessage(e) || "That didn't work.");
} finally {
setBusyKey(null);
}
};
return (
<div className="border rounded-lg px-3 py-2 text-xs">
<div className="flex flex-wrap justify-between gap-1">
<span className="font-medium text-gray-800">{ticket.label}{ticket.quantity > 1 ? ` ×${ticket.quantity}` : ""}</span>
<span className="text-gray-500">{ticket.name}</span>
</div>
<div className="mt-1.5 flex flex-wrap gap-2">
{ticket.sessionIds.map(key => {
const n = ticket.checkedIn[key] || 0;
const full = n >= ticket.quantity;
return (
<span key={key} className="inline-flex items-center gap-1.5 border rounded-full pl-2 pr-1 py-0.5">
{full ? <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600" /> : null}
<span className={full ? "text-emerald-700" : "text-gray-600"}>{label(key)}: {n}/{ticket.quantity}</span>
{!full && (
<button type="button" disabled={busyKey === key} onClick={() => change(key, true)} className="px-2 py-0.5 rounded-full bg-brand-600 text-white disabled:opacity-50">
Check in
</button>
)}
{n > 0 && (
<button type="button" disabled={busyKey === key} onClick={() => change(key, false)} className="px-2 py-0.5 rounded-full border bg-white disabled:opacity-50">
Undo
</button>
)}
</span>
);
})}
</div>
</div>
);
}
function CorrectionsContent() {
const { user, token, loading } = useAuth();
const router = useRouter();
const search = useSearchParams();
const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState(search.get("event") || "");
// Kept with the event they're for, so changing events never shows the last one's.
const [loaded, setLoaded] = useState<{ event: CorrectionEvent; registrations: CorrectionRow[] } | null>(null);
const [formOf, setFormOf] = useState<{ eventId: string; form: AttendeeFormDef } | null>(null);
const data = loaded && loaded.event.id === eventId ? loaded : null;
const form = formOf?.eventId === eventId ? formOf.form : null;
const [busy, setBusy] = useState(false);
const [filter, setFilter] = useState<Filter>("attention");
const [query, setQuery] = useState("");
const [sendMissing, setSendMissing] = useState(false);
const [message, setMessage] = useDismissingState<{ ok: boolean; text: string } | null>(null);
const isAdmin = user?.role === "admin";
useEffect(() => {
if (loading) return;
if (!user) router.replace("/login");
}, [user, loading, router]);
// Every event — past and closed ones too, newest first.
useEffect(() => {
if (!token || !isAdmin) return;
fetchManagedEvents<Event>(token, { past: true, inactive: true })
.then(evs => setEvents([...(evs || [])].sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())))
.catch(() => setEvents([]));
}, [token, isAdmin]);
const load = useCallback(async () => {
if (!token || !eventId) return;
try {
setLoaded(await (apiV2Data("get", "/corrections/events/{id}", { params: { id: eventId }, authToken: token }) as Promise<{ event: CorrectionEvent; registrations: CorrectionRow[] }>));
} catch (e) {
setMessage({ ok: false, text: errorMessage(e) || "Couldn't load the event." });
}
}, [token, eventId, setMessage]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
if (!eventId) return;
fetchEvent<Event>(eventId, { authToken: token || undefined })
.then(ev => setFormOf({ eventId, form: ev?.form }))
.catch(() => setFormOf({ eventId, form: null }));
}, [eventId, token]);
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return (data?.registrations || []).filter(r => {
if (filter === "attention" && !needsAttention(r)) return false;
if (filter === "unpaid" && !(r.balance > 0)) return false;
if (filter === "not_checked_in" && !notCheckedIn(r)) return false;
if (!q) return true;
return [r.user.name, r.user.email, r.user.phoneNumber, r.id].some(v => String(v || "").toLowerCase().includes(q));
});
}, [data, filter, query]);
const counts = useMemo(() => {
const regs = data?.registrations || [];
return {
attention: regs.filter(needsAttention).length,
unpaid: regs.filter(r => r.balance > 0).length,
not_checked_in: regs.filter(notCheckedIn).length,
all: regs.length,
missing: regs.filter(r => r.missingTickets).length,
};
}, [data]);
const issueMissing = async () => {
if (!token || !eventId) return;
setBusy(true);
try {
const res = await (apiV2Data("post", "/corrections/events/{id}/issue-missing", { params: { id: eventId }, authToken: token, body: { send: sendMissing } }) as Promise<{ registrations: number; tickets: number; failed: { name: string; message: string }[] }>);
setMessage({
ok: res.failed.length === 0,
text: `${res.tickets} ticket(s) issued for ${res.registrations} registration(s).${res.failed.length ? ` Not fixed: ${res.failed.map(f => `${f.name} (${f.message})`).join("; ")}` : ""}`,
});
await load();
} catch (e) {
setMessage({ ok: false, text: errorMessage(e) || "That didn't work." });
} finally {
setBusy(false);
}
};
const onMessage = useCallback((ok: boolean, text: string) => setMessage({ ok, text }), [setMessage]);
if (!loading && user && !isAdmin) {
return <div className="max-w-4xl mx-auto p-6"><div className="p-3 border rounded bg-yellow-50 text-sm">Corrections are for admins only.</div></div>;
}
const FILTERS: { key: Filter; label: string }[] = [
{ key: "attention", label: "Needs attention" },
{ key: "unpaid", label: "Owes money" },
{ key: "not_checked_in", label: "Not checked in" },
{ key: "all", label: "All" },
];
return (
<div className="max-w-4xl mx-auto w-full p-4 sm:p-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
<Wrench className="w-5 h-5 text-brand-600" />
</div>
<div>
<BackLink href="/dashboard/admin" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Corrections</h1>
</div>
</div>
<p className="text-sm text-gray-600 mb-4">
Put registrations right after the fact: issue tickets held back by an attendee form or still unpaid, make a balance free, and check people in after the event. Everything is kept in the audit log.
</p>
<EventPicker className="w-full sm:w-96 mb-4" events={events} value={eventId} onChange={id => { setEventId(id); setFilter("attention"); }} placeholder="Choose an event (past events too)" />
{message && (
<div role="status" className={`p-3 mb-3 border rounded text-sm ${message.ok ? "bg-emerald-50 text-emerald-800" : "bg-red-50 text-red-700"}`}>{message.text}</div>
)}
{data && (
<>
<div className="flex flex-wrap items-center gap-2 mb-3 text-xs">
{data.event.closed && <span className="px-2 py-0.5 rounded-full bg-gray-100 text-gray-700">Closed (cashed up) — money can&rsquo;t change; tickets and check-ins can</span>}
{data.event.formRequired && <span className="px-2 py-0.5 rounded-full bg-amber-50 text-amber-700">Required attendee form</span>}
{new Date(data.event.endDate) < new Date() && <span className="px-2 py-0.5 rounded-full bg-gray-100 text-gray-700">Event is over</span>}
</div>
{counts.missing > 0 && (
<div className="border border-red-200 bg-red-50 rounded-xl p-4 mb-4">
<div className="flex items-start gap-2 text-sm text-red-800">
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
<div>
<strong>{counts.missing} paid registration{counts.missing === 1 ? " is" : "s are"} missing tickets.</strong> Issue them all now — attendee forms still outstanding are left for later.
</div>
</div>
<div className="flex flex-wrap items-center gap-3 mt-3">
<button type="button" disabled={busy} onClick={issueMissing} className="px-3 py-1.5 text-sm rounded bg-red-600 text-white disabled:opacity-50">
{busy ? "Issuing…" : `Issue all missing tickets (${counts.missing})`}
</button>
<label className="flex items-center gap-2 text-xs text-red-900">
<input type="checkbox" checked={sendMissing} onChange={e => setSendMissing(e.target.checked)} />
Send them to the attendees
</label>
</div>
</div>
)}
<div className="flex flex-wrap gap-2 mb-3">
{FILTERS.map(f => (
<button key={f.key} type="button" onClick={() => setFilter(f.key)} className={`px-3 py-1.5 text-xs rounded-full border ${filter === f.key ? "bg-brand-600 text-white border-brand-600" : "bg-white hover:bg-gray-50"}`}>
{f.label} ({counts[f.key]})
</button>
))}
<input className="ml-auto border rounded px-3 py-1.5 text-sm w-full sm:w-56" placeholder="Search name, email, phone" value={query} onChange={e => setQuery(e.target.value)} aria-label="Search registrations" />
</div>
<div className="space-y-3">
{rows.map(r => (
<RegistrationCard key={r.id} row={r} event={data.event} form={form} token={token!} onChanged={load} onMessage={onMessage} />
))}
{rows.length === 0 && (
<div className="text-sm text-gray-500 border rounded-xl p-6 text-center bg-white">
{filter === "attention" ? "Nothing needs putting right at this event." : "No registrations match."}
</div>
)}
</div>
</>
)}
</div>
);
}
export default function CorrectionsPage() {
return (
<Suspense fallback={null}>
<CorrectionsContent />
</Suspense>
);
}
@@ -8,7 +8,7 @@ import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck, Inbox,
Baby, HandHeart, Layers,
Baby, HandHeart, Layers, Wrench,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -48,6 +48,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/admin/forms", label: "Attendee forms", description: "View submitted attendee forms", icon: FileText },
{ href: "/dashboard/supervisor/email-attendees", label: "Email attendees", description: "Send a message to attendees of an event", icon: Mail },
{ href: "/dashboard/supervisor/whatsapp-attendees", label: "WhatsApp attendees", description: "Send a WhatsApp message to event attendees", icon: MessageCircle },
{ href: "/dashboard/admin/corrections", label: "Corrections", description: "Missing tickets, free tickets, forms and late check-ins", icon: Wrench },
{ href: "/dashboard/admin/cashup", label: "Post-event Cashup", description: "Set costs, reconcile takings, and close out events", icon: Wallet },
{ href: "/dashboard/admin/audit-log", label: "Audit log", description: "Review refunds, manual registrations, event and settings changes", icon: History },
{ href: "/dashboard/admin/data-requests", label: "Data requests", description: "POPIA: people asking to correct or delete their information", icon: Inbox },
@@ -312,7 +312,7 @@ export default function KidsDeskPage() {
const r = await (apiV2Data("post", "/events/{id}/kids/check-out", {
params: { id: eventId },
authToken: token,
body: { code: lookup.code, checkInIds: ids, collectedBy, sessionId: sessionId || undefined },
body: { code: lookup.code ?? "", checkInIds: ids, collectedBy, sessionId: sessionId || undefined },
}) as Promise<{ checkedOut: { name: string }[] }>);
setMsg({ type: "ok", text: `Collected: ${r.checkedOut.map(c => c.name).join(", ")}.` });
setLookup(null);
@@ -19,6 +19,7 @@ import { bookableSessions, choosesSessions, isPickOption, todaysSession } from "
import { SessionPicker } from "@/components/events/SessionPicker";
import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRecord, UserSummary } from "@/types";
import { EventPicker } from "@/components/shared/EventPicker";
import { AttendeeFormModal, formsStillNeeded } from "@/components/shared/AttendeeFormModal";
import { apiV2, apiV2Data } from "@/lib/apiV2";
type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" };
@@ -198,12 +199,37 @@ export default function AtTheDoorPage() {
const [info, setInfo] = useDismissingState<string | null>(null);
const [error, setError] = useDismissingState<string | null>(null);
// A required attendee form holds the tickets back: it pops up to fill in now, or "Fill in
// later" (tickets are issued anyway and the attendee gets a link).
const [formPrompt, setFormPrompt] = useState<{ registration: Registration; needed: number } | null>(null);
const loadFull = (id: string) => apiV2Data("get", "/registrations/{id}/full", { params: { id }, authToken: token }) as Promise<Registration>;
const promptFormFor = (full: Registration) => {
const needed = formsStillNeeded(doorEvent?.form, full);
if (needed > 0 && full.status !== "cancelled") setFormPrompt({ registration: full, needed });
return needed;
};
const handleRegistrationCreated = (registration: Registration) => {
setActiveRegistration(registration); // 🚀 Jump automatically (see effect below)
if ((registration.formsNeeded || 0) > 0) setFormPrompt({ registration, needed: registration.formsNeeded || 0 });
};
const handleRegistrationSelected = (registration: Registration) => {
setActiveRegistration(registration);
// The search list doesn't carry the forms, so look at the whole registration.
loadFull(registration.id).then(promptFormFor).catch(() => {});
};
const handleFormDone = async ({ later, ticketsIssued, sentTo }: { later: boolean; ticketsIssued: number; sentTo?: string[] }) => {
const reg = formPrompt?.registration;
setFormPrompt(null);
const issued = ticketsIssued > 0 ? " Tickets issued." : "";
setInfo(later
? `Form left for later${sentTo && sentTo.length ? ` — a link was sent by ${sentTo.join(" and ")}` : ""}.${issued}`
: `Attendee form saved.${issued}`);
if (reg) {
try { setActiveRegistration(await loadFull(reg.id)); } catch {}
}
};
useEffect(() => {
@@ -404,9 +430,14 @@ export default function AtTheDoorPage() {
// Tickets are generated and emailed/WhatsApped automatically server-side
// once a registration reaches "paid" (see paymentController) — no need to
// fetch/print them here, just move straight to checking the attendee in.
// Unless a required attendee form holds them back: that pops up first.
setActiveRegistration(reg);
setInfo("Payment recorded — tickets sent. Ready to check in.");
setMode("checkin");
if (reg && promptFormFor(reg) > 0) {
setInfo("Payment recorded — fill in the attendee form (or choose Fill in later) to issue the tickets.");
return;
}
setInfo("Payment recorded — tickets sent. Ready to check in.");
};
const handleDonation = (user?: UserSummary) => {
@@ -499,7 +530,12 @@ export default function AtTheDoorPage() {
)}
{mode === "checkin" && (
<DoorCheckInPanel token={token} eventId={eventId} registration={activeRegistration} setError={setError} setInfo={setInfo} />
<DoorCheckInPanel
token={token} eventId={eventId} registration={activeRegistration} setError={setError} setInfo={setInfo}
onFillForm={activeRegistration ? () => loadFull(activeRegistration.id).then(full => {
if (promptFormFor(full) === 0) setError("No attendee form is outstanding. If the tickets are still missing, an admin can issue them in Corrections.");
}).catch(e => setError(errorMessage(e) || "Couldn't load the registration")) : undefined}
/>
)}
{mode === "tickets" && (
@@ -550,6 +586,17 @@ export default function AtTheDoorPage() {
seed={newAttendeeSeed}
onConfirm={handleNewAttendeeConfirm}
/>
{formPrompt && (
<AttendeeFormModal
key={formPrompt.registration.id}
registrationId={formPrompt.registration.id}
form={doorEvent?.form}
needed={formPrompt.needed}
token={token}
attendeeName={formPrompt.registration.user?.name}
onDone={handleFormDone}
/>
)}
</div>
);
}
@@ -1027,12 +1074,14 @@ function DoorTicketsPanel({ token, eventId }: { token: string | null; eventId: s
);
}
function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: {
function DoorCheckInPanel({ token, eventId, registration, setError, setInfo, onFillForm }: {
token: string | null;
eventId: string;
registration: Registration | null;
setError: (e: string | null) => void;
setInfo: (s: string | null) => void;
/** No tickets yet: open the attendee form that holds them back. */
onFillForm?: () => void;
}) {
const [ticketsForEvent, setTicketsForEvent] = useState<TicketRecord[]>([]);
const [loading, setLoading] = useState(false);
@@ -1053,7 +1102,8 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: {
}
}, [token, eventId]);
useEffect(() => { load(); }, [load]);
// Again when the registration changes: its tickets may have just been issued.
useEffect(() => { load(); }, [load, registration]);
if (!registration) {
return (
@@ -1117,9 +1167,18 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: {
)}
{!loading && myTickets.length === 0 && (
<div className="text-sm text-gray-500">
No Main Tickets on this registration
</div>
registration.status === "paid" && onFillForm ? (
<div className="text-sm border border-amber-200 bg-amber-50 rounded-lg p-3 text-amber-900">
No tickets yet. If the event has an attendee form, it&rsquo;s holding them back.
<button type="button" onClick={onFillForm} className="block mt-2 px-3 py-1.5 rounded bg-amber-600 text-white text-xs font-medium">
Fill in the attendee form
</button>
</div>
) : (
<div className="text-sm text-gray-500">
{registration.status === "paid" ? "No Main Tickets on this registration" : "No tickets yet — they're issued once it's paid."}
</div>
)
)}
<div className="space-y-4">
@@ -167,6 +167,21 @@ function AttendeeFormsSection({ registration, form, formsData, setFormsData }: {
}
};
// The tickets stop waiting for the form (issued now if it's paid); the attendee gets a link.
const later = async () => {
if (!token) return;
try {
setSubmitting(true);
setError(null); setInfo(null);
const res = await (apiV2Data("post", "/registrations/{id}/form-later", { params: { id: registration.id }, authToken: token, body: {} }) as Promise<{ ticketsIssued: number; sentTo: string[] }>);
setInfo(`Form left for later${res?.sentTo?.length ? ` — a link was sent by ${res.sentTo.join(' and ')}` : ''}.${res?.ticketsIssued ? ' Tickets issued.' : ''}`);
} catch (e) {
setError(errorMessage(e) || 'Failed to leave the form for later');
} finally {
setSubmitting(false);
}
};
if (!form || !Array.isArray(form.fields) || count === 0) return null;
return (
<div className="mt-6 border rounded p-3 bg-gray-50">
@@ -212,7 +227,10 @@ function AttendeeFormsSection({ registration, form, formsData, setFormsData }: {
</div>
))}
</div>
<button className="mt-3 px-3 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50" disabled={submitting || !canSubmit} onClick={submit}>{submitting ? 'Submitting…' : 'Submit forms'}</button>
<div className="mt-3 flex gap-2">
<button className="px-3 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50" disabled={submitting || !canSubmit} onClick={submit}>{submitting ? 'Submitting…' : 'Submit forms'}</button>
{form.isRequired && <button className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50 disabled:opacity-50" disabled={submitting} onClick={later}>Fill in later</button>}
</div>
</div>
);
}
@@ -18,6 +18,7 @@ import type { Event, EventOption, PublicBundle, Registration, RegistrationOption
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";
// ─── Pricing helpers ─────────────────────────────────────────────────────────
@@ -91,6 +92,15 @@ export default function ManualRegistrationPage() {
const [paySubmitting, setPaySubmitting] = useState(false);
const [payMessage, setPayMessage] = useDismissingState<string | null>(null);
const [payError, setPayError] = useDismissingState<string | null>(null);
// A required attendee form holding the tickets back: fill it in now, or "Fill in later".
const [formPrompt, setFormPrompt] = useState<{ registrationId: string; needed: number; form: AttendeeFormDef; name?: string } | null>(null);
const promptForm = async (registrationId: string, needed: number, eventId: string, name?: string) => {
if (!(needed > 0)) return;
try {
const ev = await fetchEvent<Event>(eventId, { authToken: token || undefined });
setFormPrompt({ registrationId, needed, form: ev?.form, name });
} catch {}
};
// Load all users for client-side fuzzy matching
useEffect(() => {
@@ -164,7 +174,7 @@ export default function ManualRegistrationPage() {
if (!payRegistrationId) { setPayError("Please select a registration"); return; }
try {
setPaySubmitting(true);
await apiV2Data("post", "/payments", {
const paid = await (apiV2Data("post", "/payments", {
authToken: token,
body: {
amount: amt,
@@ -174,8 +184,11 @@ export default function ManualRegistrationPage() {
isDonation: false,
paidAt: payPaidAtLocal ? new Date(payPaidAtLocal).toISOString() : undefined,
},
});
setPayMessage(`Payment recorded (R ${amt.toFixed(2)}).`);
}) as Promise<{ formsNeeded?: number; registration?: { eventId?: string } }>);
setPayMessage(`Payment recorded (R ${amt.toFixed(2)}).${(paid?.formsNeeded || 0) > 0 ? " The attendee form is holding the tickets back." : ""}`);
const paidReg = allRegistrations.find(r => r.id === payRegistrationId);
const paidEventId = paid?.registration?.eventId || paidReg?.eventId;
if (paidEventId) promptForm(payRegistrationId, paid?.formsNeeded || 0, paidEventId, paidReg?.user?.name);
setPayAmount("");
setPayPaidAtLocal("");
// Refresh registrations so the displayed outstanding balance updates
@@ -362,6 +375,7 @@ export default function ManualRegistrationPage() {
setMessage(res?.couponError
? `Manual registration created, but the code wasn't applied: ${res.couponError}`
: coupon ? `Manual registration created with code ${coupon.code}.` : "Manual registration created successfully.");
if ((res?.formsNeeded || 0) > 0) setFormPrompt({ registrationId: res.id, needed: res.formsNeeded || 0, form: fullEvent?.form, name: res.user?.name || guest.name });
// Pre-load the Record Payment tab with this registration so it's ready to go the
// moment a supervisor clicks over — the tab itself is never switched to automatically.
@@ -771,6 +785,24 @@ export default function ManualRegistrationPage() {
</div>
</div>
)}
{formPrompt && (
<AttendeeFormModal
key={formPrompt.registrationId}
registrationId={formPrompt.registrationId}
form={formPrompt.form}
needed={formPrompt.needed}
token={token}
attendeeName={formPrompt.name}
onDone={({ later, ticketsIssued, sentTo }) => {
setFormPrompt(null);
const issued = ticketsIssued > 0 ? " Tickets issued." : "";
const text = later
? `Attendee form left for later${sentTo && sentTo.length ? ` — a link was sent by ${sentTo.join(" and ")}` : ""}.${issued}`
: `Attendee form saved.${issued}`;
if (tab === "payment") setPayMessage(text); else setMessage(text);
}}
/>
)}
</div>
);
}
@@ -1033,11 +1033,14 @@ export default function UserDashboardPage() {
{renderGroup('Early bird', earlyBirdRows)}
{renderGroup('Standard price', standardRows)}
<BundleSavings applications={activeReg.bundleApplications} className="mt-2" />
{Number(activeReg.discountTotal || 0) - Number(activeReg.bundleDiscount || 0) > 0.005 && (
{Number(activeReg.discountTotal || 0) - Number(activeReg.bundleDiscount || 0) - Number(activeReg.complimentaryDiscount || 0) > 0.005 && (
<div className="text-sm text-green-700 mt-2">
Discount code{activeCoupon?.coupon?.code ? <> <span className="font-mono font-semibold">{activeCoupon.coupon.code}</span></> : null} — −{formatRand(Number(activeReg.discountTotal) - Number(activeReg.bundleDiscount || 0))}
Discount code{activeCoupon?.coupon?.code ? <> <span className="font-mono font-semibold">{activeCoupon.coupon.code}</span></> : null} — −{formatRand(Number(activeReg.discountTotal) - Number(activeReg.bundleDiscount || 0) - Number(activeReg.complimentaryDiscount || 0))}
</div>
)}
{Number(activeReg.complimentaryDiscount || 0) > 0.005 && (
<div className="text-sm text-green-700 mt-2">Complimentary — −{formatRand(Number(activeReg.complimentaryDiscount))}</div>
)}
{canModifyActive && activeBill && activeBill.outstanding > 0 && !activeCoupon && (
<div className="mt-3">
<div className="flex gap-2">
@@ -197,6 +197,9 @@ export default function SelfServicePage() {
// ── Event form (attendee form) state ────────────────────────────
const [currentRegistrationId, setCurrentRegistrationId] = useState<string | null>(null);
const [currentTicketIndex, setCurrentTicketIndex] = useState(0);
// Attendee forms the server says this registration still needs (it counts places already
// on an existing registration, and a picked-session booking once).
const [formsToFill, setFormsToFill] = useState(0);
const [allFormAnswers, setAllFormAnswers] = useState<Record<string, string>[]>([]);
const [currentTicketAnswers, setCurrentTicketAnswers] = useState<Record<string, string>>({});
const [formSubmitLoading, setFormSubmitLoading] = useState(false);
@@ -264,16 +267,24 @@ export default function SelfServicePage() {
}), [quantities]);
const bundleQuote = useBundleQuote({ eventId: selectedEventId || "", basket: kioskBasket, token: supervisorToken, forUserId: matchedAccount?.id ?? null });
// Does the selected event have a required form?
// Does the selected event have a required form? (Statements and headings aren't questions.)
const eventHasRequiredForm = useMemo(() => {
return !!(selectedEvent?.form?.isRequired && (selectedEvent.form.fields || []).some(f => f.type !== 'statement'));
return !!(selectedEvent?.form?.isRequired && (selectedEvent.form.fields || []).some(f => f.type !== 'statement' && f.type !== 'paragraph'));
}, [selectedEvent]);
// Answerable form fields (exclude statement-type display fields)
// Answerable form fields (exclude statement and heading display fields)
const answerableFields = useMemo(() => {
if (!selectedEvent?.form) return [];
return (selectedEvent.form.fields || [])
.filter(f => f.type !== 'statement')
.filter(f => f.type !== 'statement' && f.type !== 'paragraph')
.sort((a, b) => (a.order || 0) - (b.order || 0));
}, [selectedEvent]);
// Statements and headings, shown above the questions
const formTexts = useMemo(() => {
if (!selectedEvent?.form) return [];
return (selectedEvent.form.fields || [])
.filter(f => f.type === 'statement' || f.type === 'paragraph')
.sort((a, b) => (a.order || 0) - (b.order || 0));
}, [selectedEvent]);
@@ -486,11 +497,13 @@ export default function SelfServicePage() {
}) as Promise<Registration>);
setCurrentRegistrationId(result?.id || null);
const needed = result?.formsNeeded ?? (eventHasRequiredForm ? mainTicketCount : 0);
setFormsToFill(needed);
setRegistrationIsFree(result?.status === "paid" || (result?.totalDueComputed ?? total) === 0);
setConfirmationName(visitorName.trim());
// If event has a required form and there are main tickets, show form step
if (eventHasRequiredForm && mainTicketCount > 0 && result?.id) {
// If the required form still holds the tickets back, show the form step
if (needed > 0 && result?.id) {
setCurrentTicketIndex(0);
setAllFormAnswers([]);
setCurrentTicketAnswers({});
@@ -528,7 +541,7 @@ export default function SelfServicePage() {
const collectedAnswers = [...allFormAnswers, currentTicketAnswers];
// If more tickets remain, advance to the next one
if (currentTicketIndex < mainTicketCount - 1) {
if (currentTicketIndex < formsToFill - 1) {
setAllFormAnswers(collectedAnswers);
setCurrentTicketAnswers({});
setCurrentTicketIndex((i) => i + 1);
@@ -606,6 +619,7 @@ export default function SelfServicePage() {
setFormError(null);
setCurrentRegistrationId(null);
setCurrentTicketIndex(0);
setFormsToFill(0);
setAllFormAnswers([]);
setCurrentTicketAnswers({});
setFormSubmitError(null);
@@ -1219,13 +1233,13 @@ export default function SelfServicePage() {
<div className="text-center mb-6">
<p className="text-sm text-gray-500 uppercase tracking-wide font-medium">{selectedEvent.title}</p>
<h2 className="text-2xl font-bold text-gray-900 mt-1">Attendee Information</h2>
{mainTicketCount > 1 && (
{formsToFill > 1 && (
<div className="mt-3">
<p className="text-base font-semibold text-brand-700">
Attendee {currentTicketIndex + 1} of {mainTicketCount}
Attendee {currentTicketIndex + 1} of {formsToFill}
</p>
<div className="flex gap-1.5 justify-center mt-2">
{Array.from({ length: mainTicketCount }).map((_, i) => (
{Array.from({ length: formsToFill }).map((_, i) => (
<div
key={i}
className={`h-2 rounded-full transition-all ${
@@ -1240,12 +1254,18 @@ export default function SelfServicePage() {
</div>
</div>
)}
{mainTicketCount <= 1 && (
{formsToFill <= 1 && (
<p className="text-sm text-gray-500 mt-1">This form is required to complete your registration.</p>
)}
</div>
<form onSubmit={handleFormSubmit} className="space-y-5">
{formTexts.map((field) => (
<div key={field.id} className={field.type === "paragraph" ? "text-base font-semibold text-gray-800" : "text-sm text-gray-600"}>
{field.label}
{field.helpText && <p className="text-sm font-normal text-gray-500 mt-1">{field.helpText}</p>}
</div>
))}
{answerableFields.map((field) => (
<div key={field.id}>
<label htmlFor={`kiosk-field-${field.id}`} className="block text-sm font-medium text-gray-700 mb-1">
@@ -1292,15 +1312,6 @@ export default function SelfServicePage() {
required={field.isRequired}
className="w-full border border-gray-300 rounded-xl px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-brand-500"
/>
) : field.type === "paragraph" ? (
<textarea
id={`kiosk-field-${field.id}`}
value={currentTicketAnswers[field.id] || ""}
onChange={e => setCurrentTicketAnswers(a => ({ ...a, [field.id]: e.target.value }))}
required={field.isRequired}
rows={3}
className="w-full border border-gray-300 rounded-xl px-4 py-3 text-base focus:outline-none focus:ring-2 focus:ring-brand-500 resize-none"
/>
) : (
<input
id={`kiosk-field-${field.id}`}
@@ -1327,8 +1338,8 @@ export default function SelfServicePage() {
>
{formSubmitLoading
? "Submitting…"
: currentTicketIndex < mainTicketCount - 1
? `Next — Attendee ${currentTicketIndex + 2} of ${mainTicketCount}`
: currentTicketIndex < formsToFill - 1
? `Next — Attendee ${currentTicketIndex + 2} of ${formsToFill}`
: "Complete Registration"}
</button>
</form>