Type the at-the-door page and share pricing helpers

Each door panel and modal gets typed props; unused setError/setInfo/
onCreated props are dropped. The current early-bird price helpers move
to src/lib/pricing.ts (shared with manual registration), dead fallbacks
for a legacy registration 'options' field are removed, and the refund
history now shows a refund's reason (stored in its status field) instead
of a 'reason' field that never exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 11:10:01 +02:00
co-authored by Claude Opus 5.5
parent f6581eb441
commit 235da5bf61
4 changed files with 232 additions and 209 deletions
@@ -1,6 +1,6 @@
"use client"; "use client";
import React, { useEffect, useMemo, useState } from "react"; import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth"; import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api"; 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 { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react"; import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react";
import { errorMessage } from "@/lib/utils"; 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"; type Mode = "registration" | "payment" | "checkin" | "tickets" | "refund";
@@ -32,7 +41,7 @@ const MODE_ICONS: Record<Mode, LucideIcon> = {
// ─── Fuzzy search helpers ───────────────────────────────────────────────────── // ─── Fuzzy search helpers ─────────────────────────────────────────────────────
function fuzzyFilterRegs(allRegs: any[], search: string): any[] { function fuzzyFilterRegs(allRegs: Registration[], search: string): Registration[] {
if (!search) return allRegs; if (!search) return allRegs;
if (search.length === 1) { if (search.length === 1) {
const q = search.toLowerCase(); const q = search.toLowerCase();
@@ -51,37 +60,24 @@ function fuzzyFilterRegs(allRegs: any[], search: string): any[] {
// ─── Pricing helpers ───────────────────────────────────────────────────────── // ─── Pricing helpers ─────────────────────────────────────────────────────────
function effectiveOptionUnit(opt: any): number { // Total due on a registration: the backend's tranche-aware total when present, else
const base = opt.price || 0; // the sum of its lines at their snapshot (or current list) prices.
const tiers = (Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers : []).filter((t: any) => !t.variantId); function registrationTotal(r: Registration): number {
if (!tiers.length) return base; return r.totalDueComputed ?? (r.registrationOptions || []).reduce((sum, opt) => {
const now = new Date(); const price = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined)
const hit = tiers ? Number(opt.priceSnapshot)
.map((t: any) => ({ ...t, deadline: new Date(t.deadline) })) : (opt.eventOption?.price ?? 0);
.filter((t: any) => now < t.deadline) return sum + price * (opt.quantity || 0);
.sort((a: any, b: any) => a.deadline - b.deadline || (a.order || 0) - (b.order || 0) || a.price - b.price); }, 0);
return hit.length ? hit[0].price : base;
} }
function effectiveVariantUnit(opt: any, variant: any): number { const totalPaidOn = (r: Registration) => (r.payments || []).reduce((s, p) => s + (p.amount || 0), 0);
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;
}
function initQuantities(eventOptions: any[]): Record<string, number> { function initQuantities(eventOptions: EventOption[]): Record<string, number> {
const map: Record<string, number> = {}; const map: Record<string, number> = {};
(eventOptions || []).forEach((o: any) => { (eventOptions || []).forEach((o) => {
if ((o.variants || []).length > 0) { 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 { } else {
map[o.id] = 0; map[o.id] = 0;
} }
@@ -89,7 +85,7 @@ function initQuantities(eventOptions: any[]): Record<string, number> {
return map; return map;
} }
function ticketLabel(t: any): string { function ticketLabel(t: TicketRecord): string {
const opt = t.registrationOption?.eventOption?.name || "Ticket"; const opt = t.registrationOption?.eventOption?.name || "Ticket";
const variant = t.registrationOption?.variant?.name; const variant = t.registrationOption?.variant?.name;
return variant ? `${opt} — ${variant}` : opt; return variant ? `${opt} — ${variant}` : opt;
@@ -98,12 +94,12 @@ function ticketLabel(t: any): string {
export default function AtTheDoorPage() { export default function AtTheDoorPage() {
const { user, loading, token } = useAuth(); const { user, loading, token } = useAuth();
const router = useRouter(); const router = useRouter();
const [events, setEvents] = useState<any[]>([]); const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState(""); const [eventId, setEventId] = useState("");
const [eventOptions, setEventOptions] = useState<any[]>([]); const [eventOptions, setEventOptions] = useState<EventOption[]>([]);
const [showOptionsModal, setShowOptionsModal] = useState(false); const [showOptionsModal, setShowOptionsModal] = useState(false);
const [pendingUser, setPendingUser] = useState<any | null>(null); const [pendingUser, setPendingUser] = useState<NewAttendee | null>(null);
const [doorCoupon, setDoorCoupon] = useState<AppliedCoupon | null>(null); const [doorCoupon, setDoorCoupon] = useState<AppliedCoupon | null>(null);
const [doorAllowsNames, setDoorAllowsNames] = useState(false); const [doorAllowsNames, setDoorAllowsNames] = useState(false);
const [doorYouthStart, setDoorYouthStart] = useState<string | null>(null); const [doorYouthStart, setDoorYouthStart] = useState<string | null>(null);
@@ -111,7 +107,7 @@ export default function AtTheDoorPage() {
const [doorNaming, setDoorNaming] = useState(false); const [doorNaming, setDoorNaming] = useState(false);
const [doorEntries, setDoorEntries] = useState<AttendeeEntries>({}); const [doorEntries, setDoorEntries] = useState<AttendeeEntries>({});
const [doorDelivery, setDoorDelivery] = useState<TicketDelivery>("payer"); const [doorDelivery, setDoorDelivery] = useState<TicketDelivery>("payer");
const [pendingEditReg, setPendingEditReg] = useState<any | null>(null); const [pendingEditReg, setPendingEditReg] = useState<Registration | null>(null);
const [confirming, setConfirming] = useState(false); const [confirming, setConfirming] = useState(false);
const [quantities, setQuantities] = useState<Record<string, number>>({}); const [quantities, setQuantities] = useState<Record<string, number>>({});
// Already-issued ticket quantity per option/variant, keyed like `quantities` — a // Already-issued ticket quantity per option/variant, keyed like `quantities` — a
@@ -120,7 +116,7 @@ export default function AtTheDoorPage() {
const [minQuantities, setMinQuantities] = useState<Record<string, number>>({}); const [minQuantities, setMinQuantities] = useState<Record<string, number>>({});
const [showDonationModal, setShowDonationModal] = useState(false); const [showDonationModal, setShowDonationModal] = useState(false);
const [donationUser, setDonationUser] = useState<any | null>(null); const [donationUser, setDonationUser] = useState<UserSummary | null>(null);
const [showNewAttendeeModal, setShowNewAttendeeModal] = useState(false); const [showNewAttendeeModal, setShowNewAttendeeModal] = useState(false);
const [newAttendeeSeed, setNewAttendeeSeed] = useState(""); const [newAttendeeSeed, setNewAttendeeSeed] = useState("");
@@ -129,7 +125,7 @@ export default function AtTheDoorPage() {
if (!token) return; if (!token) return;
(async () => { (async () => {
try { try {
const evs = await apiFetch<any[]>("/api/events/all", { authToken: token }); const evs = await apiFetch<Event[]>("/api/events/all", { authToken: token });
const now = Date.now(); const now = Date.now();
const active = (evs || []).filter(ev => { const active = (evs || []).filter(ev => {
@@ -159,7 +155,7 @@ export default function AtTheDoorPage() {
(async () => { (async () => {
try { try {
const ev = await apiFetch(`/api/events/${eventId}`, { const ev = await apiFetch<Event>(`/api/events/${eventId}`, {
authToken: token authToken: token
}); });
@@ -181,19 +177,19 @@ export default function AtTheDoorPage() {
useEffect(() => { useEffect(() => {
if (loading) return; if (loading) return;
if (!user) router.replace("/login"); if (!user) router.replace("/login");
}, [user, loading]); }, [user, loading, router]);
const [mode, setMode] = useState<Mode>("registration"); const [mode, setMode] = useState<Mode>("registration");
const [activeRegistration, setActiveRegistration] = useState<any | null>(null); const [activeRegistration, setActiveRegistration] = useState<Registration | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null); const [info, setInfo] = useDismissingState<string | null>(null);
const [error, setError] = useDismissingState<string | null>(null); const [error, setError] = useDismissingState<string | null>(null);
const handleRegistrationCreated = (registration: any) => { const handleRegistrationCreated = (registration: Registration) => {
setActiveRegistration(registration); // 🚀 Jump automatically (see effect below) setActiveRegistration(registration); // 🚀 Jump automatically (see effect below)
}; };
const handleRegistrationSelected = (registration: any) => { const handleRegistrationSelected = (registration: Registration) => {
setActiveRegistration(registration); setActiveRegistration(registration);
}; };
@@ -228,8 +224,8 @@ export default function AtTheDoorPage() {
for (const [key, minQty] of Object.entries(minQuantities)) { for (const [key, minQty] of Object.entries(minQuantities)) {
if (minQty > 0 && (quantities[key] || 0) < minQty) { if (minQty > 0 && (quantities[key] || 0) < minQty) {
const [eventOptionId, variantId] = key.split("::"); const [eventOptionId, variantId] = key.split("::");
const opt = eventOptions.find((o: any) => o.id === eventOptionId); const opt = eventOptions.find((o) => o.id === eventOptionId);
const variant = variantId ? (opt?.variants || []).find((v: any) => v.id === variantId) : null; const variant = variantId ? (opt?.variants || []).find((v) => v.id === variantId) : null;
const label = variant ? `${opt?.name || "item"} (${variant.name})` : (opt?.name || "item"); const label = variant ? `${opt?.name || "item"} (${variant.name})` : (opt?.name || "item");
setError(`Cannot reduce "${label}" below the ${minQty} already issued`); setError(`Cannot reduce "${label}" below the ${minQty} already issued`);
return; return;
@@ -245,7 +241,7 @@ export default function AtTheDoorPage() {
try { try {
if (pendingEditReg) { if (pendingEditReg) {
// Edit existing registration — replace options via PUT // Edit existing registration — replace options via PUT
let res = await apiFetch(`/api/registrations/${pendingEditReg.id}/options`, { let res = await apiFetch<Registration>(`/api/registrations/${pendingEditReg.id}/options`, {
method: "PUT", method: "PUT",
authToken: token, authToken: token,
body: { options: opts } body: { options: opts }
@@ -254,7 +250,7 @@ export default function AtTheDoorPage() {
if (doorCoupon) { if (doorCoupon) {
// Applied after the items are saved, so it's worked out on the final items. // Applied after the items are saved, so it's worked out on the final items.
try { try {
res = await apiFetch(`/api/registrations/${pendingEditReg.id}/coupon`, { res = await apiFetch<Registration>(`/api/registrations/${pendingEditReg.id}/coupon`, {
method: "POST", method: "POST",
authToken: token, authToken: token,
body: { code: doorCoupon.code }, body: { code: doorCoupon.code },
@@ -270,7 +266,7 @@ export default function AtTheDoorPage() {
handleRegistrationSelected(res); handleRegistrationSelected(res);
} else if (pendingUser) { } else if (pendingUser) {
// New attendee // New attendee
const res = await apiFetch("/api/registrations/manual", { const res = await apiFetch<Registration & { couponError?: string }>("/api/registrations/manual", {
method: "POST", method: "POST",
authToken: token, authToken: token,
body: { body: {
@@ -312,7 +308,7 @@ export default function AtTheDoorPage() {
eventOptions.forEach(o => { eventOptions.forEach(o => {
if (!o.isMainTicket) return; if (!o.isMainTicket) return;
if ((o.variants || []).length > 0) { if ((o.variants || []).length > 0) {
qtyMap[`${o.id}::${(o.variants as any[])[0].id}`] = 1; qtyMap[`${o.id}::${(o.variants || [])[0].id}`] = 1;
} else { } else {
qtyMap[o.id] = 1; 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, // 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 // see DoorRegistrationPanel's polling interval) cached search-result snapshot, so the
// already-issued-ticket floor below is always computed from current data. // already-issued-ticket floor below is always computed from current data.
const handleEditRegistration = async (reg: any) => { const handleEditRegistration = async (reg: Registration) => {
let freshReg = reg; let freshReg = reg;
try { try {
freshReg = await apiFetch<any>(`/api/registrations/${reg.id}`, { authToken: token }); freshReg = await apiFetch<Registration>(`/api/registrations/${reg.id}`, { authToken: token });
} catch (e) { } catch (e) {
setError(errorMessage(e) || "Failed to load latest registration data"); setError(errorMessage(e) || "Failed to load latest registration data");
return; return;
} }
const qtyMap = initQuantities(eventOptions); const qtyMap = initQuantities(eventOptions);
const regOptions = freshReg.registrationOptions || freshReg.options || []; const regOptions = freshReg.registrationOptions || [];
regOptions.forEach((ro: any) => { regOptions.forEach((ro) => {
const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId; const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId;
if (key in qtyMap) qtyMap[key] = ro.quantity || 0; if (key in qtyMap) qtyMap[key] = ro.quantity || 0;
}); });
// Already-issued ticket quantity per option/variant — floor for the edit below // Already-issued ticket quantity per option/variant — floor for the edit below
const minQtyMap: Record<string, number> = {}; const minQtyMap: Record<string, number> = {};
regOptions.forEach((ro: any) => { regOptions.forEach((ro) => {
const key = ro.variantId ? `${ro.eventOptionId}::${ro.variantId}` : ro.eventOptionId; 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; if (issuedQty > 0) minQtyMap[key] = (minQtyMap[key] || 0) + issuedQty;
}); });
@@ -365,7 +361,7 @@ export default function AtTheDoorPage() {
setShowOptionsModal(true); setShowOptionsModal(true);
}; };
const handlePaymentCaptured = async (registration?: any, partial?: boolean) => { const handlePaymentCaptured = async (registration?: Registration, partial?: boolean) => {
if (partial && registration) { if (partial && registration) {
setActiveRegistration(registration); setActiveRegistration(registration);
@@ -385,7 +381,7 @@ export default function AtTheDoorPage() {
setMode("checkin"); setMode("checkin");
}; };
const handleDonation = (user?: any) => { const handleDonation = (user?: UserSummary) => {
setDonationUser(user || null); // null = anonymous setDonationUser(user || null); // null = anonymous
setShowDonationModal(true); setShowDonationModal(true);
}; };
@@ -466,12 +462,10 @@ export default function AtTheDoorPage() {
<DoorRegistrationPanel <DoorRegistrationPanel
token={token} token={token}
eventId={eventId} eventId={eventId}
onCreated={handleRegistrationCreated}
onSelected={handleRegistrationSelected} onSelected={handleRegistrationSelected}
onEditRegistration={handleEditRegistration} onEditRegistration={handleEditRegistration}
onNewAttendee={handleShowNewAttendee} onNewAttendee={handleShowNewAttendee}
onDonation={handleDonation} onDonation={handleDonation}
setError={setError}
/> />
)} )}
@@ -493,7 +487,7 @@ export default function AtTheDoorPage() {
)} )}
{mode === "refund" && ( {mode === "refund" && (
<DoorRefundPanel token={token} eventId={eventId} setError={setError} setInfo={setInfo} /> <DoorRefundPanel token={token} eventId={eventId} setInfo={setInfo} />
)} )}
<OptionsModal <OptionsModal
open={showOptionsModal} open={showOptionsModal}
@@ -505,7 +499,7 @@ export default function AtTheDoorPage() {
onConfirm={confirmRegistration} onConfirm={confirmRegistration}
confirming={confirming} confirming={confirming}
isEdit={!!pendingEditReg} isEdit={!!pendingEditReg}
totalPaid={(pendingEditReg?.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0)} totalPaid={pendingEditReg ? totalPaidOn(pendingEditReg) : 0}
eventId={eventId} eventId={eventId}
token={token} token={token}
coupon={doorCoupon} 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 [search, setSearch] = useState("");
const [allRegs, setAllRegs] = useState<any[]>([]); const [allRegs, setAllRegs] = useState<Registration[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
// Load registrations for this event — once on mount/eventId change, then every 5 min // 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 () => { const load = async () => {
try { try {
setLoading(true); setLoading(true);
const regs = await apiFetch<any[]>(`/api/registrations/event/${eventId}`, { authToken: token }); const regs = await apiFetch<Registration[]>(`/api/registrations/event/${eventId}`, { authToken: token });
if (!cancelled) setAllRegs(regs || []); if (!cancelled) setAllRegs(regs || []);
} catch { } catch {
if (!cancelled) setAllRegs([]); if (!cancelled) setAllRegs([]);
@@ -577,7 +578,7 @@ function DoorRegistrationPanel({ token, eventId, onCreated, onSelected, onEditRe
if (!token || !eventId) return; if (!token || !eventId) return;
try { try {
setLoading(true); setLoading(true);
const regs = await apiFetch<any[]>(`/api/registrations/event/${eventId}`, { authToken: token }); const regs = await apiFetch<Registration[]>(`/api/registrations/event/${eventId}`, { authToken: token });
setAllRegs(regs || []); setAllRegs(regs || []);
} catch {} finally { setLoading(false); } } 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 [amount, setAmount] = useState("");
const [method, setMethod] = useState("card"); const [method, setMethod] = useState("card");
const [saving, setSaving] = useState(false); 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 // 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. // multiple early-bird prices) — fall back to the old client-side estimate otherwise.
const totalValue = registration.totalDueComputed ?? options.reduce((sum: number, opt: any) => { const totalValue = registrationTotal(registration);
const price = (opt.priceSnapshot !== null && opt.priceSnapshot !== undefined) const paidValue = totalPaidOn(registration);
? 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 balance = Math.max(0, totalValue - paidValue); 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<Registration>(`/api/registrations/${registration.id}`, {
authToken: token authToken: token
}); });
const updatedOptions = updated.options || updated.registrationOptions || []; const updatedBalance = Math.max(0, registrationTotal(updated) - totalPaidOn(updated));
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);
if (updatedBalance === 0) { if (updatedBalance === 0) {
onSuccess(updated); // 🎯 ONLY NOW generate tickets onSuccess(updated); // 🎯 ONLY NOW generate tickets
@@ -850,11 +828,10 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) {
token={token} token={token}
registration={registration} registration={registration}
maxRefund={paidValue} maxRefund={paidValue}
onRefunded={(updated: any) => { onRefunded={(updated) => {
setShowRefund(false); setShowRefund(false);
onSuccess(updated, true); onSuccess(updated, true);
}} }}
setError={setError}
/> />
<SendTicketsModal <SendTicketsModal
@@ -862,20 +839,23 @@ function DoorPaymentPanel({ token, registration, onSuccess, setError }: any) {
onClose={() => setShowSendTickets(false)} onClose={() => setShowSendTickets(false)}
token={token} token={token}
registration={registration} registration={registration}
setError={setError}
setInfo={() => {}}
/> />
</div> </div>
); );
} }
function DoorTicketsPanel({ token, eventId }: any) { function DoorTicketsPanel({ token, eventId }: { token: string | null; eventId: string }) {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [allTickets, setAllTickets] = useState<any[]>([]); const [allTickets, setAllTickets] = useState<TicketRecord[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [sendTarget, setSendTarget] = useState<any | null>(null); const [sendTarget, setSendTarget] = useState<TicketRecord | null>(null);
const [transferTarget, setTransferTarget] = useState<any | null>(null); const [transferTarget, setTransferTarget] = useState<TicketRecord | null>(null);
const [notice, setNotice] = useState<string | null>(null); const [notice, setNotice] = useState<string | null>(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 // Load all tickets for the event once
useEffect(() => { useEffect(() => {
@@ -883,8 +863,8 @@ function DoorTicketsPanel({ token, eventId }: any) {
(async () => { (async () => {
try { try {
setLoading(true); setLoading(true);
const res = await apiFetch<any>(`/api/tickets/event/${eventId}`, { authToken: token }); const res = await apiFetch<EventTicketsResponse>(`/api/tickets/event/${eventId}`, { authToken: token });
setAllTickets(res?.tickets || res?.data || (Array.isArray(res) ? res : [])); setAllTickets(ticketsFrom(res));
} catch { } catch {
setAllTickets([]); setAllTickets([]);
} finally { } finally {
@@ -917,8 +897,8 @@ function DoorTicketsPanel({ token, eventId }: any) {
if (!token || !eventId) return; if (!token || !eventId) return;
try { try {
setLoading(true); setLoading(true);
const res = await apiFetch<any>(`/api/tickets/event/${eventId}`, { authToken: token }); const res = await apiFetch<EventTicketsResponse>(`/api/tickets/event/${eventId}`, { authToken: token });
setAllTickets(res?.tickets || res?.data || (Array.isArray(res) ? res : [])); setAllTickets(ticketsFrom(res));
} catch { } catch {
setAllTickets([]); setAllTickets([]);
} finally { } finally {
@@ -926,7 +906,7 @@ function DoorTicketsPanel({ token, eventId }: any) {
} }
}; };
const print = (ticket: any) => { const print = (ticket: TicketRecord) => {
const w = window.open("", "_blank"); const w = window.open("", "_blank");
if (!w) return; if (!w) return;
const eventTitle = ticket.event?.title || ticket.eventId || "Event"; const eventTitle = ticket.event?.title || ticket.eventId || "Event";
@@ -1062,49 +1042,50 @@ function DoorTicketsPanel({ token, eventId }: any) {
<TransferTicketModal <TransferTicketModal
ticket={transferTarget} ticket={transferTarget}
event={transferTarget.event} event={transferTarget.event}
token={token} token={token ?? ""}
onClose={() => setTransferTarget(null)} onClose={() => setTransferTarget(null)}
onDone={(msg) => { setTransferTarget(null); setNotice(msg); load(); }} onDone={(msg) => { setTransferTarget(null); setNotice(msg); load(); }}
/> />
)} )}
{sendTarget && ( {sendRegistration && (
<SendTicketsModal <SendTicketsModal
open={true} open={true}
onClose={() => setSendTarget(null)} onClose={() => setSendTarget(null)}
token={token} token={token}
registration={{ registration={sendRegistration}
id: sendTarget.registrationOption?.registration?.id || sendTarget.registrationOption?.registrationId,
user: sendTarget.user,
}}
setError={() => {}}
setInfo={() => {}}
/> />
)} )}
</div> </div>
); );
} }
function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: any) { function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: {
const [ticketsForEvent, setTicketsForEvent] = useState<any[]>([]); token: string | null;
eventId: string;
registration: Registration | null;
setError: (e: string | null) => void;
setInfo: (s: string | null) => void;
}) {
const [ticketsForEvent, setTicketsForEvent] = useState<TicketRecord[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [qtyByTicket, setQtyByTicket] = useState<Record<string, number>>({}); const [qtyByTicket, setQtyByTicket] = useState<Record<string, number>>({});
const [submittingId, setSubmittingId] = useState<string | null>(null); const [submittingId, setSubmittingId] = useState<string | null>(null);
const load = async () => { const load = useCallback(async () => {
if (!token || !eventId) return; if (!token || !eventId) return;
try { try {
setLoading(true); setLoading(true);
const res = await apiFetch<any>(`/api/tickets/event/${eventId}`, { authToken: token }); const res = await apiFetch<EventTicketsResponse>(`/api/tickets/event/${eventId}`, { authToken: token });
const tickets = res?.tickets || res?.data || (Array.isArray(res) ? res : []); const tickets = ticketsFrom(res);
setTicketsForEvent(tickets.filter((t: any) => t.registrationOption?.eventOption?.isMainTicket)); setTicketsForEvent(tickets.filter((t) => t.registrationOption?.eventOption?.isMainTicket));
} catch { } catch {
setTicketsForEvent([]); setTicketsForEvent([]);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; }, [token, eventId]);
useEffect(() => { load(); }, [token, eventId]); useEffect(() => { load(); }, [load]);
if (!registration) { if (!registration) {
return ( return (
@@ -1117,25 +1098,26 @@ function DoorCheckInPanel({ token, eventId, registration, setError, setInfo }: a
const myTickets = ticketsForEvent const myTickets = ticketsForEvent
.filter(t => t.registrationOption?.registration?.id === registration.id) .filter(t => t.registrationOption?.registration?.id === registration.id)
.map(t => { .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; const remaining = (t.quantity || 1) - totalRedeemed;
return { ...t, totalRedeemed, remaining }; return { ...t, totalRedeemed, remaining };
}); });
const qtyFor = (t: any) => qtyByTicket[t.id] ?? (t.remaining > 0 ? t.remaining : 1); type CheckInTicket = (typeof myTickets)[number];
const setQtyFor = (t: any, n: 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)) })); 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); const qty = qtyFor(ticket);
try { try {
setSubmittingId(ticket.id); setSubmittingId(ticket.id);
const res = await apiFetch<any>( const res = await apiFetch<{ qtyRedeemed?: number; remaining?: number }>(
`/api/tickets/scan/${encodeURIComponent(ticket.qrCode)}?eventId=${encodeURIComponent(eventId)}`, `/api/tickets/scan/${encodeURIComponent(ticket.qrCode)}?eventId=${encodeURIComponent(eventId)}`,
{ method: "POST", authToken: token, body: { qty } } { method: "POST", authToken: token, body: { qty } }
); );
setInfo(`${res?.qtyRedeemed ?? qty} checked in for ${registration.user?.name || "guest"}${ 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.`); }. Confirmation sent.`);
await load(); await load();
} catch (e) { } 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<string, number>;
setQuantities: React.Dispatch<React.SetStateAction<Record<string, number>>>;
minQuantities?: Record<string, number>;
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<React.ComponentProps<typeof AttendeeNamesEditor>, "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; if (!open) return null;
const basket = Object.entries(quantities as Record<string, number>) const basket = Object.entries(quantities)
.filter(([, qty]) => qty > 0) .filter(([, qty]) => qty > 0)
.map(([key, quantity]) => { .map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::"); const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null }; 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) { if ((o.variants || []).length > 0) {
return sum + (o.variants as any[]).reduce((vs: number, v: any) => return sum + (o.variants || []).reduce((vs, v) =>
vs + (quantities[`${o.id}::${v.id}`] || 0) * effectiveVariantUnit(o, v), 0); 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); }, 0);
const belowPaid = isEdit && total < totalPaid; const belowPaid = isEdit && total < totalPaid;
const belowIssued = isEdit && Object.entries(minQuantities).some( 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) => const stepper = (key: string, delta: number) =>
setQuantities((q: Record<string, number>) => ({ ...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 ( return (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"> <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
@@ -1272,7 +1275,7 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
{/* Scrollable Content */} {/* Scrollable Content */}
<div className="flex-1 overflow-y-auto overscroll-contain p-5 space-y-3"> <div className="flex-1 overflow-y-auto overscroll-contain p-5 space-y-3">
{safeOptions.map((opt: any) => { {safeOptions.map((opt) => {
const hasVariants = (opt.variants || []).length > 0; const hasVariants = (opt.variants || []).length > 0;
if (hasVariants) { if (hasVariants) {
return ( return (
@@ -1281,8 +1284,8 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
{opt.name} {opt.name}
{opt.isMainTicket && <span className="ml-1.5 text-xs text-brand-600 font-normal">• Main</span>} {opt.isMainTicket && <span className="ml-1.5 text-xs text-brand-600 font-normal">• Main</span>}
</div> </div>
{(opt.variants as any[]).map((v: any) => { {(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 basePrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const key = `${opt.id}::${v.id}`; const key = `${opt.id}::${v.id}`;
const minQty = minQuantities[key] || 0; const minQty = minQuantities[key] || 0;
@@ -1307,7 +1310,7 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
</div> </div>
); );
} }
const unit = effectiveOptionUnit(opt); const unit = optionUnitNow(opt);
const minQty = minQuantities[opt.id] || 0; const minQty = minQuantities[opt.id] || 0;
return ( return (
<div key={opt.id} className="border rounded-xl p-3"> <div key={opt.id} className="border rounded-xl p-3">
@@ -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 [amount, setAmount] = useState("");
const [method, setMethod] = useState("cash"); const [method, setMethod] = useState("cash");
const [saving, setSaving] = useState(false); 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<Registration, "id" | "user"> | null;
}) {
const [channel, setChannel] = useState<"email" | "whatsapp" | "both">("email"); const [channel, setChannel] = useState<"email" | "whatsapp" | "both">("email");
const [phone, setPhone] = useState(""); const [phone, setPhone] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@@ -1496,7 +1512,7 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf
setLocalError(""); setLocalError("");
setLocalInfo(""); setLocalInfo("");
} }
}, [open, registration]); }, [open, registration, setLocalError]);
if (!open) return null; if (!open) return null;
@@ -1516,7 +1532,7 @@ function SendTicketsModal({ open, onClose, token, registration, setError, setInf
method: "POST", method: "POST",
authToken: token, authToken: token,
body: { body: {
registrationId: registration.id, registrationId: registration?.id,
channel, channel,
overrideEmail: email.trim() || undefined, overrideEmail: email.trim() || undefined,
overridePhone: phone.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 [amount, setAmount] = useState("");
const [method, setMethod] = useState("cash"); const [method, setMethod] = useState("cash");
const [reason, setReason] = useState(""); const [reason, setReason] = useState("");
@@ -1619,9 +1642,9 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded
useEffect(() => { useEffect(() => {
if (open) { setAmount(""); setReason(""); setLocalError(""); } if (open) { setAmount(""); setReason(""); setLocalError(""); }
}, [open]); }, [open, setLocalError]);
if (!open) return null; if (!open || !registration) return null;
const save = async (e: React.FormEvent) => { const save = async (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
@@ -1644,7 +1667,7 @@ function RefundModal({ open, onClose, token, registration, maxRefund, onRefunded
} }
}); });
// Re-fetch registration to get updated status & payments // Re-fetch registration to get updated status & payments
const updated = await apiFetch<any>(`/api/registrations/${registration.id}`, { authToken: token }); const updated = await apiFetch<Registration>(`/api/registrations/${registration.id}`, { authToken: token });
onRefunded(updated); onRefunded(updated);
} catch (e) { } catch (e) {
setLocalError(errorMessage(e) || "Refund failed."); 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 [search, setSearch] = useState("");
const [allRegs, setAllRegs] = useState<any[]>([]); const [allRegs, setAllRegs] = useState<Registration[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [selectedReg, setSelectedReg] = useState<any | null>(null); const [selectedReg, setSelectedReg] = useState<Registration | null>(null);
const [showRefund, setShowRefund] = useState(false); const [showRefund, setShowRefund] = useState(false);
const load = async () => { const load = useCallback(async () => {
if (!token || !eventId) return; if (!token || !eventId) return;
try { try {
setLoading(true); setLoading(true);
const regs = await apiFetch<any[]>(`/api/registrations/event/${eventId}`, { authToken: token }); const regs = await apiFetch<Registration[]>(`/api/registrations/event/${eventId}`, { authToken: token });
setAllRegs(regs || []); setAllRegs(regs || []);
} catch { } catch {
setAllRegs([]); setAllRegs([]);
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; }, [token, eventId]);
useEffect(() => { useEffect(() => {
load(); load();
}, [token, eventId]); }, [load]);
// Only show registrations that have at least one payment // Only show registrations that have at least one payment
const paidRegs = allRegs.filter(r => const paidRegs = allRegs.filter(r => totalPaidOn(r) > 0);
(r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0) > 0
);
const results = fuzzyFilterRegs(paidRegs, search); const results = fuzzyFilterRegs(paidRegs, search);
const handleRefunded = async (updated: any) => { const handleRefunded = async (updated: Registration) => {
setShowRefund(false); setShowRefund(false);
setSelectedReg(updated); setSelectedReg(updated);
setInfo("Refund recorded"); setInfo("Refund recorded");
// Refresh list // Refresh list
const regs = await apiFetch<any[]>(`/api/registrations/event/${eventId}`, { authToken: token }).catch(() => null); const regs = await apiFetch<Registration[]>(`/api/registrations/event/${eventId}`, { authToken: token }).catch(() => null);
if (regs) setAllRegs(regs); if (regs) setAllRegs(regs);
}; };
const maxRefund = selectedReg const maxRefund = selectedReg ? totalPaidOn(selectedReg) : 0;
? (selectedReg.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0)
: 0;
return ( return (
<div className="border rounded-xl p-4 bg-white shadow-sm"> <div className="border rounded-xl p-4 bg-white shadow-sm">
@@ -1797,7 +1820,7 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
<div className="space-y-2 max-h-[32rem] overflow-auto"> <div className="space-y-2 max-h-[32rem] overflow-auto">
{results.map(r => { {results.map(r => {
const paidValue = (r.payments || []).reduce((s: number, p: any) => s + (p.amount || 0), 0); const paidValue = totalPaidOn(r);
return ( return (
<div key={r.id} className="border rounded p-3 flex justify-between items-center"> <div key={r.id} className="border rounded p-3 flex justify-between items-center">
<div> <div>
@@ -1846,12 +1869,7 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
<div className="border rounded p-3 text-center"> <div className="border rounded p-3 text-center">
<div className="text-xs text-gray-500">TOTAL</div> <div className="text-xs text-gray-500">TOTAL</div>
<div className="font-semibold"> <div className="font-semibold">
R {(selectedReg.totalDueComputed ?? (selectedReg.options || selectedReg.registrationOptions || []).reduce((s: number, o: any) => { R {registrationTotal(selectedReg).toFixed(2)}
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)}
</div> </div>
</div> </div>
<div className="border rounded p-3 text-center bg-red-50"> <div className="border rounded p-3 text-center bg-red-50">
@@ -1864,11 +1882,12 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
<div className="mt-3"> <div className="mt-3">
<div className="text-xs font-medium text-gray-500 mb-1">Payment history</div> <div className="text-xs font-medium text-gray-500 mb-1">Payment history</div>
<div className="space-y-1"> <div className="space-y-1">
{selectedReg.payments.map((p: any, i: number) => ( {(selectedReg.payments || []).map((p, i) => (
<div key={i} className="flex justify-between text-sm"> <div key={i} className="flex justify-between text-sm">
<span className={p.amount < 0 ? "text-red-600" : ""}> <span className={p.amount < 0 ? "text-red-600" : ""}>
{p.amount < 0 ? "Refund" : "Payment"} — {p.method || "—"} {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})` : ""}
</span> </span>
<span className={p.amount < 0 ? "text-red-600 font-medium" : ""}> <span className={p.amount < 0 ? "text-red-600 font-medium" : ""}>
R {Number(p.amount).toFixed(2)} R {Number(p.amount).toFixed(2)}
@@ -1902,7 +1921,6 @@ function DoorRefundPanel({ token, eventId, setError, setInfo }: any) {
registration={selectedReg} registration={selectedReg}
maxRefund={maxRefund} maxRefund={maxRefund}
onRefunded={handleRefunded} onRefunded={handleRefunded}
setError={setError}
/> />
</div> </div>
); );
@@ -10,35 +10,11 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor"; import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { UserPlus, CreditCard } from "lucide-react"; import { UserPlus, CreditCard } from "lucide-react";
import { errorMessage } from "@/lib/utils"; 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 ───────────────────────────────────────────────────────── // ─── 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) { function fmtPrice(n: number) {
return n === 0 ? "Free" : `R ${n.toFixed(2)}`; return n === 0 ? "Free" : `R ${n.toFixed(2)}`;
} }
@@ -52,8 +28,8 @@ function optionUnitPrice(opt: RegistrationOption): number {
} }
const eo = opt.eventOption; const eo = opt.eventOption;
if (!eo) return 0; if (!eo) return 0;
if (opt.variant) return effectiveVariantUnit(eo, opt.variant); if (opt.variant) return variantUnitNow(eo, opt.variant);
return effectiveOptionUnit(eo); return optionUnitNow(eo);
} }
// ─── Component ─────────────────────────────────────────────────────────────── // ─── Component ───────────────────────────────────────────────────────────────
@@ -292,9 +268,9 @@ export default function ManualRegistrationPage() {
const totalDue = useMemo(() => { const totalDue = useMemo(() => {
return options.reduce((sum, o) => { return options.reduce((sum, o) => {
if ((o.variants || []).length > 0) { 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); }, 0);
}, [options, quantities]); }, [options, quantities]);
@@ -561,7 +537,7 @@ export default function ManualRegistrationPage() {
{opt.name}{opt.isMainTicket ? <span className="ml-1.5 text-xs text-brand-600 font-normal">• Main</span> : null} {opt.name}{opt.isMainTicket ? <span className="ml-1.5 text-xs text-brand-600 font-normal">• Main</span> : null}
</div> </div>
{(opt.variants || []).map((v) => { {(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 basePrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const key = `${opt.id}::${v.id}`; const key = `${opt.id}::${v.id}`;
return ( return (
@@ -588,7 +564,7 @@ export default function ManualRegistrationPage() {
</div> </div>
); );
} }
const unit = effectiveOptionUnit(opt); const unit = optionUnitNow(opt);
return ( return (
<div key={opt.id} className="border rounded p-3"> <div key={opt.id} className="border rounded p-3">
<div className="font-medium text-sm">{opt.name}</div> <div className="font-medium text-sm">{opt.name}</div>
+28 -1
View File
@@ -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 // Effective unit price for a registration option. Uses priceSnapshot when available
// (authoritative backend price, variant-aware). Falls back to a deadline-only early-bird // (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); const price = Number(applicable[0].price);
return (price >= 0) ? price : base; 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;
}
+2
View File
@@ -271,6 +271,8 @@ export type RegistrationOption = {
variant?: OptionVariant | null; variant?: OptionVariant | null;
// One entry per price the line was bought at (e.g. some before an early-bird tier expired). // 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 }[]; 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. // A named person on a group registration, for one main-ticket place.