"use client"; import React, { useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { fetchAllUsers, fetchManagedEvents, fetchEvent, fetchAllRegistrations } 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 { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor"; import { UserPlus, CreditCard } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import { optionUnitNow, variantUnitNow } from "@/lib/pricing"; import { choosesSessions, isPickOption } from "@/lib/sessions"; import { SessionPicker } from "@/components/events/SessionPicker"; import type { Event, EventOption, PublicBundle, Registration, RegistrationOption, User } from "@/types"; 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 ───────────────────────────────────────────────────────── function fmtPrice(n: number) { return n === 0 ? "Free" : `R ${n.toFixed(2)}`; } // Effective unit price for an existing registration option (as returned by /api/v2/registrations). // Prefers priceSnapshot (authoritative price captured at registration time) and only falls // back to a live early-bird calculation for legacy rows without a snapshot. function optionUnitPrice(opt: RegistrationOption): number { if (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) { return Number(opt.priceSnapshot); } const eo = opt.eventOption; if (!eo) return 0; if (opt.variant) return variantUnitNow(eo, opt.variant); return optionUnitNow(eo); } // ─── Component ─────────────────────────────────────────────────────────────── export default function ManualRegistrationPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const canView = useMemo(() => { const role = user?.role; return role === "admin" || role === "supervisor"; }, [user]); useEffect(() => { if (loading) return; if (!user) router.replace("/login"); }, [user, loading, router]); const [events, setEvents] = useState([]); const [selectedEventId, setSelectedEventId] = useState(""); const [options, setOptions] = useState([]); // All system users for fuzzy lookup const [allUsers, setAllUsers] = useState([]); const [guest, setGuest] = useState({ name: "", email: "", phoneNumber: "" }); const [notifPref, setNotifPref] = useState<"email" | "whatsapp" | "both">("email"); const [quantities, setQuantities] = useState>({}); const [bundles, setBundles] = useState([]); // User search state const [userQuery, setUserQuery] = useState(""); const [dropdownOpen, setDropdownOpen] = useState(false); const searchRef = useRef(null); const [submitting, setSubmitting] = useState(false); const [message, setMessage] = useDismissingState(null); const [error, setError] = useDismissingState(null); // ── Tabs ────────────────────────────────────────────────────────────────── const [tab, setTab] = useState<"register" | "payment">("register"); // ── Record Payment tab state ───────────────────────────────────────────── const [allRegistrations, setAllRegistrations] = useState([]); const [payUserId, setPayUserId] = useState(""); const [payUserQuery, setPayUserQuery] = useState(""); const [payDropdownOpen, setPayDropdownOpen] = useState(false); const paySearchRef = useRef(null); const [payRegistrationId, setPayRegistrationId] = useState(""); const [payAmount, setPayAmount] = useState(""); const [payMethod, setPayMethod] = useState("cash"); const [payPaidAtLocal, setPayPaidAtLocal] = useState(""); const [paySubmitting, setPaySubmitting] = useState(false); const [payMessage, setPayMessage] = useDismissingState(null); const [payError, setPayError] = useDismissingState(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(eventId, { authToken: token || undefined }); setFormPrompt({ registrationId, needed, form: ev?.form, name }); } catch {} }; // Load all users for client-side fuzzy matching useEffect(() => { if (!token) return; fetchAllUsers(token) .then(users => setAllUsers(users)) .catch(() => {}); }, [token]); // Load all registrations for the Record Payment tab (embeds payments, so outstanding // balances can be computed without a per-registration fetch loop). useEffect(() => { if (!token) return; fetchAllRegistrations(token) .then(regs => setAllRegistrations(Array.isArray(regs) ? regs : [])) .catch(() => {}); }, [token]); const regOutstanding = useMemo(() => { const map: Record = {}; for (const r of allRegistrations) { const totalDue = r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => sum + optionUnitPrice(opt) * (opt.quantity || 0), 0); const totalPaid = (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0); map[r.id] = { totalDue, totalPaid, outstanding: Math.max(0, totalDue - totalPaid) }; } return map; }, [allRegistrations]); const payMatchedUsers = useMemo(() => { if (payUserQuery.trim().length < 2) return []; return allUsers .map(u => ({ u, score: scoreUser(u, payUserQuery) })) .filter(x => x.score >= 0.45) .sort((a, b) => b.score - a.score) .slice(0, 6) .map(x => x.u); }, [payUserQuery, allUsers]); const selectPayUser = (u: User) => { setPayUserId(u.id); setPayUserQuery(u.name || ""); setPayDropdownOpen(false); setPayRegistrationId(""); }; // Close payment-tab user dropdown on outside click useEffect(() => { const handler = (e: MouseEvent) => { if (paySearchRef.current && !paySearchRef.current.contains(e.target as Node)) { setPayDropdownOpen(false); } }; document.addEventListener("mousedown", handler); return () => document.removeEventListener("mousedown", handler); }, []); const regsForPayUser = useMemo(() => { if (!payUserId) return []; return allRegistrations .filter((r) => String(r.userId || r.user?.id) === String(payUserId)) .filter((r) => (regOutstanding[r.id]?.outstanding ?? 0) > 0.000001) .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); }, [allRegistrations, payUserId, regOutstanding]); const createManualPayment = async () => { if (!token) return; setPayError(null); setPayMessage(null); const amt = parseFloat(payAmount || "0"); if (!amt || amt <= 0) { setPayError("Enter a valid amount"); return; } if (!payRegistrationId) { setPayError("Please select a registration"); return; } try { setPaySubmitting(true); const paid = await (apiV2Data("post", "/payments", { authToken: token, body: { amount: amt, method: payMethod, userId: payUserId || undefined, registrationId: payRegistrationId, isDonation: false, paidAt: payPaidAtLocal ? new Date(payPaidAtLocal).toISOString() : undefined, }, }) 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 try { const regs = await fetchAllRegistrations(token); setAllRegistrations(Array.isArray(regs) ? regs : []); } catch {} } catch (e) { setPayError(errorMessage(e) || "Failed to record payment"); } finally { setPaySubmitting(false); } }; // Fuzzy match results (top 6, score threshold 0.45) const matchedUsers = useMemo(() => { if (userQuery.trim().length < 2) return []; return allUsers .map(u => ({ u, score: scoreUser(u, userQuery) })) .filter(x => x.score >= 0.45) .sort((a, b) => b.score - a.score) .slice(0, 6) .map(x => x.u); }, [userQuery, allUsers]); // Discount code, checked against the picked account (or a walk-in when none is picked). const [coupon, setCoupon] = useState(null); // Named attendees (group tickets), when the event takes them. const [namingOthers, setNamingOthers] = useState(false); const [attendeeEntries, setAttendeeEntries] = useState({}); const [delivery, setDelivery] = useState("payer"); const manualQtyFor = (optionId: string, variantId: string | null) => quantities[variantId ? `${optionId}::${variantId}` : optionId] || 0; const selectedEv = events.find(ev => ev.id === selectedEventId); const selectedIsYouth = !!selectedEv?.requiresParentalConsent; const selectedEventAllowsNames = !!selectedEv?.allowNamedAttendees || selectedIsYouth; const [pickedUserId, setPickedUserId] = useState(null); const selectUser = (u: User) => { setPickedUserId(u.id || null); setGuest({ name: u.name || "", email: u.email || "", phoneNumber: u.phoneNumber || "" }); setUserQuery(u.name || ""); setDropdownOpen(false); }; // Close dropdown on outside click useEffect(() => { const handler = (e: MouseEvent) => { if (searchRef.current && !searchRef.current.contains(e.target as Node)) { setDropdownOpen(false); } }; document.addEventListener("mousedown", handler); return () => document.removeEventListener("mousedown", handler); }, []); useEffect(() => { (async () => { try { if (!token) return; const evs = await fetchManagedEvents(token); const now = Date.now(); const active = (evs || []).filter(ev => { const t = new Date(ev.endDate).getTime(); // Manual registration is rejected server-side for closed (cashed-up) events — // don't offer them here even in the rare case one is closed before it ends. return !isNaN(t) && t > now && ev.cashupStatus !== 'closed'; }); active.sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); setEvents(active); } catch { // ignore } })(); }, [token]); useEffect(() => { const ev = events.find(e => e.id === selectedEventId); if (ev) { const opts = ev.options || ev.eventOptions || []; setOptions(opts); const map: Record = {}; opts.forEach((o) => { if ((o.variants || []).length > 0) { (o.variants || []).forEach(v => { map[`${o.id}::${v.id}`] = 0; }); } else { map[o.id] = 0; } }); setQuantities(map); } else { setOptions([]); setQuantities({}); } }, [selectedEventId, events]); // The events list doesn't carry bundle deals or places per session; the single-event // response does. const [fullEvent, setFullEvent] = useState(null); useEffect(() => { if (!selectedEventId) { setBundles([]); setFullEvent(null); return; } let cancelled = false; fetchEvent(selectedEventId, { authToken: token || undefined }) .then(ev => { if (!cancelled) { setBundles(ev?.bundles || []); setFullEvent(ev || null); } }) .catch(() => { if (!cancelled) { setBundles([]); setFullEvent(null); } }); return () => { cancelled = true; }; }, [selectedEventId, token]); // "Pick sessions" options: the sessions chosen per quantity key. const [picks, setPicks] = useState>({}); useEffect(() => { setPicks({}); }, [selectedEventId]); const pickOpt = (optionId: string) => { const o = (fullEvent?.eventOptions || []).find(x => x.id === optionId); return fullEvent && o && isPickOption(fullEvent, o) ? o : null; }; // On a "pick sessions" event every ticket has sessions to tick; only pickOpt ones are charged per session. const choiceOpt = (optionId: string) => { const o = (fullEvent?.eventOptions || []).find(x => x.id === optionId); return fullEvent && o && choosesSessions(fullEvent) ? o : null; }; const times = (key: string) => (pickOpt(key.split("::")[0]) ? (picks[key] || []).length : 1); const picker = (key: string, optionId: string) => { const o = choiceOpt(optionId); if (!o || !fullEvent) return null; // The sessions show straight away; ticking one when the quantity is 0 makes it 1. const qty = quantities[key] || 0; return 0 ? picks[key] || [] : []} onChange={ids => { setPicks(p => ({ ...p, [key]: ids })); if (qty === 0 && ids.length > 0) setQuantities(q => ({ ...q, [key]: 1 })); }} />; }; const totalDue = useMemo(() => { return options.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); }, [options, quantities, picks, fullEvent]); // eslint-disable-line react-hooks/exhaustive-deps const basket = useMemo(() => Object.entries(quantities).map(([key, quantity]) => { const [eventOptionId, variantId] = key.split("::"); return { eventOptionId, quantity, variantId: variantId || null, ...(choiceOpt(eventOptionId) ? { sessionIds: picks[key] || [] } : {}) }; }), [quantities, picks, fullEvent]); // eslint-disable-line react-hooks/exhaustive-deps const bundleQuote = useBundleQuote({ eventId: selectedEventId, basket, token, forUserId: pickedUserId }); const payable = coupon ? coupon.total : bundleQuote ? bundleQuote.total : totalDue; const submit = async () => { if (!token) return; setError(null); setMessage(null); if (!selectedEventId) { setError("Please select an event."); return; } if (!guest.name || (!guest.email.trim() && !guest.phoneNumber.trim())) { setError("Guest name and at least one of email or phone are required."); return; } const opts = Object.entries(quantities) .filter(([, qty]) => qty > 0) .map(([key, quantity]) => { const [eventOptionId, variantId] = key.split("::"); return { eventOptionId, quantity, ...(variantId ? { variantId } : {}), ...(choiceOpt(eventOptionId) ? { sessionIds: picks[key] || [] } : {}) }; }); if (opts.length === 0) { setError("Please select at least one ticket option."); return; } const noSessions = opts.find(o => "sessionIds" in o && o.sessionIds && o.sessionIds.length === 0); if (noSessions) { setError(`Choose the sessions for "${options.find(o => o.id === noSessions.eventOptionId)?.name || "the ticket"}".`); return; } if (selectedIsYouth) { const missing = consentDetailsMissing(options, manualQtyFor, attendeeEntries, selectedEv.startDate); if (missing) { setError(missing); return; } } try { setSubmitting(true); const hasEmail = !!guest.email.trim(); const hasPhone = !!guest.phoneNumber.trim(); const resolvedPref = hasEmail && hasPhone ? notifPref : hasPhone ? "whatsapp" : "email"; const res = await (apiV2Data("post", "/registrations/manual", { authToken: token, body: { eventId: selectedEventId, options: opts, user: guest, notificationPreference: resolvedPref, ...(coupon ? { couponCode: coupon.code } : {}), ...(selectedEventAllowsNames && (namingOthers || selectedIsYouth) && attendeesPayload(options, manualQtyFor, attendeeEntries).length > 0 ? { attendees: attendeesPayload(options, manualQtyFor, attendeeEntries), ticketDelivery: delivery } : {}), }, }) as Promise); 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. setAllRegistrations(prev => [res, ...prev.filter((r) => r.id !== res.id)]); setPayUserId(res.userId || res.user?.id || ""); setPayUserQuery(res.user?.name || guest.name || ""); setPayRegistrationId(res.id); setPayDropdownOpen(false); // Reset guest/ticket fields so the next registration starts from a clean slate setGuest({ name: "", email: "", phoneNumber: "" }); setNotifPref("email"); setUserQuery(""); setDropdownOpen(false); setCoupon(null); setPickedUserId(null); setNamingOthers(false); setAttendeeEntries({}); setDelivery("payer"); setQuantities(prev => Object.fromEntries(Object.keys(prev).map(k => [k, 0]))); } catch (e) { setError(errorMessage(e) || "Failed to create manual registration"); } finally { setSubmitting(false); } }; return (

Manual registration

{!canView && (
You need supervisor or admin access to use this page.
)}
{tab === 'register' && ( <> {message &&
{message}
} {error &&
{error}
}
1) Choose event
{selectedEventId && (
{(() => { const ev = events.find(e => e.id === selectedEventId); if (!ev) return null; return <>
{new Date(ev.startDate).toLocaleString()} - {new Date(ev.endDate).toLocaleString()}
; })()}
)}
2) Guest details
{/* ── User lookup ─────────────────────────────────────────── */}
{ setUserQuery(e.target.value); setDropdownOpen(true); }} onFocus={() => { if (userQuery.length >= 2) setDropdownOpen(true); }} /> {dropdownOpen && userQuery.trim().length >= 2 && (
{matchedUsers.length > 0 ? ( <>
{matchedUsers.length} match{matchedUsers.length !== 1 ? "es" : ""} — click to auto-fill
{matchedUsers.map(u => ( ))} ) : (
No matching users found — fill in details below manually.
)}
)}
setGuest({ ...guest, name: e.target.value })} /> setGuest({ ...guest, email: e.target.value })} /> { const v = e.target.value; setGuest({ ...guest, phoneNumber: v }); if (v.trim() && !guest.email.trim()) setNotifPref("whatsapp"); else if (!v.trim() && guest.email.trim()) setNotifPref("email"); }} /> {/* Preference selector */} {(() => { const hasEmail = !!guest.email.trim(); const hasPhone = !!guest.phoneNumber.trim(); if (!hasEmail && !hasPhone) return null; if (hasEmail && !hasPhone) return (

Tickets will be sent via email.

); if (hasPhone && !hasEmail) return (

Tickets will be sent via WhatsApp.

); return (
{(["email", "whatsapp", "both"] as const).map((p) => ( ))}
); })()} {guest.name && ( )}
3) Select ticket options
{options.length > 0 && } {options.length === 0 ? (
Select an event to view options.
) : (
{options.map(opt => { const hasVariants = (opt.variants || []).length > 0; if (hasVariants) { return (
{opt.name}{opt.isMainTicket ? • Main : null}
{(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}`; return (
{v.name}
{fmtPrice(unit)} {unit < basePrice && basePrice > 0 && (early bird, was {fmtPrice(basePrice)})}
setQuantities(q => ({ ...q, [key]: Math.max(0, parseInt(e.target.value || '0')) }))} />
{picker(key, opt.id) &&
{picker(key, opt.id)}
}
); })}
); } const unit = optionUnitNow(opt); return (
{opt.name}
{fmtPrice(unit)} {unit < opt.price && opt.price > 0 && (early bird, was {fmtPrice(opt.price)})} {opt.isMainTicket ? " • Main" : ""}
setQuantities(q => ({ ...q, [opt.id]: Math.max(0, parseInt(e.target.value || '0')) }))} />
{picker(opt.id, opt.id)}
); })}
)} quantities[v ? `${o}::${v}` : o] || 0} onSetQuantity={(o, v, n) => setQuantities(q => ({ ...q, [v ? `${o}::${v}` : o]: n }))} />
{selectedEventAllowsNames && (
)} {selectedEventId && totalDue > 0 && (
)}
Total due: R {payable.toFixed(2)} {payable < totalDue - 0.005 && R {totalDue.toFixed(2)}}
)} {tab === 'payment' && (
{payMessage &&
{payMessage}
} {payError &&
{payError}
}
Record a payment
setPayAmount(e.target.value)} />
{ setPayUserQuery(e.target.value); setPayDropdownOpen(true); if (!e.target.value) { setPayUserId(""); setPayRegistrationId(""); } }} onFocus={() => { if (payUserQuery.length >= 2) setPayDropdownOpen(true); }} /> {payDropdownOpen && payUserQuery.trim().length >= 2 && (
{payMatchedUsers.length > 0 ? ( <>
{payMatchedUsers.length} match{payMatchedUsers.length !== 1 ? "es" : ""}
{payMatchedUsers.map(u => ( ))} ) : (
No matching users found.
)}
)}
{!payUserId &&
Search for a user above to see their registrations.
}
setPayPaidAtLocal(e.target.value)} max={new Date().toISOString().slice(0,16)} />
Leave blank to use current time
)} {formPrompt && ( { 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); }} /> )}
); }