diff --git a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx index 8557185..2ae89fc 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/at-the-door/page.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useEffect, useMemo, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { apiFetch } from "@/lib/api"; @@ -11,6 +11,15 @@ import { TransferTicketModal, canOfferTransfer } from "@/components/shared/Trans 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 type { Event, EventOption, Registration, Ticket as TicketRecord, UserSummary } from "@/types"; + +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"; @@ -32,7 +41,7 @@ const MODE_ICONS: Record = { // ─── Fuzzy search helpers ───────────────────────────────────────────────────── -function fuzzyFilterRegs(allRegs: any[], search: string): any[] { +function fuzzyFilterRegs(allRegs: Registration[], search: string): Registration[] { if (!search) return allRegs; if (search.length === 1) { const q = search.toLowerCase(); @@ -51,37 +60,24 @@ function fuzzyFilterRegs(allRegs: any[], search: string): any[] { // ─── Pricing helpers ───────────────────────────────────────────────────────── -function effectiveOptionUnit(opt: any): number { - const base = opt.price || 0; - const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t: any) => !t.variantId); - if (!tiers.length) return base; - const now = new Date(); - const hit = tiers - .map((t: any) => ({ ...t, deadline: new Date(t.deadline) })) - .filter((t: any) => now < t.deadline) - .sort((a: any, b: any) => a.deadline - b.deadline || (a.order || 0) - (b.order || 0) || a.price - b.price); - return hit.length ? hit[0].price : base; +// 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); } -function effectiveVariantUnit(opt: any, variant: any): number { - const base = variant.price !== null && variant.price !== undefined ? variant.price : opt.price || 0; - const allTiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []; - const vtiers = allTiers.filter((t: any) => t.variantId === variant.id); - const tiers = vtiers.length ? vtiers : allTiers.filter((t: any) => !t.variantId); - if (!tiers.length) return base; - const now = new Date(); - const hit = tiers - .map((t: any) => ({ ...t, deadline: new Date(t.deadline) })) - .filter((t: any) => now < t.deadline) - .sort((a: any, b: any) => a.deadline - b.deadline || (a.order || 0) - (b.order || 0) || a.price - b.price); - return hit.length ? hit[0].price : base; -} +const totalPaidOn = (r: Registration) => (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0); -function initQuantities(eventOptions: any[]): Record { +function initQuantities(eventOptions: EventOption[]): Record { const map: Record = {}; - (eventOptions || []).forEach((o: any) => { + (eventOptions || []).forEach((o) => { if ((o.variants || []).length > 0) { - (o.variants as any[]).forEach((v: any) => { map[`${o.id}::${v.id}`] = 0; }); + (o.variants || []).forEach((v) => { map[`${o.id}::${v.id}`] = 0; }); } else { map[o.id] = 0; } @@ -89,7 +85,7 @@ function initQuantities(eventOptions: any[]): Record { return map; } -function ticketLabel(t: any): string { +function ticketLabel(t: TicketRecord): string { const opt = t.registrationOption?.eventOption?.name || "Ticket"; const variant = t.registrationOption?.variant?.name; return variant ? `${opt} — ${variant}` : opt; @@ -98,12 +94,12 @@ function ticketLabel(t: any): string { export default function AtTheDoorPage() { const { user, loading, token } = useAuth(); const router = useRouter(); - const [events, setEvents] = useState([]); + const [events, setEvents] = useState([]); const [eventId, setEventId] = useState(""); - const [eventOptions, setEventOptions] = useState([]); + const [eventOptions, setEventOptions] = useState([]); const [showOptionsModal, setShowOptionsModal] = useState(false); - const [pendingUser, setPendingUser] = useState(null); + const [pendingUser, setPendingUser] = useState(null); const [doorCoupon, setDoorCoupon] = useState(null); const [doorAllowsNames, setDoorAllowsNames] = useState(false); const [doorYouthStart, setDoorYouthStart] = useState(null); @@ -111,7 +107,7 @@ export default function AtTheDoorPage() { const [doorNaming, setDoorNaming] = useState(false); const [doorEntries, setDoorEntries] = useState({}); const [doorDelivery, setDoorDelivery] = useState("payer"); - const [pendingEditReg, setPendingEditReg] = useState(null); + 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 @@ -120,7 +116,7 @@ export default function AtTheDoorPage() { const [minQuantities, setMinQuantities] = useState>({}); const [showDonationModal, setShowDonationModal] = useState(false); - const [donationUser, setDonationUser] = useState(null); + const [donationUser, setDonationUser] = useState(null); const [showNewAttendeeModal, setShowNewAttendeeModal] = useState(false); const [newAttendeeSeed, setNewAttendeeSeed] = useState(""); @@ -129,7 +125,7 @@ export default function AtTheDoorPage() { if (!token) return; (async () => { try { - const evs = await apiFetch("/api/events/all", { authToken: token }); + const evs = await apiFetch("/api/events/all", { authToken: token }); const now = Date.now(); const active = (evs || []).filter(ev => { @@ -159,7 +155,7 @@ export default function AtTheDoorPage() { (async () => { try { - const ev = await apiFetch(`/api/events/${eventId}`, { + const ev = await apiFetch(`/api/events/${eventId}`, { authToken: token }); @@ -181,19 +177,19 @@ export default function AtTheDoorPage() { useEffect(() => { if (loading) return; if (!user) router.replace("/login"); - }, [user, loading]); + }, [user, loading, router]); const [mode, setMode] = useState("registration"); - const [activeRegistration, setActiveRegistration] = useState(null); + const [activeRegistration, setActiveRegistration] = useState(null); const [info, setInfo] = useDismissingState(null); const [error, setError] = useDismissingState(null); - const handleRegistrationCreated = (registration: any) => { + const handleRegistrationCreated = (registration: Registration) => { setActiveRegistration(registration); // 🚀 Jump automatically (see effect below) }; - const handleRegistrationSelected = (registration: any) => { + const handleRegistrationSelected = (registration: Registration) => { setActiveRegistration(registration); }; @@ -228,8 +224,8 @@ export default function AtTheDoorPage() { 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: any) => o.id === eventOptionId); - const variant = variantId ? (opt?.variants || []).find((v: any) => v.id === variantId) : null; + 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; @@ -245,7 +241,7 @@ export default function AtTheDoorPage() { try { if (pendingEditReg) { // Edit existing registration — replace options via PUT - let res = await apiFetch(`/api/registrations/${pendingEditReg.id}/options`, { + let res = await apiFetch(`/api/registrations/${pendingEditReg.id}/options`, { method: "PUT", authToken: token, body: { options: opts } @@ -254,7 +250,7 @@ export default function AtTheDoorPage() { 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`, { + res = await apiFetch(`/api/registrations/${pendingEditReg.id}/coupon`, { method: "POST", authToken: token, body: { code: doorCoupon.code }, @@ -270,7 +266,7 @@ export default function AtTheDoorPage() { handleRegistrationSelected(res); } else if (pendingUser) { // New attendee - const res = await apiFetch("/api/registrations/manual", { + const res = await apiFetch("/api/registrations/manual", { method: "POST", authToken: token, body: { @@ -312,7 +308,7 @@ export default function AtTheDoorPage() { eventOptions.forEach(o => { if (!o.isMainTicket) return; if ((o.variants || []).length > 0) { - qtyMap[`${o.id}::${(o.variants as any[])[0].id}`] = 1; + qtyMap[`${o.id}::${(o.variants || [])[0].id}`] = 1; } else { qtyMap[o.id] = 1; } @@ -333,27 +329,27 @@ export default function AtTheDoorPage() { // 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: any) => { + const handleEditRegistration = async (reg: Registration) => { let freshReg = reg; try { - freshReg = await apiFetch(`/api/registrations/${reg.id}`, { authToken: token }); + 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); - const regOptions = freshReg.registrationOptions || freshReg.options || []; - regOptions.forEach((ro: any) => { + const regOptions = freshReg.registrationOptions || []; + 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: any) => { + regOptions.forEach((ro) => { const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId; - const issuedQty = (ro.tickets || []).reduce((s: number, t: any) => s + (t.quantity || 0), 0); + const issuedQty = (ro.tickets || []).reduce((s, t) => s + (t.quantity || 0), 0); if (issuedQty > 0) minQtyMap[key] = (minQtyMap[key] || 0) + issuedQty; }); @@ -365,7 +361,7 @@ export default function AtTheDoorPage() { setShowOptionsModal(true); }; - const handlePaymentCaptured = async (registration?: any, partial?: boolean) => { + const handlePaymentCaptured = async (registration?: Registration, partial?: boolean) => { if (partial && registration) { setActiveRegistration(registration); @@ -385,7 +381,7 @@ export default function AtTheDoorPage() { setMode("checkin"); }; - const handleDonation = (user?: any) => { + const handleDonation = (user?: UserSummary) => { setDonationUser(user || null); // null = anonymous setShowDonationModal(true); }; @@ -466,12 +462,10 @@ export default function AtTheDoorPage() { )} @@ -493,7 +487,7 @@ export default function AtTheDoorPage() { )} {mode === "refund" && ( - + )} s + (p.amount || 0), 0)} + totalPaid={pendingEditReg ? totalPaidOn(pendingEditReg) : 0} eventId={eventId} token={token} coupon={doorCoupon} @@ -538,9 +532,16 @@ export default function AtTheDoorPage() { ); } -function DoorRegistrationPanel({ token, eventId, onCreated, onSelected, onEditRegistration, onNewAttendee, onDonation, setError }: any) { +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 [allRegs, setAllRegs] = useState([]); const [loading, setLoading] = useState(false); // Load registrations for this event — once on mount/eventId change, then every 5 min @@ -551,7 +552,7 @@ function DoorRegistrationPanel({ token, eventId, onCreated, onSelected, onEditRe const load = async () => { try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); if (!cancelled) setAllRegs(regs || []); } catch { if (!cancelled) setAllRegs([]); @@ -577,7 +578,7 @@ function DoorRegistrationPanel({ token, eventId, onCreated, onSelected, onEditRe if (!token || !eventId) return; try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); setAllRegs(regs || []); } catch {} finally { setLoading(false); } }} @@ -645,7 +646,12 @@ function DoorRegistrationPanel({ token, eventId, onCreated, onSelected, onEditRe ); } -function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) { +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); @@ -660,23 +666,10 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) { ); } - const options = registration.options || registration.registrationOptions || []; - const payments = registration.payments || []; - // 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 = registration.totalDueComputed ?? options.reduce((sum: number, opt: any) => { - const price = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) - ? Number(opt.priceSnapshot) - : (opt.eventOption?.price ?? opt.price ?? 0); - const qty = opt.quantity || 0; - return sum + price * qty; - }, 0); - - const paidValue = payments.reduce( - (sum: number, p: any) => sum + (p.amount || 0), - 0 - ); + const totalValue = registrationTotal(registration); + const paidValue = totalPaidOn(registration); const balance = Math.max(0, totalValue - paidValue); @@ -699,26 +692,11 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) { } }); - const updated = await apiFetch(`/api/registrations/${registration.id}`, { + const updated = await apiFetch(`/api/registrations/${registration.id}`, { authToken: token }); - const updatedOptions = updated.options || updated.registrationOptions || []; - const updatedPayments = updated.payments || []; - - const totalValue = updated.totalDueComputed ?? updatedOptions.reduce((sum: number, opt: any) => { - const price = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) - ? Number(opt.priceSnapshot) - : (opt.eventOption?.price ?? opt.price ?? 0); - return sum + price * (opt.quantity || 0); - }, 0); - - const paidValue = updatedPayments.reduce( - (sum: number, p: any) => sum + (p.amount || 0), - 0 - ); - - const updatedBalance = Math.max(0, totalValue - paidValue); + const updatedBalance = Math.max(0, registrationTotal(updated) - totalPaidOn(updated)); if (updatedBalance === 0) { onSuccess(updated); // 🎯 ONLY NOW generate tickets @@ -850,11 +828,10 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) { token={token} registration={registration} maxRefund={paidValue} - onRefunded={(updated: any) => { + onRefunded={(updated) => { setShowRefund(false); onSuccess(updated, true); }} - setError={setError} /> setShowSendTickets(false)} token={token} registration={registration} - setError={setError} - setInfo={() => {}} /> ); } -function DoorTicketsPanel({ token, eventId }: any) { +function DoorTicketsPanel({ token, eventId }: { token: string | null; eventId: string }) { const [search, setSearch] = useState(""); - const [allTickets, setAllTickets] = useState([]); + const [allTickets, setAllTickets] = useState([]); const [loading, setLoading] = useState(false); - const [sendTarget, setSendTarget] = useState(null); - const [transferTarget, setTransferTarget] = useState(null); + 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(() => { @@ -883,8 +863,8 @@ function DoorTicketsPanel({ token, eventId }: any) { (async () => { try { setLoading(true); - const res = await apiFetch(`/api/tickets/event/${eventId}`, { authToken: token }); - setAllTickets(res?.tickets || res?.data || (Array.isArray(res) ? res : [])); + const res = await apiFetch(`/api/tickets/event/${eventId}`, { authToken: token }); + setAllTickets(ticketsFrom(res)); } catch { setAllTickets([]); } finally { @@ -917,8 +897,8 @@ function DoorTicketsPanel({ token, eventId }: any) { if (!token || !eventId) return; try { setLoading(true); - const res = await apiFetch(`/api/tickets/event/${eventId}`, { authToken: token }); - setAllTickets(res?.tickets || res?.data || (Array.isArray(res) ? res : [])); + const res = await apiFetch(`/api/tickets/event/${eventId}`, { authToken: token }); + setAllTickets(ticketsFrom(res)); } catch { setAllTickets([]); } finally { @@ -926,7 +906,7 @@ function DoorTicketsPanel({ token, eventId }: any) { } }; - const print = (ticket: any) => { + const print = (ticket: TicketRecord) => { const w = window.open("", "_blank"); if (!w) return; const eventTitle = ticket.event?.title || ticket.eventId || "Event"; @@ -1062,49 +1042,50 @@ function DoorTicketsPanel({ token, eventId }: any) { setTransferTarget(null)} onDone={(msg) => { setTransferTarget(null); setNotice(msg); load(); }} /> )} - {sendTarget && ( + {sendRegistration && ( setSendTarget(null)} token={token} - registration={{ - id: sendTarget.registrationOption?.registration?.id || sendTarget.registrationOption?.registrationId, - user: sendTarget.user, - }} - setError={() => {}} - setInfo={() => {}} + registration={sendRegistration} /> )} ); } -function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: any) { - const [ticketsForEvent, setTicketsForEvent] = useState([]); +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 = async () => { + const load = useCallback(async () => { if (!token || !eventId) return; try { setLoading(true); - const res = await apiFetch(`/api/tickets/event/${eventId}`, { authToken: token }); - const tickets = res?.tickets || res?.data || (Array.isArray(res) ? res : []); - setTicketsForEvent(tickets.filter((t: any) => t.registrationOption?.eventOption?.isMainTicket)); + 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(); }, [token, eventId]); + useEffect(() => { load(); }, [load]); if (!registration) { return ( @@ -1117,25 +1098,26 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: a const myTickets = ticketsForEvent .filter(t => t.registrationOption?.registration?.id === registration.id) .map(t => { - const totalRedeemed = (t.usages || []).reduce((s: number, u: any) => s + (u.quantityRedeemed || 1), 0); + const totalRedeemed = (t.usages || []).reduce((s, u) => s + (u.quantityRedeemed || 1), 0); const remaining = (t.quantity || 1) - totalRedeemed; return { ...t, totalRedeemed, remaining }; }); - const qtyFor = (t: any) => qtyByTicket[t.id] ?? (t.remaining > 0 ? t.remaining : 1); - const setQtyFor = (t: any, n: number) => + 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: any) => { + const commit = async (ticket: CheckInTicket) => { const qty = qtyFor(ticket); try { setSubmittingId(ticket.id); - const res = await apiFetch( + const res = await apiFetch<{ qtyRedeemed?: number; remaining?: number }>( `/api/tickets/scan/${encodeURIComponent(ticket.qrCode)}?eventId=${encodeURIComponent(eventId)}`, { method: "POST", authToken: token, body: { qty } } ); setInfo(`${res?.qtyRedeemed ?? qty} checked in for ${registration.user?.name || "guest"}${ - res?.remaining > 0 ? ` — ${res.remaining} remaining` : " — fully checked in" + (res?.remaining ?? 0) > 0 ? ` — ${res.remaining} remaining` : " — fully checked in" }. Confirmation sent.`); await load(); } catch (e) { @@ -1226,33 +1208,54 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: a ); } -function OptionsModal({ open, onClose, options, quantities, setQuantities, minQuantities = {}, onConfirm, confirming, isEdit, totalPaid = 0, eventId, token, coupon, setCoupon, couponForUserId, existingCode, names }: any) { +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; + // Named-attendee editor settings, or null when the event doesn't take names. + names: Omit, "options" | "qtyFor" | "payerLabel"> | null; +}; + +function OptionsModal({ open, onClose, options, quantities, setQuantities, minQuantities = {}, onConfirm, confirming, isEdit, totalPaid = 0, eventId, token, coupon, setCoupon, couponForUserId, existingCode, names }: OptionsModalProps) { if (!open) return null; - const basket = Object.entries(quantities as Record) + const basket = Object.entries(quantities) .filter(([, qty]) => qty > 0) .map(([key, quantity]) => { const [eventOptionId, variantId] = key.split("::"); return { eventOptionId, quantity, variantId: variantId || null }; }); - const safeOptions: any[] = options || []; + const safeOptions: EventOption[] = options || []; - const total = safeOptions.reduce((sum: number, o: any) => { + const total = safeOptions.reduce((sum, o) => { if ((o.variants || []).length > 0) { - return sum + (o.variants as any[]).reduce((vs: number, v: any) => - vs + (quantities[`${o.id}::${v.id}`] || 0) * effectiveVariantUnit(o, v), 0); + return sum + (o.variants || []).reduce((vs, v) => + vs + (quantities[`${o.id}::${v.id}`] || 0) * variantUnitNow(o, v), 0); } - return sum + (quantities[o.id] || 0) * effectiveOptionUnit(o); + return sum + (quantities[o.id] || 0) * optionUnitNow(o); }, 0); const belowPaid = isEdit && total < totalPaid; const belowIssued = isEdit && Object.entries(minQuantities).some( - ([key, minQty]: [string, any]) => minQty > 0 && (quantities[key] || 0) < minQty + ([key, minQty]) => minQty > 0 && (quantities[key] || 0) < minQty ); const stepper = (key: string, delta: number) => - setQuantities((q: Record) => ({ ...q, [key]: Math.max(minQuantities[key] || 0, (q[key] || 0) + delta) })); + setQuantities((q) => ({ ...q, [key]: Math.max(minQuantities[key] || 0, (q[key] || 0) + delta) })); return (
@@ -1272,7 +1275,7 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu {/* Scrollable Content */}
- {safeOptions.map((opt: any) => { + {safeOptions.map((opt) => { const hasVariants = (opt.variants || []).length > 0; if (hasVariants) { return ( @@ -1281,8 +1284,8 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu {opt.name} {opt.isMainTicket && • Main}
- {(opt.variants as any[]).map((v: any) => { - const unit = effectiveVariantUnit(opt, v); + {(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; @@ -1307,7 +1310,7 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
); } - const unit = effectiveOptionUnit(opt); + const unit = optionUnitNow(opt); const minQty = minQuantities[opt.id] || 0; return (
@@ -1387,7 +1390,15 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu ); } -function DonationModal({ open, onClose, user, token, eventId, onSuccess, setError }: any) { +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); @@ -1481,7 +1492,12 @@ function DonationModal({ open, onClose, user, token, eventId, onSuccess, setErro ); } -function SendTicketsModal({ open, onClose, token, registration, setError, setInfo }: any) { +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(""); @@ -1496,7 +1512,7 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf setLocalError(""); setLocalInfo(""); } - }, [open, registration]); + }, [open, registration, setLocalError]); if (!open) return null; @@ -1516,7 +1532,7 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf method: "POST", authToken: token, body: { - registrationId: registration.id, + registrationId: registration?.id, channel, overrideEmail: email.trim() || undefined, overridePhone: phone.trim() || undefined, @@ -1610,7 +1626,14 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf ); } -function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded, setError }: any) { +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(""); @@ -1619,9 +1642,9 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded useEffect(() => { if (open) { setAmount(""); setReason(""); setLocalError(""); } - }, [open]); + }, [open, setLocalError]); - if (!open) return null; + if (!open || !registration) return null; const save = async (e: React.FormEvent) => { e.preventDefault(); @@ -1644,7 +1667,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded } }); // Re-fetch registration to get updated status & payments - const updated = await apiFetch(`/api/registrations/${registration.id}`, { authToken: token }); + const updated = await apiFetch(`/api/registrations/${registration.id}`, { authToken: token }); onRefunded(updated); } catch (e) { setLocalError(errorMessage(e) || "Refund failed."); @@ -1730,48 +1753,48 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded ); } -function DoorRefundPanel({ token, eventId, setError, setInfo }: any) { +function DoorRefundPanel({ token, eventId, setInfo }: { + token: string | null; + eventId: string; + setInfo: (s: string | null) => void; +}) { const [search, setSearch] = useState(""); - const [allRegs, setAllRegs] = useState([]); + const [allRegs, setAllRegs] = useState([]); const [loading, setLoading] = useState(false); - const [selectedReg, setSelectedReg] = useState(null); + const [selectedReg, setSelectedReg] = useState(null); const [showRefund, setShowRefund] = useState(false); - const load = async () => { + const load = useCallback(async () => { if (!token || !eventId) return; try { setLoading(true); - const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); + const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }); setAllRegs(regs || []); } catch { setAllRegs([]); } finally { setLoading(false); } - }; + }, [token, eventId]); useEffect(() => { load(); - }, [token, eventId]); + }, [load]); // Only show registrations that have at least one payment - const paidRegs = allRegs.filter(r => - (r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0) > 0 - ); + const paidRegs = allRegs.filter(r => totalPaidOn(r) > 0); const results = fuzzyFilterRegs(paidRegs, search); - const handleRefunded = async (updated: any) => { + 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); + const regs = await apiFetch(`/api/registrations/event/${eventId}`, { authToken: token }).catch(() => null); if (regs) setAllRegs(regs); }; - const maxRefund = selectedReg - ? (selectedReg.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0) - : 0; + const maxRefund = selectedReg ? totalPaidOn(selectedReg) : 0; return (
@@ -1797,7 +1820,7 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
{results.map(r => { - const paidValue = (r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0); + const paidValue = totalPaidOn(r); return (
@@ -1846,12 +1869,7 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
TOTAL
- R {(selectedReg.totalDueComputed ?? (selectedReg.options || selectedReg.registrationOptions || []).reduce((s: number, o: any) => { - const price = o.priceSnapshot !== null && o.priceSnapshot !== undefined - ? Number(o.priceSnapshot) - : (o.eventOption?.price || o.price || 0); - return s + price * (o.quantity || 0); - }, 0)).toFixed(2)} + R {registrationTotal(selectedReg).toFixed(2)}
@@ -1864,11 +1882,12 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
Payment history
- {selectedReg.payments.map((p: any, i: number) => ( + {(selectedReg.payments || []).map((p, i) => (
{p.amount < 0 ? "Refund" : "Payment"} — {p.method || "—"} - {p.reason ? ` (${p.reason})` : ""} + {/* A refund's reason is stored in its status field. */} + {p.amount < 0 && p.status ? ` (${p.status})` : ""} R {Number(p.amount).toFixed(2)} @@ -1902,7 +1921,6 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) { registration={selectedReg} maxRefund={maxRefund} onRefunded={handleRefunded} - setError={setError} />
); diff --git a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx index 4e23a95..a949fad 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/manual/page.tsx @@ -10,35 +10,11 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor"; import { UserPlus, CreditCard } from "lucide-react"; import { errorMessage } from "@/lib/utils"; -import type { EarlyBirdTier, Event, EventOption, OptionVariant, Registration, RegistrationOption, User } from "@/types"; +import { optionUnitNow, variantUnitNow } from "@/lib/pricing"; +import type { Event, EventOption, Registration, RegistrationOption, User } from "@/types"; // ─── Pricing helpers ───────────────────────────────────────────────────────── -// The earliest-deadline tier that's still open, or undefined when none are. -function currentTier(tiers: EarlyBirdTier[]): EarlyBirdTier | undefined { - const now = new Date(); - return tiers - .map((t) => ({ ...t, deadlineAt: new Date(t.deadline) })) - .filter((t) => now < t.deadlineAt) - .sort((a, b) => a.deadlineAt.getTime() - b.deadlineAt.getTime() || (a.order || 0) - (b.order || 0) || a.price - b.price)[0]; -} - -function effectiveOptionUnit(opt: EventOption): number { - const base = opt.price || 0; - const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t) => !t.variantId); - if (tiers.length === 0) return base; - return currentTier(tiers)?.price ?? base; -} - -function effectiveVariantUnit(opt: EventOption, variant: OptionVariant): number { - const base = variant.price !== null && variant.price !== undefined ? variant.price : opt.price || 0; - const allTiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []; - const variantTiers = allTiers.filter((t) => t.variantId === variant.id); - const tiers = variantTiers.length > 0 ? variantTiers : allTiers.filter((t) => !t.variantId); - if (tiers.length === 0) return base; - return currentTier(tiers)?.price ?? base; -} - function fmtPrice(n: number) { return n === 0 ? "Free" : `R ${n.toFixed(2)}`; } @@ -52,8 +28,8 @@ function optionUnitPrice(opt: RegistrationOption): number { } const eo = opt.eventOption; if (!eo) return 0; - if (opt.variant) return effectiveVariantUnit(eo, opt.variant); - return effectiveOptionUnit(eo); + if (opt.variant) return variantUnitNow(eo, opt.variant); + return optionUnitNow(eo); } // ─── Component ─────────────────────────────────────────────────────────────── @@ -292,9 +268,9 @@ export default function ManualRegistrationPage() { 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) * effectiveVariantUnit(o, v), 0); + return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * variantUnitNow(o, v), 0); } - return sum + (quantities[o.id] || 0) * effectiveOptionUnit(o); + return sum + (quantities[o.id] || 0) * optionUnitNow(o); }, 0); }, [options, quantities]); @@ -561,7 +537,7 @@ export default function ManualRegistrationPage() { {opt.name}{opt.isMainTicket ? • Main : null}
{(opt.variants || []).map((v) => { - const unit = effectiveVariantUnit(opt, 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 ( @@ -588,7 +564,7 @@ export default function ManualRegistrationPage() {
); } - const unit = effectiveOptionUnit(opt); + const unit = optionUnitNow(opt); return (
{opt.name}
diff --git a/apps/events/frontend/src/lib/pricing.ts b/apps/events/frontend/src/lib/pricing.ts index a815471..7fb7b7b 100644 --- a/apps/events/frontend/src/lib/pricing.ts +++ b/apps/events/frontend/src/lib/pricing.ts @@ -1,4 +1,4 @@ -import type { RegistrationOption } from "@/types"; +import type { EarlyBirdTier, EventOption, OptionVariant, RegistrationOption } from "@/types"; // Effective unit price for a registration option. Uses priceSnapshot when available // (authoritative backend price, variant-aware). Falls back to a deadline-only early-bird @@ -30,3 +30,30 @@ export function registrationOptionUnitPrice(opt: RegistrationOption, referenceTi const price = Number(applicable[0].price); return (price >= 0) ? price : base; } + +// The earliest-deadline early-bird tier that's still open, or undefined when none are. +function currentTier(tiers: EarlyBirdTier[]): EarlyBirdTier | undefined { + const now = new Date(); + return tiers + .map((t) => ({ ...t, deadlineAt: new Date(t.deadline) })) + .filter((t) => now < t.deadlineAt) + .sort((a, b) => a.deadlineAt.getTime() - b.deadlineAt.getTime() || (a.order || 0) - (b.order || 0) || a.price - b.price)[0]; +} + +// What an event option costs right now: its current early-bird price, else its base price. +export function optionUnitNow(opt: EventOption): number { + const base = opt.price || 0; + const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t) => !t.variantId); + if (tiers.length === 0) return base; + return currentTier(tiers)?.price ?? base; +} + +// Same for a variant: its own tiers if it has any, otherwise the option's. +export function variantUnitNow(opt: EventOption, variant: OptionVariant): number { + const base = variant.price !== null && variant.price !== undefined ? variant.price : opt.price || 0; + const allTiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []; + const variantTiers = allTiers.filter((t) => t.variantId === variant.id); + const tiers = variantTiers.length > 0 ? variantTiers : allTiers.filter((t) => !t.variantId); + if (tiers.length === 0) return base; + return currentTier(tiers)?.price ?? base; +} diff --git a/apps/events/frontend/src/types/index.ts b/apps/events/frontend/src/types/index.ts index ab806e7..ad7dffd 100644 --- a/apps/events/frontend/src/types/index.ts +++ b/apps/events/frontend/src/types/index.ts @@ -271,6 +271,8 @@ export type RegistrationOption = { variant?: OptionVariant | null; // One entry per price the line was bought at (e.g. some before an early-bird tier expired). tranches?: { id: string; quantity: number; priceSnapshot: number; appliedTierId?: string | null }[]; + tickets?: { id: string; quantity?: number }[]; + registration?: Registration; }; // A named person on a group registration, for one main-ticket place.