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

At The Door

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

{localError}

} {localInfo &&

{localInfo}

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

{localError}

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

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

{err &&

{err}

}
); }