"use client"; import React, { useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { createFullPaymentCheckout, fetchEvent } from "@/lib/api"; import { apiV2, apiV2Data } from "@/lib/apiV2"; import { useOnlinePayments } from "@/lib/onlinePayments"; import { useRouter } from "next/navigation"; import { formatDate } from "@/lib/date"; import { printTicketCards } from "@/lib/ticketPrint"; import { formatPaymentMethod } from "@/lib/paymentMethod"; import { QrImage } from "@/components/shared/QrImage"; import { ApiImage } from "@/components/shared/ApiImage"; import { useDismissingState } from "@/hooks/useDismissingState"; import { AttendeesPanel } from "@/components/shared/AttendeesPanel"; import { MyWaitlists } from "@/components/shared/MyWaitlists"; import { TransferTicketModal, canOfferTransfer } from "@/components/shared/TransferTicketModal"; import { ClipboardList, Calendar, Ticket, ChevronRight } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { registrationOptionUnitPrice } from "@/lib/pricing"; import { BundleSavings } from "@/components/shared/BundleDeals"; 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)}`; const isFuture = (d: string | Date) => new Date(d).getTime() > Date.now(); type EventStatusFields = Pick; type Billing = { totalDue: number; totalPaid: number; outstanding: number; payments: Payment[] }; const isEventOver = (ev: EventStatusFields | null | undefined) => !!ev && ((ev.endDate && new Date(ev.endDate).getTime() < Date.now()) || ev.cashupStatus === 'closed'); // 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() < now) { label = 'Past'; className = 'bg-amber-50 text-amber-700'; } else if (event.isActive === false) { label = 'Inactive'; className = 'bg-gray-100 text-gray-500'; } if (!label) return null; return {label}; } // Status badge for a registration, shown wherever registration.status is displayed on this // page. Colors match the status coloring already used on dashboard/admin/registrations. const REGISTRATION_STATUS_STYLES: Record = { pending: { label: 'Pending', className: 'bg-gray-100 text-gray-600' }, confirmed: { label: 'Confirmed', className: 'bg-blue-50 text-blue-700' }, partial_paid: { label: 'Partially Paid', className: 'bg-amber-50 text-amber-700' }, paid: { label: 'Paid', className: 'bg-green-50 text-green-700' }, cancelled: { label: 'Cancelled', className: 'bg-red-50 text-red-700' }, }; function RegistrationStatusBadge({ status }: { status: string }) { const s = REGISTRATION_STATUS_STYLES[status] || { label: status, className: 'bg-gray-100 text-gray-500' }; return {s.label}; } // Effective unit price for an event option (or one of its variants), early-bird aware. // Used by the registration editor, which works off raw /api/events/:id data rather than // a registration's priceSnapshot — mirrors the pricing logic in register/[eventId]/RegisterForm.tsx. function effectiveEventOptionUnitPrice(eo: EventOption, variantId: string | null): number { const variant = variantId ? (eo?.variants || []).find((v) => v.id === variantId) : null; const base = (variant && variant.price !== null && variant.price !== undefined) ? Number(variant.price) : Number(eo?.price || 0); const allTiers = Array.isArray(eo?.earlyBirdTiers) ? eo.earlyBirdTiers : []; const tiers = variantId ? allTiers.filter((t) => t.variantId === variantId) : allTiers.filter((t) => !t.variantId); if (tiers.length === 0) return base; const now = new Date(); const applicable = tiers .map((t) => ({ ...t, _d: new Date(t.deadline) })) .filter((t) => now < t._d) .sort((a, b) => a.price - b.price || a._d.getTime() - b._d.getTime()); return applicable.length > 0 ? applicable[0].price : base; } export default function UserDashboardPage() { const { token, user } = useAuth(); const online = useOnlinePayments(); const [registrations, setRegistrations] = useState([]); const [tickets, setTickets] = useState([]); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); const [loading, setLoading] = useState(false); // Filters const [showPast, setShowPast] = useState(false); // Billing map: regId -> { totalDue, totalPaid, outstanding, payments } const [billing, setBilling] = useState>({}); // Forms status cache for registrations // regId -> { hasForm: boolean; isRequired?: boolean; submittedCount?: number; requiredCount?: number; complete?: boolean } const [formStatuses, setFormStatuses] = useState>({}); // Ticket selection const [selected, setSelected] = useState>({}); // Registration details modal const [activeRegId, setActiveRegId] = useState(null); const [dialog, setDialog] = useState<{ open: boolean; message: string; loading?: boolean; loadingTitle?: string; loadingSubtitle?: string; title?: string }>({ open: false, message: "", loading: false }); // Channel-choice popup shown by the single "Invoice"/"Receipt" buttons — asks Email or WhatsApp. const [channelPicker, setChannelPicker] = useState<{ kind: 'invoice' | 'receipt'; id: string } | null>(null); // Track whether the active registration's event has attendee forms const [activeEventHasForm, setActiveEventHasForm] = useState(null); useEffect(() => { (async () => { if (!token) return; setLoading(true); setError(null); try { // Tickets don't depend on registrations, so fetch both at once instead of // waterfalling — this was previously fetched only after registrations + all // their payments had already resolved. const [myRegs, myTicks] = await Promise.all([ (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise), (apiV2Data("get", "/me/tickets", { authToken: token }) as Promise), ]); setRegistrations(myRegs); setTickets(myTicks); // Use the backend's tranche-aware totalDueComputed (exact even when a line spans // multiple early-bird prices) rather than re-deriving from priceSnapshot client-side. const totals: Record = {}; for (const r of myRegs) { const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, new Date()) * (opt.quantity || 0), 0); totals[r.id] = { totalDue, totalPaid: 0, outstanding: totalDue, payments: [] }; } setBilling(totals); // Fetch payments per registration to compute outstanding await Promise.all( myRegs.map(async (r) => { try { const pays = await (apiV2Data("get", "/registrations/{id}/payments", { params: { id: r.id }, authToken: token }) as Promise); const totalPaid = pays.reduce((s, p) => s + (p.amount || 0), 0); // totalDueComputed is not time-dependent, no need to recompute per payment time const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, new Date()) * (opt.quantity || 0), 0); const outstanding = Math.max(0, totalDue - totalPaid); setBilling(prev => ({ ...prev, [r.id]: { totalDue, totalPaid, outstanding, payments: pays, }, })); } catch (e) { // Ignore per-reg payment errors but log console.warn("Failed to load payments for", r.id, e); } }) ); } catch (e) { setError(errorMessage(e) || "Failed to load data"); } finally { setLoading(false); } })(); }, [token, showPast, setError]); // After registrations load, compute forms status for each registration. // `myregistrations` now embeds event.form (with fields) directly, so this no longer // needs a GET /api/events/:id per registration — only the registration-detail fetch // (to get submittedCount) remains, and only for registrations that actually have a form. useEffect(() => { (async () => { if (!token || registrations.length === 0) return; const next: Record = {}; await Promise.all( registrations.map(async (r) => { try { const ev = r.event; const hasForm = !!(ev?.form && Array.isArray(ev.form.fields) && ev.form.fields.length > 0); if (!hasForm) { next[r.id] = { hasForm: false }; return; } // Load registration to get number of submitted responses const regFull = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: r.id }, authToken: token }) as Promise); const submittedCount = (regFull?.formResponses || []).length; // Required count equals the number of main tickets purchased const requiredCount = (r.registrationOptions || []) .filter((ro) => ro.eventOption?.isMainTicket) .reduce((s, ro) => s + (ro.quantity || 0), 0); const complete = submittedCount >= requiredCount && requiredCount > 0 ? true : (submittedCount >= requiredCount); next[r.id] = { hasForm: true, isRequired: !!ev?.form?.isRequired, submittedCount, requiredCount, complete, }; } catch { // On any error, do not show forms status to avoid noisy UI next[r.id] = { hasForm: false }; } }) ); setFormStatuses(next); })(); }, [token, registrations]); const toggleSelect = (id: string, checked?: boolean) => { setSelected(prev => ({ ...prev, [id]: checked ?? !prev[id] })); }; const selectAll = (on: boolean) => { const next: Record = {}; tickets.forEach(t => (next[t.id] = on)); setSelected(next); }; const selectedIds = useMemo(() => Object.entries(selected).filter(([, v]) => v).map(([k]) => k), [selected]); const emailTickets = async (ticketIds: string[]) => { if (!token || ticketIds.length === 0) return; setError(null); setInfo(null); // Open loading dialog immediately setDialog({ open: true, message: "Sending tickets…", loading: true }); try { const res = await (apiV2Data("post", "/me/tickets/email", { body: { ticketIds }, authToken: token, }) as Promise<{ message?: string }>); const msg = (res && res.message) ? res.message : `${ticketIds.length} ticket(s) emailed successfully.`; setDialog({ open: true, message: msg, loading: false }); } catch (e) { setDialog({ open: false, message: "", loading: false }); setError(errorMessage(e) || "Failed to email tickets"); } }; const whatsappTickets = async (ticketIds: string[]) => { if (!token || ticketIds.length === 0) return; if (!user?.phoneNumber) { setError("No phone number on your account. Add one in your profile."); return; } setError(null); setInfo(null); setDialog({ open: true, message: "Sending to WhatsApp…", loading: true }); try { const res = await (apiV2Data("post", "/me/tickets/email", { body: { ticketIds, channel: "whatsapp" }, authToken: token, }) as Promise<{ message?: string }>); const msg = (res && res.message) ? res.message : `${ticketIds.length} ticket(s) sent to WhatsApp.`; setDialog({ open: true, message: msg, loading: false }); } catch (e) { setDialog({ open: false, message: "", loading: false }); setError(errorMessage(e) || "Failed to send tickets to WhatsApp"); } }; const sendInvoice = async (registrationId: string, channel: 'email' | 'whatsapp') => { if (!token) return; setError(null); setInfo(null); setDialog({ open: true, loading: true, message: "", loadingTitle: channel === 'whatsapp' ? "Sending invoice to WhatsApp…" : "Sending invoice…", loadingSubtitle: "Please wait while we prepare your invoice.", }); try { const res = await (apiV2Data("post", "/registrations/{id}/invoice", { params: { id: registrationId }, body: { channel }, authToken: token, }) as Promise<{ message?: string }>); setDialog({ open: true, loading: false, title: "Invoice sent", message: (res && res.message) || "Invoice sent." }); } catch (e) { setDialog({ open: false, message: "", loading: false }); setError(errorMessage(e) || "Failed to send invoice"); } }; const sendReceipt = async (paymentId: string, channel: 'email' | 'whatsapp') => { if (!token) return; setError(null); setInfo(null); setDialog({ open: true, loading: true, message: "", loadingTitle: channel === 'whatsapp' ? "Sending receipt to WhatsApp…" : "Sending receipt…", loadingSubtitle: "Please wait while we prepare your receipt.", }); try { const res = await (apiV2Data("post", "/payments/{id}/receipt", { params: { id: paymentId }, body: { channel }, authToken: token, }) as Promise<{ message?: string }>); setDialog({ open: true, loading: false, title: "Receipt sent", message: (res && res.message) || "Receipt sent." }); } catch (e) { setDialog({ open: false, message: "", loading: false }); setError(errorMessage(e) || "Failed to send receipt"); } }; // Resolves the channel-picker popup: dispatches to the invoice or receipt sender for // whichever id it was opened with, then closes the popup. const chooseChannel = (channel: 'email' | 'whatsapp') => { if (!channelPicker) return; const { kind, id } = channelPicker; setChannelPicker(null); if (kind === 'invoice') sendInvoice(id, channel); else sendReceipt(id, channel); }; // Creates an online checkout for the full outstanding balance and redirects there directly — // choosing a partial amount is only available from the supervisor payments dashboard. const payNow = async (registrationId: string) => { if (!token) return; setError(null); setInfo(null); setDialog({ open: true, message: "Creating payment link…", loading: true, loadingTitle: "Creating payment link…", loadingSubtitle: "Please wait while we take you to the secure payment page." }); try { const res = await createFullPaymentCheckout(token, registrationId); if (res.priceUpdated) { setDialog({ open: false, message: "", loading: false }); setError(`${res.message || 'Pricing has changed.'} New total: R ${(res.newTotal ?? 0).toFixed(2)}. Please try again.`); // Refresh this registration's billing so the displayed outstanding reflects the new price try { const now = new Date(); const r = await (apiV2Data("get", "/registrations/{id}/full", { params: { id: registrationId }, authToken: token }) as Promise); const pays = await (apiV2Data("get", "/registrations/{id}/payments", { params: { id: registrationId }, authToken: token }) as Promise); const totalPaid = pays.reduce((s, p) => s + (p.amount || 0), 0); const totalDue = (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, now) * (opt.quantity || 0), 0); setBilling(prev => ({ ...prev, [registrationId]: { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid), payments: pays } })); } catch {} return; } if (!res.redirectUrl) { setDialog({ open: false, message: "", loading: false }); setError("Failed to create checkout"); return; } window.location.href = res.redirectUrl; } catch (e) { setDialog({ open: false, message: "", loading: false }); setError(errorMessage(e) || "Failed to create checkout"); } }; const printTickets = (ticketList: TicketRecord[]) => printTicketCards(ticketList, () => user?.name); // Upcoming events derived from registrations const upcomingEvents = useMemo(() => { const map = new Map(); for (const r of registrations) { if (r.event && isFuture(r.event.startDate)) { if (!map.has(r.event.id)) map.set(r.event.id, r.event); } } return Array.from(map.values()).sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); }, [registrations]); // Registration click -> open modal const activeReg = useMemo(() => registrations.find(r => r.id === activeRegId) || null, [registrations, activeRegId]); const activeBill = activeRegId ? billing[activeRegId] : undefined; // When a registration is opened, determine whether its event has attendee forms useExternalEffect(() => { setActiveEventHasForm(null); if (!activeRegId) return; const ar = registrations.find(r => r.id === activeRegId); if (!ar) return; const evForm = ar.event?.form; if (evForm && Array.isArray(evForm.fields) && evForm.fields.length > 0) { setActiveEventHasForm(true); return; } (async () => { try { const ev = await fetchEvent(ar.eventId); const has = !!(ev?.form && Array.isArray(ev.form.fields) && ev.form.fields.length > 0); setActiveEventHasForm(has); } catch { setActiveEventHasForm(false); } })(); }, [activeRegId, registrations]); const showFormsButton = useMemo(() => { const evForm = activeReg?.event?.form; if (evForm && Array.isArray(evForm.fields)) return evForm.fields.length > 0; if (activeEventHasForm !== null) return activeEventHasForm; return false; }, [activeReg, activeEventHasForm]); // Discount code on an existing registration const [codeInput, setCodeInput] = useState(""); const [codeBusy, setCodeBusy] = useState(false); const [codeError, setCodeError] = useState(null); const applyCodeToActive = async () => { if (!token || !activeRegId || !codeInput.trim()) return; setCodeBusy(true); setCodeError(null); try { const res = await (apiV2Data("post", "/registrations/{id}/coupon", { params: { id: activeRegId }, authToken: token, body: { code: codeInput.trim() }, }) as Promise<{ message?: string }>); const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); const updated = myRegs.find(r => r.id === activeRegId); const pays = await (apiV2Data("get", "/registrations/{id}/payments", { params: { id: activeRegId }, authToken: token }) as Promise); const totalPaid = pays.reduce((s, p) => s + (p.amount || 0), 0); const totalDue = updated?.totalDueComputed ?? 0; setBilling(prev => ({ ...prev, [activeRegId]: { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid), payments: pays } })); try { const myTicks = await (apiV2Data("get", "/me/tickets", { authToken: token }) as Promise); setTickets(myTicks); } catch {} setCodeInput(""); setInfo(res?.message || 'Code applied.'); } catch (e) { setCodeError(errorMessage(e) || "Couldn't apply that code"); } finally { setCodeBusy(false); } }; const [transferTarget, setTransferTarget] = useState(null); // Re-fetch registrations and tickets after something on one changes (attendee names). const reloadAfterAttendees = async () => { if (!token) return; try { const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); const myTicks = await (apiV2Data("get", "/me/tickets", { authToken: token }) as Promise); setTickets(myTicks); } catch {} }; // Cancel registration state const [cancelLoading, setCancelLoading] = useState(false); const [showCancelConfirm, setShowCancelConfirm] = useState(false); const cancelRegistration = async () => { if (!token || !activeRegId) return; setCancelLoading(true); try { await apiV2("post", "/registrations/{id}/cancel", { params: { id: activeRegId }, authToken: token }); const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); setActiveRegId(null); setShowCancelConfirm(false); setInfo('Registration cancelled.'); } catch (e) { setError(errorMessage(e) || 'Failed to cancel registration'); setShowCancelConfirm(false); } finally { setCancelLoading(false); } }; // Editor state for registration items. Keyed like register/[eventId]/RegisterForm.tsx: // "eventOptionId" for plain options, "eventOptionId:variantId" for variant options. const [editMode, setEditMode] = useState(false); const [editLoading, setEditLoading] = useState(false); const [editEventOptions, setEditEventOptions] = useState([]); const [editQuantities, setEditQuantities] = useState>({}); const [editBaseQty, setEditBaseQty] = useState>({}); const [editMinQty, setEditMinQty] = useState>({}); const [editError, setEditError] = useState(null); // Whether the active registration's event still permits self-service changes // (edit items, pay, cancel) — false once the event is past or its cashup is closed. const canModifyActive = useMemo(() => { if (!activeReg) return false; return !isEventOver(activeReg.event); }, [activeReg]); // Picked-session lines can't be edited here (book more by registering), but still count. const pickedLinesTotal = useMemo(() => (activeReg?.registrationOptions || []) .filter(ro => ro.sessionId) .reduce((s, ro) => s + (ro.lineTotal ?? (ro.quantity || 0) * (ro.priceSnapshot || 0)), 0), [activeReg]); const editTotal = useMemo(() => { return pickedLinesTotal + editEventOptions.reduce((sum, eo) => { if (Array.isArray(eo.variants) && eo.variants.length > 0) { return sum + eo.variants.reduce((vsum, v) => { const qty = editQuantities[`${eo.id}:${v.id}`] || 0; return vsum + qty * effectiveEventOptionUnitPrice(eo, v.id); }, 0); } return sum + (editQuantities[eo.id] || 0) * effectiveEventOptionUnitPrice(eo, null); }, 0); }, [editEventOptions, editQuantities, pickedLinesTotal]); const beginEdit = async () => { if (!activeReg || !token) return; setEditError(null); setEditLoading(true); try { // Load event options (with variants) for this event const eventData = await fetchEvent(activeReg.eventId); const eventOptions = (eventData?.eventOptions || []).filter((eo) => !isPickOption(eventData, eo)); const regOptById = new Map((activeReg.registrationOptions || []).map((o) => [o.id, o])); // Prefill quantities from the current registration const qtyMap: Record = {}; for (const ro of (activeReg.registrationOptions || []).filter(r => !r.sessionId)) { const key = ro.variantId ? `${ro.eventOptionId}:${ro.variantId}` : ro.eventOptionId; qtyMap[key] = (qtyMap[key] || 0) + (ro.quantity || 0); } // Already-issued ticket quantity per option/variant — can't reduce below this // (tickets are never deleted or shrunk, only ever grown, once paid). const minQtyMap: Record = {}; for (const t of tickets) { const ro = t.registrationOptionId ? regOptById.get(t.registrationOptionId) : undefined; if (!ro || ro.sessionId) continue; const key = ro.variantId ? `${ro.eventOptionId}:${ro.variantId}` : ro.eventOptionId; minQtyMap[key] = (minQtyMap[key] || 0) + (t.quantity || 0); } // Ensure every option/variant has a (possibly zero) entry so they all render eventOptions.forEach((eo) => { if (Array.isArray(eo.variants) && eo.variants.length > 0) { eo.variants.forEach((v) => { const key = `${eo.id}:${v.id}`; if (!(key in qtyMap)) qtyMap[key] = 0; }); } else if (!(eo.id in qtyMap)) { qtyMap[eo.id] = 0; } }); setEditEventOptions(eventOptions); setEditQuantities(qtyMap); setEditBaseQty({ ...qtyMap }); setEditMinQty(minQtyMap); setEditMode(true); } catch (e) { setEditError(errorMessage(e) || 'Failed to load event options'); } finally { setEditLoading(false); } }; const saveEdit = async () => { if (!activeReg || !token) return; setEditError(null); for (const [key, minQty] of Object.entries(editMinQty)) { if (minQty <= 0) continue; if ((editQuantities[key] || 0) < minQty) { const [eventOptionId, variantId] = key.includes(':') ? key.split(':') : [key, undefined]; const eo = editEventOptions.find((o) => o.id === eventOptionId); const variant = variantId ? (eo?.variants || []).find((v) => v.id === variantId) : null; const label = variant ? `${eo?.name || 'item'} (${variant.name})` : (eo?.name || 'item'); setEditError(`Cannot reduce "${label}" below the ${minQty} already issued`); return; } } const payloadOptions: { eventOptionId: string; quantity: number; variantId?: string }[] = []; for (const [key, qty] of Object.entries(editQuantities)) { if (qty <= 0) continue; if (key.includes(':')) { const [eventOptionId, variantId] = key.split(':'); payloadOptions.push({ eventOptionId, quantity: qty, variantId }); } else { payloadOptions.push({ eventOptionId: key, quantity: qty }); } } if (payloadOptions.length === 0) { setEditError('Please select at least one item'); return; } // Enforce client-side: do not reduce below paid const paid = activeBill?.totalPaid || 0; if (editTotal < paid) { setEditError('Cannot reduce items below the amount already paid'); return; } setLoading(true); try { await apiV2Data("put", "/registrations/{id}/items", { params: { id: activeReg.id }, authToken: token, body: { options: payloadOptions }, }); // Reload registrations to reflect changes const myRegs = await (apiV2Data("get", "/me/registrations/full", { query: { past: showPast ? "true" : "false" }, authToken: token }) as Promise); setRegistrations(myRegs); try { const myTicks = await (apiV2Data("get", "/me/tickets", { authToken: token }) as Promise); setTickets(myTicks); } catch {} // Recompute billing totals using the backend's tranche-aware totalDueComputed const totals: Record = {}; for (const r of myRegs) { const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + registrationOptionUnitPrice(opt, null, new Date()) * (opt.quantity || 0), 0); totals[r.id] = { totalDue, totalPaid: 0, outstanding: totalDue, payments: [] }; } setBilling(totals); // Payments will be refreshed lazily or on next open; fetch for this one immediately try { const pays = await (apiV2Data("get", "/registrations/{id}/payments", { params: { id: activeReg.id }, authToken: token }) as Promise); const totalPaid = pays.reduce((s, p) => s + (p.amount || 0), 0); const totalDue = totals[activeReg.id]?.totalDue ?? 0; setBilling(prev => ({ ...prev, [activeReg.id]: { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid), payments: pays, } })); } catch {} setInfo('Registration updated successfully'); setEditMode(false); } catch (e) { setEditError(errorMessage(e) || 'Failed to update registration'); } finally { setLoading(false); } }; const router = useRouter(); return (

Welcome{user ? `, ${user.name}` : ""} 👋

Here's what's happening with your events.

{online.available && ( )}
{error &&

{error}

} {info &&

{info}

} {loading &&

Loading…

}

My Registrations

Click on a registration to edit or make a payment

{registrations.length === 0 ? (

No registrations yet.

) : (
    {registrations // Hide cancelled always; hide past unless showPast .filter((r) => r.status !== 'cancelled') .filter((r) => showPast || !isEventOver(r.event)) .map((r) => { const bill = billing[r.id]; const isCancelled = r.status === 'cancelled'; const outstanding = isCancelled ? 0 : (bill?.outstanding ?? 0); const totalDue = bill?.totalDue ?? 0; return (
  • setActiveRegId(r.id)} >
    {r.event?.title || r.eventId}
    {r.event?.startDate && (
    {formatDate(new Date(r.event.startDate))}
    )}
    Status:
    {(() => { const fs = formStatuses[r.id]; if (!fs || !fs.hasForm) return null; const label = fs.complete ? 'Complete' : 'Incomplete'; const colorClass = fs.complete ? 'bg-green-100 text-green-800' : (fs.isRequired ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800'); return (
    Forms: {label}
    ); })()} {(() => { if (r.status == 'paid') return null; // Early-bird notice: only for events with tiers that haven't passed const allTiers = (r.registrationOptions || []).flatMap((ro) => Array.isArray(ro.eventOption?.earlyBirdTiers) ? ro.eventOption.earlyBirdTiers : []); const upcoming = allTiers .map((t) => ({ ...t, deadline: new Date(t.deadline) })) .filter((t) => new Date() < t.deadline) .sort((a, b) => a.deadline.getTime() - b.deadline.getTime()); if (upcoming.length === 0) return null; const nextDeadline = upcoming[0].deadline; const pays = (billing[r.id]?.payments || []); const lastPaymentAt = pays.length > 0 ? new Date(Math.max(...pays.map((p) => new Date(p.createdAt).getTime()))) : null; const now = new Date(); const priceNow = (r.registrationOptions || []).reduce((s, ro) => s + registrationOptionUnitPrice(ro, lastPaymentAt, now) * (ro.quantity || 0), 0); const afterPrice = (r.registrationOptions || []).reduce((s, ro) => s + registrationOptionUnitPrice(ro, lastPaymentAt, new Date(nextDeadline.getTime() + 1000)) * (ro.quantity || 0), 0); const dateStr = nextDeadline.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: '2-digit' }); if (afterPrice > priceNow) { return (
    Early bird: R {priceNow.toFixed(2)} if paid before {dateStr}. Price increases to R {afterPrice.toFixed(2)} thereafter.
    ); } return (
    Early bird pricing in effect until {dateStr}.
    ); })()}
    {isCancelled ? (
    No outstanding — registration cancelled
    ) : ( <>
    Outstanding: 0 ? "text-red-600" : "text-green-700"}>{formatRand(outstanding)}
    Total: {formatRand(totalDue)}
    )}
  • ); })}
)}
{token && (
)}

Upcoming Events

{upcomingEvents.length === 0 ? (

No upcoming events.

) : (
    {upcomingEvents.map(ev => (
  • {ev.title}
    {new Date(ev.startDate).toLocaleString()} - {new Date(ev.endDate).toLocaleString()}
    {user?.phoneNumber && ( )}
  • ))}
)}

My Tickets

{tickets.length > 0 && (
{user?.phoneNumber && ( )}
)}
{tickets.filter(t => showPast || !isEventOver(t.event)).length === 0 ? (

No tickets yet.

) : (
    {tickets .filter((t) => showPast || !isEventOver(t.event)) .map((t) => { const eventDate = t.event?.startDate ? new Date(t.event.startDate) : null; const optionName = t.registrationOption?.eventOption?.name || "Ticket"; const variantName = t.registrationOption?.variant?.name; const type = variantName ? `${optionName} — ${variantName}` : optionName; return (
  • {t.event?.title || t.eventId}
    {eventDate && {formatDate(eventDate)}}
    {type}
    {t.attendee?.name ? <>For: {t.attendee.name} : <>Qty: {t.quantity || 1}}
    {(t.attendee?.allocations || []).length > 0 && (
    {[...(t.attendee?.allocations || [])].sort((a, b) => (a.set?.order || 0) - (b.set?.order || 0)).map((a) => `${a.set.name}: ${a.group.name}`).join(" · ")}
    )} {t.userId && user?.id && t.userId !== user.id && t.user?.name && (
    Booked by {t.user.name}
    )}
    #{t.id.slice(0, 8)}
    {user?.phoneNumber && ( )} {(t.transferRequests || [])[0] && ( Waiting for {t.transferRequests?.[0]?.toName} to accept )} {canOfferTransfer(t, t.event) && ( )}
  • ); })}
)}
{transferTarget && token && ( setTransferTarget(null)} onDone={(msg) => { setTransferTarget(null); setInfo(msg); reloadAfterAttendees(); }} /> )} {activeReg && ( { setEditMode(false); setEditError(null); setShowCancelConfirm(false); setActiveRegId(null); }}>

{activeReg.event?.title || activeReg.eventId}

Status:
{activeBill && (
Total: {formatRand(activeBill.totalDue)}
Paid: {formatRand(activeBill.totalPaid)}
Outstanding: 0 ? "text-red-600" : "text-green-700"}>{formatRand(activeBill.outstanding)}
)}
Registration items {!editMode && canModifyActive && ( )}
{!editMode ? (() => { // A line can span multiple price tranches (e.g. tickets bought before // and after an early-bird tier expired, or across repeat registrations). // Merge tranches that share a name/price/tier into one row, then group // early-bird rows separately from standard-price rows so repeat purchases // of the same item don't show as a wall of near-duplicate lines. const rows: { key: string; label: string; quantity: number; unitPrice: number; isEarlyBird: boolean }[] = []; (activeReg.registrationOptions || []).forEach((opt) => { const variantLabel = opt.variant?.name ? ` (${opt.variant.name})` : ''; const label = `${opt.eventOption?.name || ''}${variantLabel}`; const tranches = Array.isArray(opt.tranches) && opt.tranches.length > 0 ? opt.tranches : [{ quantity: opt.quantity, priceSnapshot: (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) ? Number(opt.priceSnapshot) : (opt.variant?.price ?? opt.eventOption?.price ?? 0), appliedTierId: opt.appliedTierId, }]; tranches.forEach((t) => { const unitPrice = Number(t.priceSnapshot || 0); const isEarlyBird = !!t.appliedTierId; const key = `${label}__${isEarlyBird}__${unitPrice}`; const existing = rows.find(r => r.key === key); if (existing) { existing.quantity += (t.quantity || 0); } else { rows.push({ key, label, quantity: t.quantity || 0, unitPrice, isEarlyBird }); } }); }); const earlyBirdRows = rows.filter(r => r.isEarlyBird); const standardRows = rows.filter(r => !r.isEarlyBird); const showGroupLabels = earlyBirdRows.length > 0 && standardRows.length > 0; const renderGroup = (heading: string, groupRows: typeof rows) => groupRows.length > 0 && (
{showGroupLabels && (
{heading}
)}
    {groupRows.map(r => (
  • {r.label} x {r.quantity} — {formatRand(r.unitPrice * r.quantity)} {r.isEarlyBird && ( (early bird) )}
  • ))}
); const activeCoupon = (activeReg.couponRedemptions || [])[0]; return (
{renderGroup('Early bird', earlyBirdRows)} {renderGroup('Standard price', standardRows)} {Number(activeReg.discountTotal || 0) - Number(activeReg.bundleDiscount || 0) - Number(activeReg.complimentaryDiscount || 0) > 0.005 && (
Discount code{activeCoupon?.coupon?.code ? <> {activeCoupon.coupon.code} : null} — −{formatRand(Number(activeReg.discountTotal) - Number(activeReg.bundleDiscount || 0) - Number(activeReg.complimentaryDiscount || 0))}
)} {Number(activeReg.complimentaryDiscount || 0) > 0.005 && (
Complimentary — −{formatRand(Number(activeReg.complimentaryDiscount))}
)} {canModifyActive && activeBill && activeBill.outstanding > 0 && !activeCoupon && (
{ setCodeInput(e.target.value.toUpperCase()); setCodeError(null); }} placeholder="Have a discount code?" className="flex-1 min-w-0 border rounded px-2 py-1 text-sm font-mono uppercase" aria-label="Discount code" />
{codeError &&

{codeError}

}
)}
); })() : (
{editError &&

{editError}

} {editLoading ? (
Loading options…
) : ( <>
{editEventOptions.map((eo) => { const hasVariants = Array.isArray(eo.variants) && eo.variants.length > 0; const renderQtyInput = (key: string, label: string, unitPrice: number, stockLimit?: number, availableCount?: number) => { const qty = editQuantities[key] || 0; const minQty = editMinQty[key] || 0; const baseQty = editBaseQty[key] || 0; const maxQty = ((stockLimit ?? 0) > 0 && availableCount !== undefined) ? availableCount + baseQty : undefined; return (
{ let v = Math.max(minQty, parseInt(e.target.value || '0', 10) || 0); if (maxQty !== undefined) v = Math.min(v, maxQty); setEditQuantities(prev => ({ ...prev, [key]: v })); }} className="w-20 border rounded px-2 py-1 text-sm" />
); }; if (hasVariants) { const variants = (eo.variants || []).slice().sort((a, b) => (a.order || 0) - (b.order || 0)); return (
{eo.name}
    {variants.map((v) => { const key = `${eo.id}:${v.id}`; const minQty = editMinQty[key] || 0; const unitPrice = effectiveEventOptionUnitPrice(eo, v.id); return (
  • {v.name}
    {formatRand(unitPrice)}
    {minQty > 0 && (
    {minQty} already issued
    )}
    {renderQtyInput(key, `${eo.name} (${v.name})`, unitPrice, v.stockLimit, v.availableCount)}
  • ); })}
); } const key = eo.id; const minQty = editMinQty[key] || 0; const unitPrice = effectiveEventOptionUnitPrice(eo, null); return (
{eo.name}
{formatRand(unitPrice)}
{minQty > 0 && (
{minQty} already issued
)}
{renderQtyInput(key, eo.name, unitPrice, eo.stockLimit, eo.availableCount)}
); })}
{(() => { const paid = activeBill?.totalPaid || 0; const hasAnyQty = Object.values(editQuantities).some(q => q > 0); const invalid = editTotal < paid || !hasAnyQty; return ( <>
New total: {formatRand(editTotal)}
{paid > 0 &&
Paid: {formatRand(paid)}
} {invalid &&
Total cannot be below amount already paid and at least one item is required.
} ); })()}
)}
)}
{token && ( )} {activeBill && activeBill.payments.length > 0 && (
Payments
    {activeBill.payments.map((p) => (
  • {new Date(p.createdAt).toLocaleString()} — {formatRand(p.amount)} ({formatPaymentMethod(p.method)})
  • ))}
)}
{showFormsButton && ( )} {canModifyActive && activeBill && online.canPay(activeBill.outstanding) && ( )}
{canModifyActive && activeBill && activeBill.outstanding > 0 && online.reason(activeBill.outstanding) && (

{online.reason(activeBill.outstanding)}

)} {/* Cancel registration — only shown when no payments have been made and the event still permits changes */} {canModifyActive && activeReg.status !== 'cancelled' && (activeBill?.totalPaid ?? 0) === 0 && (
{!showCancelConfirm ? ( ) : (
Are you sure you want to cancel? This cannot be undone.
)}
)}
)} {channelPicker && ( setChannelPicker(null)} closeOnBackdrop >

Send {channelPicker.kind === 'invoice' ? 'invoice' : 'receipt'}

How would you like to receive it?

{user?.phoneNumber && ( )}
)} {dialog.open && ( { if (!dialog.loading) setDialog({ open: false, message: "", loading: false }); }} closeOnBackdrop >
{dialog.loading ? (
) : ( <>

{dialog.title || "Tickets sent"}

{dialog.message}

)}
)}
); }