Archived
- Waitlist per session: entries for pick-sessions tickets name a session; offers use that session's free places, never run past its start, and claim links tick it. Held offers count towards session capacity. - At the door: the Select items pop-up has the session picker, with today's session preselected for new attendees. - On pick-sessions events every ticket shows the session list straight away. "All sessions" tickets record the ticked sessions (RegistrationOption.sessionIds) at one price; scanning, attendance, certificates, reminders and capacity follow them. - Fix: per-session stock limits weren't enforced (takenCount filtered WaitlistEntry by a sessionId column that didn't exist, and the error was swallowed), and the public event page lost its stock info. - Fix: editing a door registration with picked sessions couldn't be saved. - Fix: the offline-scanning service worker served /_next/static cache-first forever, so dev browsers that had opened the scanner ran stale code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
823 lines
36 KiB
TypeScript
823 lines
36 KiB
TypeScript
"use client";
|
||
|
||
import React, { useEffect, useMemo, useState } from "react";
|
||
import { useAuth } from "@/hooks/useAuth";
|
||
import { apiFetch } from "@/lib/api";
|
||
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
|
||
import { BundleBuilder, BundleOffers, BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
|
||
import type { EventSession, LateJoinInfo, PublicBundle } from "@/types";
|
||
import { choosesSessions, isPickOption, latePrice, registrationClosesAt } from "@/lib/sessions";
|
||
import { SessionPicker } from "@/components/events/SessionPicker";
|
||
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
|
||
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
|
||
import { analyticsSessionId } from "@/lib/analytics";
|
||
import { errorMessage } from "@/lib/utils";
|
||
|
||
// Tiered low-stock threshold — mirrors events/[id]/page.tsx
|
||
function lowStockThreshold(stockLimit: number): number {
|
||
let pct: number;
|
||
if (stockLimit <= 50) pct = 0.20;
|
||
else if (stockLimit <= 200) pct = 0.15;
|
||
else if (stockLimit <= 1000) pct = 0.10;
|
||
else pct = 0.05;
|
||
return Math.round(stockLimit * pct);
|
||
}
|
||
|
||
type EarlyBirdTier = { id: string; deadline: string; price: number; stockLimit?: number; availableCount?: number; order?: number };
|
||
type OptionVariant = { id: string; name: string; price: number | null; stockLimit?: number; availableCount?: number; order?: number };
|
||
type EventOption = {
|
||
id: string;
|
||
name: string;
|
||
price: number;
|
||
stockLimit?: number;
|
||
availableCount?: number;
|
||
isMainTicket?: boolean;
|
||
earlyBirdTiers?: EarlyBirdTier[];
|
||
variants?: OptionVariant[];
|
||
sessionMode?: "all" | "pick";
|
||
sessionAvailability?: Record<string, number>;
|
||
};
|
||
|
||
export type RegisterEvent = {
|
||
id: string;
|
||
title: string;
|
||
description?: string;
|
||
startDate: string;
|
||
endDate: string;
|
||
registrationDeadline?: string | null;
|
||
price: number;
|
||
picture?: string;
|
||
eventOptions?: EventOption[];
|
||
form?: { isRequired: boolean; fields?: unknown[] } | null;
|
||
requiresRegistration?: boolean;
|
||
requiresAuth?: boolean;
|
||
allowNamedAttendees?: boolean;
|
||
requiresParentalConsent?: boolean;
|
||
collectGender?: boolean;
|
||
waitlistEnabled?: boolean;
|
||
bundles?: PublicBundle[];
|
||
scheduleType?: "single" | "sessions";
|
||
attendanceMode?: "whole" | "pick";
|
||
sessions?: EventSession[];
|
||
registrationClosesAt?: string;
|
||
wholeCourseClosesAt?: string | null;
|
||
lateJoin?: LateJoinInfo | null;
|
||
};
|
||
|
||
// Late joiners on a multi-day event: show main tickets at the late price (the server
|
||
// charges the same — see backend utils/sessions.js).
|
||
function withLatePrices(event: RegisterEvent): RegisterEvent {
|
||
const late = event.lateJoin?.active ? event.lateJoin : null;
|
||
if (!late) return event;
|
||
return {
|
||
...event,
|
||
eventOptions: (event.eventOptions || []).map(o => (!o.isMainTicket || o.sessionMode === "pick" ? o : {
|
||
...o,
|
||
price: latePrice(o.price, late),
|
||
earlyBirdTiers: (o.earlyBirdTiers || []).map(t => ({ ...t, price: latePrice(t.price, late) })),
|
||
variants: (o.variants || []).map(v => (v.price === null || v.price === undefined ? v : { ...v, price: latePrice(v.price, late) })),
|
||
})),
|
||
};
|
||
}
|
||
|
||
type WaitlistOffer = { eventOptionId: string; variantId: string | null; sessionId?: string | null; lineName?: string; quantity: number; expiresAt: string; optionName: string; variantName: string | null };
|
||
|
||
// Key format: "optionId" for no-variant options, "optionId:variantId" for variant options
|
||
type QtyMap = Record<string, number>;
|
||
|
||
function effectiveUnitForOption(opt: EventOption): number {
|
||
const base = opt.price || 0;
|
||
const tiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers.slice() : [];
|
||
if (tiers.length === 0) return base;
|
||
const now = new Date();
|
||
const applicable = tiers
|
||
.map((t) => ({ ...t, _d: new Date(t.deadline) }))
|
||
.filter((t) => now < t._d && (t.stockLimit === undefined || t.stockLimit === 0 || t.availableCount === undefined || t.availableCount > 0))
|
||
.sort((a, b) => a.price - b.price || a._d.getTime() - b._d.getTime());
|
||
return applicable.length > 0 ? applicable[0].price : base;
|
||
}
|
||
|
||
function effectiveUnitForVariant(opt: EventOption, variant: OptionVariant): number {
|
||
if (variant.price !== null && variant.price !== undefined) return variant.price;
|
||
return effectiveUnitForOption(opt);
|
||
}
|
||
|
||
function nextTierForOption(opt: EventOption): EarlyBirdTier | null {
|
||
const tiers = Array.isArray(opt.earlyBirdTiers) ? opt.earlyBirdTiers.slice() : [];
|
||
if (tiers.length === 0) return null;
|
||
const now = new Date();
|
||
const applicable = tiers
|
||
.map((t) => ({ ...t, _d: new Date(t.deadline) }))
|
||
.filter((t) => now < t._d)
|
||
.sort((a, b) => a.price - b.price || a._d.getTime() - b._d.getTime());
|
||
if (applicable.length === 0) return null;
|
||
return applicable[0];
|
||
}
|
||
|
||
function StockBadge({ stockLimit, availableCount }: { stockLimit?: number; availableCount?: number }) {
|
||
if (!stockLimit || stockLimit === 0) return null;
|
||
if (availableCount === undefined) return null;
|
||
if (availableCount <= 0) {
|
||
return <span className="text-xs font-medium text-red-600 bg-red-50 border border-red-200 rounded px-1.5 py-0.5">Sold out</span>;
|
||
}
|
||
const threshold = lowStockThreshold(stockLimit);
|
||
if (availableCount <= threshold) {
|
||
return <span className="text-xs font-medium text-orange-600 bg-orange-50 border border-orange-200 rounded px-1.5 py-0.5">{availableCount} remaining</span>;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function QtyControl({
|
||
value,
|
||
onChange,
|
||
disabled,
|
||
max,
|
||
}: {
|
||
value: number;
|
||
onChange: (v: number) => void;
|
||
disabled?: boolean;
|
||
max?: number;
|
||
}) {
|
||
return (
|
||
<div className="flex items-center gap-1.5">
|
||
<button
|
||
type="button"
|
||
className="w-7 h-7 flex items-center justify-center border rounded text-gray-600 hover:bg-gray-50 disabled:opacity-40"
|
||
onClick={() => onChange(Math.max(0, value - 1))}
|
||
disabled={disabled || value <= 0}
|
||
>
|
||
−
|
||
</button>
|
||
<span className="w-6 text-center text-sm font-medium">{value}</span>
|
||
<button
|
||
type="button"
|
||
className="w-7 h-7 flex items-center justify-center border rounded text-gray-600 hover:bg-gray-50 disabled:opacity-40"
|
||
onClick={() => onChange(value + 1)}
|
||
disabled={disabled || (max !== undefined && max > 0 && value >= max)}
|
||
>
|
||
+
|
||
</button>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// A "pick sessions" event: the sessions chosen per quantity key, and the event's schedule.
|
||
// perSession: this ticket is charged per session (otherwise one price for the sessions ticked).
|
||
type PickProps = { event: RegisterEvent; picks: Record<string, string[]>; onPick: (key: string, ids: string[]) => void; perSession: boolean };
|
||
|
||
function OptionCard({
|
||
opt,
|
||
quantities,
|
||
onQtyChange,
|
||
waitlist,
|
||
pick,
|
||
}: {
|
||
opt: EventOption;
|
||
quantities: QtyMap;
|
||
onQtyChange: (key: string, val: number) => void;
|
||
waitlist?: { eventId: string; guestsAllowed: boolean } | null;
|
||
pick?: PickProps | null;
|
||
}) {
|
||
const hasVariants = Array.isArray(opt.variants) && opt.variants.length > 0;
|
||
const perSession = pick?.perSession ? " per session" : "";
|
||
// The sessions show straight away; ticking one when the quantity is 0 makes it 1.
|
||
const picker = (key: string, qty: number, unit: number, variant?: { id: string; name: string }) => (pick ? (
|
||
<SessionPicker event={pick.event} option={opt} selected={qty > 0 ? pick.picks[key] || [] : []} quantity={Math.max(1, qty)} unitPrice={pick.perSession ? unit : undefined}
|
||
onChange={(ids) => { pick.onPick(key, ids); if (qty === 0 && ids.length > 0) onQtyChange(key, 1); }}
|
||
waitlist={waitlist ? { ...waitlist, variantId: variant?.id ?? null, label: variant ? `${opt.name} (${variant.name})` : opt.name } : null} />
|
||
) : null);
|
||
const isSoldOut = (opt.stockLimit ?? 0) > 0 && opt.availableCount !== undefined && opt.availableCount <= 0;
|
||
|
||
if (hasVariants) {
|
||
const variants = opt.variants!.slice().sort((a, b) => (a.order || 0) - (b.order || 0));
|
||
|
||
// Compute "From R..." display
|
||
const variantPrices = variants.map((v) => effectiveUnitForVariant(opt, v));
|
||
const minPrice = Math.min(...variantPrices);
|
||
const maxPrice = Math.max(...variantPrices);
|
||
const priceLabel = (minPrice === maxPrice ? `R${minPrice.toFixed(2)}` : `From R${minPrice.toFixed(2)}`) + perSession;
|
||
|
||
return (
|
||
<div className="border rounded-lg overflow-hidden bg-white shadow-sm">
|
||
{/* Option header */}
|
||
<div className="flex items-center justify-between px-4 py-3 border-b bg-gray-50">
|
||
<div>
|
||
<div className="font-medium text-sm">{opt.name}</div>
|
||
<div className="text-xs text-gray-500 mt-0.5">{priceLabel}</div>
|
||
</div>
|
||
<div className="flex items-center gap-2">
|
||
{isSoldOut ? (
|
||
<>
|
||
<span className="text-xs font-medium text-red-600 bg-red-50 border border-red-200 rounded px-1.5 py-0.5">Sold out</span>
|
||
{waitlist && (
|
||
<JoinWaitlistButton compact eventId={waitlist.eventId} guestsAllowed={waitlist.guestsAllowed}
|
||
lines={variants.map(v => ({ eventOptionId: opt.id, variantId: v.id, label: `${opt.name} (${v.name})` }))} />
|
||
)}
|
||
</>
|
||
) : (
|
||
<StockBadge stockLimit={opt.stockLimit} availableCount={opt.availableCount} />
|
||
)}
|
||
</div>
|
||
</div>
|
||
|
||
{/* Variant rows */}
|
||
<div className="divide-y">
|
||
{variants.map((variant) => {
|
||
const key = `${opt.id}:${variant.id}`;
|
||
const qty = quantities[key] || 0;
|
||
const unitPrice = effectiveUnitForVariant(opt, variant);
|
||
const variantSoldOut = (variant.stockLimit ?? 0) > 0 && variant.availableCount !== undefined && variant.availableCount <= 0;
|
||
const maxQty = ((variant.stockLimit ?? 0) > 0 && variant.availableCount !== undefined)
|
||
? variant.availableCount
|
||
: undefined;
|
||
|
||
return (
|
||
<div key={variant.id} className="px-4 py-2.5">
|
||
<div className="flex items-center justify-between">
|
||
<div className="flex items-center gap-2 min-w-0">
|
||
<span className="text-sm">{variant.name}</span>
|
||
<span className="text-xs text-gray-500">R{unitPrice.toFixed(2)}{perSession}</span>
|
||
<StockBadge stockLimit={variant.stockLimit} availableCount={variant.availableCount} />
|
||
{waitlist && variantSoldOut && !isSoldOut && (
|
||
<JoinWaitlistButton compact eventId={waitlist.eventId} guestsAllowed={waitlist.guestsAllowed}
|
||
lines={[{ eventOptionId: opt.id, variantId: variant.id, label: `${opt.name} (${variant.name})` }]} />
|
||
)}
|
||
</div>
|
||
<QtyControl
|
||
value={qty}
|
||
onChange={(v) => onQtyChange(key, v)}
|
||
disabled={!!(isSoldOut || variantSoldOut)}
|
||
max={maxQty}
|
||
/>
|
||
</div>
|
||
{picker(key, qty, unitPrice, variant)}
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// No variants — simple row
|
||
const key = opt.id;
|
||
const qty = quantities[key] || 0;
|
||
const tier = nextTierForOption(opt);
|
||
const price = effectiveUnitForOption(opt);
|
||
const maxQty = ((opt.stockLimit ?? 0) > 0 && opt.availableCount !== undefined)
|
||
? opt.availableCount
|
||
: undefined;
|
||
|
||
return (
|
||
<div className="border rounded-lg p-3 bg-white shadow-sm">
|
||
<div className="flex items-center justify-between">
|
||
<div className="min-w-0 flex-1 mr-3">
|
||
<div className="font-medium text-sm">{opt.name}</div>
|
||
<div className="text-xs text-gray-500 mt-0.5 flex items-center gap-2 flex-wrap">
|
||
{tier ? (
|
||
<>
|
||
<span>R{price.toFixed(2)}</span>
|
||
<span className="text-brand-600">
|
||
Early bird — ends {new Date(tier.deadline).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "2-digit" })}
|
||
</span>
|
||
</>
|
||
) : (
|
||
<span>R{price.toFixed(2)}{perSession}</span>
|
||
)}
|
||
<StockBadge stockLimit={opt.stockLimit} availableCount={opt.availableCount} />
|
||
{waitlist && isSoldOut && (
|
||
<JoinWaitlistButton compact eventId={waitlist.eventId} guestsAllowed={waitlist.guestsAllowed} lines={[{ eventOptionId: opt.id, label: opt.name }]} />
|
||
)}
|
||
</div>
|
||
</div>
|
||
<QtyControl
|
||
value={qty}
|
||
onChange={(v) => onQtyChange(key, v)}
|
||
disabled={!!(isSoldOut)}
|
||
max={maxQty}
|
||
/>
|
||
</div>
|
||
{picker(key, qty, price)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// Online donations have the same R15 minimum as the donate page and the backend.
|
||
const MIN_DONATION = 15;
|
||
|
||
// Suggested donations: 10/15/20/25% of the ticket total rounded up to the next R10 (at least R20),
|
||
// topped up with fixed amounts when the percentages collapse on a small total.
|
||
function donationPresets(total: number): number[] {
|
||
const out: number[] = [];
|
||
for (const pct of [0.10, 0.15, 0.20, 0.25]) {
|
||
const v = Math.max(20, Math.ceil((total * pct) / 10) * 10);
|
||
if (!out.includes(v)) out.push(v);
|
||
}
|
||
for (const v of [50, 100, 200]) {
|
||
if (out.length >= 3) break;
|
||
if (!out.includes(v) && v > out[out.length - 1]) out.push(v);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
type DonationChoice = { kind: "none" } | { kind: "preset"; index: number } | { kind: "custom" };
|
||
|
||
function DonationPicker({
|
||
presets,
|
||
choice,
|
||
onChoiceChange,
|
||
customAmount,
|
||
onCustomAmountChange,
|
||
}: {
|
||
presets: number[];
|
||
choice: DonationChoice;
|
||
onChoiceChange: (c: DonationChoice) => void;
|
||
customAmount: string;
|
||
onCustomAmountChange: (v: string) => void;
|
||
}) {
|
||
const btn = (active: boolean) =>
|
||
`px-3 py-2 rounded-lg border text-sm font-medium transition-colors ${active ? "bg-brand-600 border-brand-600 text-white" : "bg-white text-gray-700 hover:bg-gray-50"}`;
|
||
return (
|
||
<div className="border rounded-lg p-4 bg-white shadow-sm">
|
||
<div className="font-medium text-sm">Donation amount</div>
|
||
<p className="text-xs text-gray-500 mt-0.5 mb-3">Would you like to add a donation to support this event? It's added to your payment.</p>
|
||
<div className="flex flex-wrap gap-2">
|
||
{presets.map((amt, i) => (
|
||
<button key={i} type="button" className={btn(choice.kind === "preset" && choice.index === i)} onClick={() => onChoiceChange({ kind: "preset", index: i })}>
|
||
R{amt}
|
||
</button>
|
||
))}
|
||
<button type="button" className={btn(choice.kind === "custom")} onClick={() => onChoiceChange({ kind: "custom" })}>
|
||
Custom
|
||
</button>
|
||
<button type="button" className={btn(choice.kind === "none")} onClick={() => onChoiceChange({ kind: "none" })}>
|
||
None
|
||
</button>
|
||
</div>
|
||
{choice.kind === "custom" && (
|
||
<div className="mt-3">
|
||
<input
|
||
type="number"
|
||
min={MIN_DONATION}
|
||
step="1"
|
||
inputMode="decimal"
|
||
autoFocus
|
||
placeholder={`Amount in Rand (min R${MIN_DONATION})`}
|
||
value={customAmount}
|
||
onChange={(e) => onCustomAmountChange(e.target.value)}
|
||
className="w-full sm:w-60 border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||
/>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export default function RegisterForm({ event: baseEvent }: { event: RegisterEvent }) {
|
||
const { token, user } = useAuth();
|
||
const eventId = baseEvent.id;
|
||
|
||
// A waitlist claim link (?waitlist=<token>): the places held for this person are
|
||
// added back to what's available, so they can choose them.
|
||
const [waitlistToken, setWaitlistToken] = useState<string | null>(null);
|
||
const [offer, setOffer] = useState<WaitlistOffer | null>(null);
|
||
const [offerError, setOfferError] = useState<string | null>(null);
|
||
useEffect(() => {
|
||
const t = new URLSearchParams(window.location.search).get("waitlist");
|
||
if (!t) return;
|
||
apiFetch<WaitlistOffer & { status: string }>(`/api/waitlist/claim/${encodeURIComponent(t)}`)
|
||
.then(res => {
|
||
if (res.status !== "offered") { setOfferError("This waitlist offer has expired."); return; }
|
||
setWaitlistToken(t);
|
||
setOffer(res);
|
||
setQuantities(q => ({ ...q, [res.variantId ? `${res.eventOptionId}:${res.variantId}` : res.eventOptionId]: res.quantity }));
|
||
})
|
||
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
|
||
}, []);
|
||
const event = useMemo<RegisterEvent>(() => {
|
||
const priced = withLatePrices(baseEvent);
|
||
if (!offer) return priced;
|
||
return {
|
||
...priced,
|
||
eventOptions: (priced.eventOptions || []).map(o => {
|
||
if (o.id !== offer.eventOptionId) return o;
|
||
if (offer.sessionId) {
|
||
const left = o.sessionAvailability?.[offer.sessionId];
|
||
return { ...o, ...(left !== undefined ? { sessionAvailability: { ...o.sessionAvailability, [offer.sessionId]: left + offer.quantity } } : {}) };
|
||
}
|
||
return {
|
||
...o,
|
||
availableCount: o.availableCount !== undefined ? o.availableCount + offer.quantity : o.availableCount,
|
||
variants: (o.variants || []).map(v => v.id === offer.variantId && v.availableCount !== undefined ? { ...v, availableCount: v.availableCount + offer.quantity } : v),
|
||
};
|
||
}),
|
||
};
|
||
}, [baseEvent, offer]);
|
||
|
||
const [quantities, setQuantities] = useState<QtyMap>(() => {
|
||
const initial: QtyMap = {};
|
||
(event.eventOptions || []).forEach((o) => {
|
||
if (Array.isArray(o.variants) && o.variants.length > 0) {
|
||
o.variants.forEach((v) => { initial[`${o.id}:${v.id}`] = 0; });
|
||
} else {
|
||
initial[o.id] = 0;
|
||
}
|
||
});
|
||
return initial;
|
||
});
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [creatingRegistration, setCreatingRegistration] = useState(false);
|
||
const [coupon, setCoupon] = useState<AppliedCoupon | null>(null);
|
||
const [namingOthers, setNamingOthers] = useState(false);
|
||
const [attendeeEntries, setAttendeeEntries] = useState<AttendeeEntries>({});
|
||
const [delivery, setDelivery] = useState<TicketDelivery>("payer");
|
||
const qtyFor = (optionId: string, variantId: string | null) => quantities[variantId ? `${optionId}:${variantId}` : optionId] || 0;
|
||
const isYouthEvent = !!event.requiresParentalConsent;
|
||
const namedAttendees = () => ((event.allowNamedAttendees && namingOthers) || isYouthEvent
|
||
? attendeesPayload(event.eventOptions || [], qtyFor, attendeeEntries)
|
||
: []);
|
||
|
||
// Guest details (for unauthenticated free-event registration)
|
||
const [guestName, setGuestName] = useState("");
|
||
const [guestEmail, setGuestEmail] = useState("");
|
||
const [guestPhone, setGuestPhone] = useState("");
|
||
|
||
// Event data is server-rendered, but "now" has to be evaluated in the browser (and this page
|
||
// can be served from a up-to-60s-old cache — see revalidate in page.tsx), so still guard against
|
||
// someone loading a link after registration has actually closed.
|
||
useEffect(() => {
|
||
try {
|
||
const now = new Date();
|
||
const end = event.endDate ? new Date(event.endDate) : null;
|
||
const deadline = event.registrationDeadline ? new Date(event.registrationDeadline) : null;
|
||
if ((deadline && now >= deadline) || (end && now >= end) || now >= registrationClosesAt(event)) {
|
||
window.location.replace('/events');
|
||
}
|
||
} catch {}
|
||
}, [event]);
|
||
|
||
const handleQtyChange = (key: string, val: number) => {
|
||
setQuantities((q) => ({ ...q, [key]: val }));
|
||
};
|
||
|
||
// "Pick sessions" events: the sessions chosen for each quantity key. Every ticket
|
||
// shows the sessions; per-session tickets are charged once per session ticked.
|
||
const [picks, setPicks] = useState<Record<string, string[]>>({});
|
||
const choosing = choosesSessions(event);
|
||
const pickFor = (opt: EventOption) => isPickOption(event, opt);
|
||
// A waitlist offer for one session: that session is ticked for them.
|
||
useEffect(() => {
|
||
if (!offer?.sessionId) return;
|
||
const key = offer.variantId ? `${offer.eventOptionId}:${offer.variantId}` : offer.eventOptionId;
|
||
setPicks(p => ({ ...p, [key]: [offer.sessionId as string] }));
|
||
}, [offer]);
|
||
const sessionsFor = (key: string, opt: EventOption) => (pickFor(opt) ? (picks[key] || []).length : 1);
|
||
|
||
const total = useMemo(() => {
|
||
return (event.eventOptions || []).reduce((sum, opt) => {
|
||
const hasVariants = Array.isArray(opt.variants) && opt.variants.length > 0;
|
||
if (hasVariants) {
|
||
return sum + opt.variants!.reduce((vsum, v) => {
|
||
const key = `${opt.id}:${v.id}`;
|
||
const qty = quantities[key] || 0;
|
||
return vsum + qty * sessionsFor(key, opt) * effectiveUnitForVariant(opt, v);
|
||
}, 0);
|
||
}
|
||
return sum + (quantities[opt.id] || 0) * sessionsFor(opt.id, opt) * effectiveUnitForOption(opt);
|
||
}, 0);
|
||
}, [event, quantities, picks]); // eslint-disable-line react-hooks/exhaustive-deps
|
||
|
||
const isGuestEligible = !!(event.requiresAuth === false);
|
||
const isLoggedIn = !!user || !!token;
|
||
const showGuestForm = isGuestEligible && !isLoggedIn;
|
||
|
||
const eventSoldOut = useMemo(() => {
|
||
const limitedOpts = (event.eventOptions || []).filter(o => (o.stockLimit ?? 0) > 0);
|
||
return limitedOpts.length > 0 && limitedOpts.every(o => o.availableCount !== undefined && o.availableCount <= 0);
|
||
}, [event]);
|
||
|
||
const basket = useMemo(() => buildItems(), [quantities, picks]); // eslint-disable-line react-hooks/exhaustive-deps
|
||
const bundleQuote = useBundleQuote({ eventId, basket, token, enabled: (event.bundles || []).length > 0 });
|
||
// The server prices the basket (staff price, tiers, bundle deals) when quoting or checking
|
||
// a code, so its total wins.
|
||
const payable = coupon ? coupon.total : bundleQuote ? bundleQuote.total : total;
|
||
|
||
// Optional donation on top of the tickets — paid in the same Yoco checkout and recorded
|
||
// as a separate donation payment. Only offered when there's something to pay online.
|
||
const [donationChoice, setDonationChoice] = useState<DonationChoice>({ kind: "none" });
|
||
const [customDonation, setCustomDonation] = useState("");
|
||
const presets = useMemo(() => donationPresets(total), [total]);
|
||
const showDonation = isLoggedIn && payable > 0 && !eventSoldOut;
|
||
const donation = !showDonation ? 0
|
||
: donationChoice.kind === "preset" ? (presets[donationChoice.index] ?? 0)
|
||
: donationChoice.kind === "custom" ? Math.max(0, Math.round((parseFloat(customDonation) || 0) * 100) / 100)
|
||
: 0;
|
||
|
||
function buildItems() {
|
||
const items: { eventOptionId: string; quantity: number; variantId?: string; sessionIds?: string[] }[] = [];
|
||
Object.entries(quantities).forEach(([key, qty]) => {
|
||
if (qty <= 0) return;
|
||
const [eventOptionId, variantId] = key.includes(":") ? key.split(":") : [key, undefined];
|
||
const opt = (event.eventOptions || []).find(o => o.id === eventOptionId);
|
||
const sessionIds = opt && choosing ? picks[key] || [] : undefined;
|
||
items.push({ eventOptionId, quantity: qty, ...(variantId ? { variantId } : {}), ...(sessionIds ? { sessionIds } : {}) });
|
||
});
|
||
return items;
|
||
}
|
||
|
||
const submitRegistration = async () => {
|
||
const items = buildItems();
|
||
if (items.length === 0) {
|
||
setError("Select at least one ticket.");
|
||
return;
|
||
}
|
||
const noSessions = items.find(i => i.sessionIds && i.sessionIds.length === 0);
|
||
if (noSessions) {
|
||
setError(`Choose the sessions for "${(event.eventOptions || []).find(o => o.id === noSessions.eventOptionId)?.name || "your ticket"}".`);
|
||
return;
|
||
}
|
||
if (isYouthEvent) {
|
||
const missing = consentDetailsMissing(event.eventOptions || [], qtyFor, attendeeEntries, event.startDate);
|
||
if (missing) { setError(missing); return; }
|
||
}
|
||
if (showDonation && donationChoice.kind === "custom" && donation > 0 && donation < MIN_DONATION) {
|
||
setError(`The minimum donation is R${MIN_DONATION}. Choose None to skip it.`);
|
||
return;
|
||
}
|
||
const donationParam = donation > 0 ? `&donation=${encodeURIComponent(donation.toFixed(2))}` : "";
|
||
|
||
// Claim link without logging in: the link identifies the person.
|
||
if (waitlistToken && !isLoggedIn) {
|
||
try {
|
||
setError(null);
|
||
setCreatingRegistration(true);
|
||
const res = await apiFetch<{ id: string; totalDueComputed?: number }>("/api/registrations", {
|
||
method: "POST",
|
||
body: { eventId, options: items, waitlistToken, analyticsSessionId: analyticsSessionId(), ...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}) },
|
||
});
|
||
if (res?.id) window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent((res.totalDueComputed ?? payable).toFixed(2))}`;
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Registration failed");
|
||
} finally {
|
||
setCreatingRegistration(false);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (isLoggedIn) {
|
||
if (!token) {
|
||
setError("Session expired — please log in again.");
|
||
window.location.href = `/login?redirect=/register/${eventId}`;
|
||
return;
|
||
}
|
||
try {
|
||
setError(null);
|
||
setCreatingRegistration(true);
|
||
const res = await apiFetch<{ id: string; totalDueComputed?: number; couponError?: string }>("/api/registrations", {
|
||
method: "POST",
|
||
body: {
|
||
eventId,
|
||
options: items,
|
||
...(coupon ? { couponCode: coupon.code } : {}),
|
||
analyticsSessionId: analyticsSessionId(),
|
||
...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}),
|
||
...(waitlistToken ? { waitlistToken } : {}),
|
||
},
|
||
authToken: token,
|
||
});
|
||
if (res?.id) {
|
||
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
|
||
const due = res.totalDueComputed ?? payable;
|
||
const next = hasForm
|
||
? `/forms?registrationId=${encodeURIComponent(res.id)}${donationParam}`
|
||
: `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=${encodeURIComponent((due || 0).toFixed(2))}${donationParam}`;
|
||
if (res.couponError) {
|
||
// The code ran out between checking and registering — the registration is
|
||
// saved at full price, so say so before moving on.
|
||
setError(`You're registered, but the code couldn't be applied: ${res.couponError} Continuing at full price…`);
|
||
setTimeout(() => { window.location.href = next; }, 4000);
|
||
return;
|
||
}
|
||
window.location.href = next;
|
||
}
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Registration failed");
|
||
} finally {
|
||
setCreatingRegistration(false);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (!showGuestForm) {
|
||
setError("Please log in to register for this event.");
|
||
window.location.href = `/login?redirect=/register/${eventId}`;
|
||
return;
|
||
}
|
||
|
||
if (!guestName.trim()) { setError("Please enter your name."); return; }
|
||
if (!guestEmail.trim() || !guestEmail.includes("@")) { setError("Please enter a valid email address."); return; }
|
||
|
||
try {
|
||
setError(null);
|
||
setCreatingRegistration(true);
|
||
const res = await apiFetch<{ id: string }>("/api/registrations", {
|
||
method: "POST",
|
||
body: {
|
||
eventId, options: items, guestName: guestName.trim(), guestEmail: guestEmail.trim(), guestPhone: guestPhone.trim() || undefined,
|
||
analyticsSessionId: analyticsSessionId(),
|
||
...(namedAttendees().length > 0 ? { attendees: namedAttendees(), ticketDelivery: delivery } : {}),
|
||
},
|
||
});
|
||
if (res?.id) {
|
||
const hasForm = !!(event?.form && Array.isArray(event.form.fields) && event.form.fields.length > 0);
|
||
if (hasForm) {
|
||
window.location.href = `/forms?registrationId=${encodeURIComponent(res.id)}`;
|
||
} else {
|
||
window.location.href = `/registration/success?registrationId=${encodeURIComponent(res.id)}&totalDue=0.00`;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Registration failed");
|
||
} finally {
|
||
setCreatingRegistration(false);
|
||
}
|
||
};
|
||
|
||
|
||
return (
|
||
<>
|
||
<h1 className="text-2xl font-semibold mb-4">Register for {event.title}</h1>
|
||
|
||
{offer && (
|
||
<div className="mb-4 p-4 border rounded-lg bg-green-50 border-green-200 text-sm text-green-900">
|
||
<strong>Your waitlist place:</strong> {offer.quantity} × {offer.lineName || `${offer.optionName}${offer.variantName ? ` (${offer.variantName})` : ""}`} — held for you until {new Date(offer.expiresAt).toLocaleString()}.
|
||
</div>
|
||
)}
|
||
{offerError && (
|
||
<div className="mb-4 p-4 border rounded-lg bg-amber-50 border-amber-200 text-sm text-amber-900">{offerError}</div>
|
||
)}
|
||
|
||
{eventSoldOut && !event.waitlistEnabled && (
|
||
<div className="mb-4 p-4 border rounded-lg bg-red-50 border-red-200 text-sm text-red-800 font-medium">
|
||
This event is sold out. Registration is no longer available.
|
||
</div>
|
||
)}
|
||
|
||
{!isLoggedIn && !isGuestEligible && !waitlistToken && (
|
||
<div className="mb-4 p-4 border rounded-lg bg-amber-50 border-amber-200 text-sm text-amber-800">
|
||
You need to <a href={`/login?redirect=/register/${eventId}`} className="font-semibold underline">log in</a> or <a href={`/register?redirect=/register/${eventId}`} className="font-semibold underline">create an account</a> to register for this event.
|
||
</div>
|
||
)}
|
||
|
||
{showGuestForm && (
|
||
<div className="mb-6 border rounded-xl p-4 bg-white shadow-sm">
|
||
<div className="text-base font-semibold mb-1">Your details</div>
|
||
<p className="text-sm text-gray-500 mb-3">
|
||
No account needed for this event.{" "}
|
||
<a href={`/login?redirect=/register/${eventId}`} className="text-brand-600 hover:underline">Log in</a> if you already have one.
|
||
</p>
|
||
<div className="space-y-2">
|
||
<input
|
||
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||
placeholder="Full name *"
|
||
value={guestName}
|
||
onChange={e => setGuestName(e.target.value)}
|
||
required
|
||
/>
|
||
<input
|
||
type="email"
|
||
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||
placeholder="Email address *"
|
||
value={guestEmail}
|
||
onChange={e => setGuestEmail(e.target.value)}
|
||
required
|
||
/>
|
||
<input
|
||
type="tel"
|
||
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||
placeholder="Phone number (optional)"
|
||
value={guestPhone}
|
||
onChange={e => setGuestPhone(e.target.value)}
|
||
/>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{!eventSoldOut && <BundleOffers bundles={event.bundles} className="mb-3" />}
|
||
|
||
<div className="space-y-3">
|
||
{(event.eventOptions || []).map((opt) => (
|
||
<OptionCard
|
||
key={opt.id}
|
||
opt={opt}
|
||
quantities={quantities}
|
||
onQtyChange={handleQtyChange}
|
||
waitlist={event.waitlistEnabled ? { eventId, guestsAllowed: event.requiresAuth === false } : null}
|
||
pick={choosing ? { event, picks, onPick: (key, ids) => setPicks(p => ({ ...p, [key]: ids })), perSession: pickFor(opt) } : null}
|
||
/>
|
||
))}
|
||
</div>
|
||
|
||
{!eventSoldOut && (
|
||
<BundleBuilder
|
||
className="mt-3"
|
||
bundles={event.bundles}
|
||
options={event.eventOptions || []}
|
||
qty={qtyFor}
|
||
onSetQuantity={(optionId, variantId, quantity) => handleQtyChange(variantId ? `${optionId}:${variantId}` : optionId, quantity)}
|
||
/>
|
||
)}
|
||
|
||
{showDonation && (
|
||
<div className="mt-3">
|
||
<DonationPicker
|
||
presets={presets}
|
||
choice={donationChoice}
|
||
onChoiceChange={setDonationChoice}
|
||
customAmount={customDonation}
|
||
onCustomAmountChange={setCustomDonation}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
{event.lateJoin?.active && (
|
||
<div className="mt-4 p-3 rounded-lg bg-brand-50 border border-brand-200 text-sm text-brand-900">
|
||
<strong>Joining late:</strong> {event.lateJoin.sessionsLeft} of {event.lateJoin.totalSessions} sessions are still to come, so main tickets are at the {event.lateJoin.mode === "prorata" ? "price for the sessions left" : "late-joiner price"}.
|
||
</div>
|
||
)}
|
||
|
||
{(() => {
|
||
// Collect all upcoming early-bird tiers across all options
|
||
const now = new Date();
|
||
const upcomingTiers = (event.eventOptions || []).flatMap(opt =>
|
||
(opt.earlyBirdTiers || [])
|
||
.map((t) => ({ ...t, deadline: new Date(t.deadline) }))
|
||
.filter((t) => t.deadline > now)
|
||
).sort((a, b) => a.deadline.getTime() - b.deadline.getTime());
|
||
if (upcomingTiers.length === 0) return null;
|
||
const soonest = upcomingTiers[0].deadline;
|
||
const dateStr = soonest.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
|
||
return (
|
||
<div className="mt-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-sm text-amber-800">
|
||
<strong>Early bird pricing notice:</strong> Reduced early-bird prices are available until {dateStr}. Prices are subject to deadline and availability — your price is locked at registration but payment must be completed before the deadline to guarantee the early-bird rate.
|
||
</div>
|
||
);
|
||
})()}
|
||
|
||
{(event.allowNamedAttendees || isYouthEvent) && !eventSoldOut && (isLoggedIn || showGuestForm) && (
|
||
<div className="mt-6">
|
||
<AttendeeNamesEditor
|
||
options={event.eventOptions || []}
|
||
qtyFor={qtyFor}
|
||
enabled={namingOthers}
|
||
onEnabledChange={setNamingOthers}
|
||
entries={attendeeEntries}
|
||
onEntriesChange={setAttendeeEntries}
|
||
delivery={delivery}
|
||
onDeliveryChange={setDelivery}
|
||
consentEventStart={isYouthEvent ? event.startDate : undefined}
|
||
collectGender={!!event.collectGender}
|
||
/>
|
||
</div>
|
||
)}
|
||
|
||
{isLoggedIn && total > 0 && !eventSoldOut && (
|
||
<div className="mt-6">
|
||
<CouponCodeField eventId={eventId} basket={basket} token={token} applied={coupon} onChange={setCoupon} />
|
||
</div>
|
||
)}
|
||
|
||
<div className="mt-6 flex items-center justify-between">
|
||
<div>
|
||
{(bundleQuote || (coupon && coupon.discount > 0)) && (
|
||
<div className="text-sm text-gray-500 line-through">R{(coupon?.subtotal ?? bundleQuote?.subtotal ?? total).toFixed(2)}</div>
|
||
)}
|
||
<BundleSavings applications={bundleQuote?.bundles} />
|
||
{coupon && coupon.discount > 0 && (
|
||
<div className="text-sm text-green-700">Code {coupon.code} −R{coupon.discount.toFixed(2)}</div>
|
||
)}
|
||
{donation > 0 && (
|
||
<div className="text-sm text-gray-600">Donation +R{donation.toFixed(2)}</div>
|
||
)}
|
||
<div className="text-lg font-semibold">Total: R{(payable + donation).toFixed(2)}</div>
|
||
</div>
|
||
{eventSoldOut ? (
|
||
<button disabled className="bg-red-50 text-red-700 border border-red-200 px-4 py-2 rounded cursor-not-allowed">
|
||
Sold Out
|
||
</button>
|
||
) : (
|
||
<button
|
||
onClick={submitRegistration}
|
||
disabled={creatingRegistration || (!isLoggedIn && !isGuestEligible && !waitlistToken)}
|
||
className="bg-brand-600 text-white px-4 py-2 rounded hover:bg-brand-700 disabled:opacity-60"
|
||
>
|
||
{creatingRegistration ? "Registering..." : "Register"}
|
||
</button>
|
||
)}
|
||
</div>
|
||
|
||
{error && <p className="text-sm text-red-600 mt-3">{error}</p>}
|
||
</>
|
||
);
|
||
}
|