Add bundle deals

Sell a set of tickets together for one price (e.g. 5 Adult + 3 Child for R500).
Bundles apply automatically, as many times as a registration's tickets allow, and
only when cheaper than the prices actually charged. Coupons come off afterwards.

- EventBundle/EventBundleItem/RegistrationBundle models and Registration.bundleDiscount
- Supervisor "Bundle deals" page, quote endpoint, bundle lines on invoices,
  receipts, emails, WhatsApp and Yoco checkout, Discounts report rows
- Register form shows started bundles with "Complete bundle" and "+" buttons
- Demo: Family Fun Day sells a Family deal bundle instead of the Family pass ticket

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 15:14:53 +02:00
co-authored by Claude Opus 5.5
parent 2a8e8c7c11
commit 268781d610
35 changed files with 1766 additions and 149 deletions
@@ -24,6 +24,9 @@ const ACTIONS = [
"coupon_updated",
"coupon_disabled",
"coupon_applied_manual",
"bundle_created",
"bundle_updated",
"bundle_deleted",
"consent_override",
"consent_rerequested",
"medical_list_viewed",
@@ -53,6 +56,9 @@ const ACTION_LABELS: Record<string, string> = {
coupon_updated: "Coupon edited",
coupon_disabled: "Coupon turned off",
coupon_applied_manual: "Coupon applied/removed by staff",
bundle_created: "Bundle deal created",
bundle_updated: "Bundle deal edited",
bundle_deleted: "Bundle deal deleted",
consent_override: "Consent overridden at check-in",
consent_rerequested: "Consent re-requested",
medical_list_viewed: "Medical list viewed",
@@ -33,6 +33,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks },
{ href: "/dashboard/supervisor/consent", label: "Parental consent", description: "Youth events: consent status and medical list", icon: ShieldCheck },
{ href: "/dashboard/supervisor/coupons", label: "Coupon codes", description: "Discounts for staff, leaders and promotions", icon: TicketPercent },
{ href: "/dashboard/supervisor/bundles", label: "Bundle deals", description: "Tickets sold together for one price", icon: Gift },
{ href: "/dashboard/staff/ticket-scanning", label: "Open scanner", description: "Use your device camera to validate tickets", icon: QrCode },
{ href: "/dashboard/supervisor/reports", label: "Reports", description: "View, export, and email reports", icon: BarChart2 },
{ href: "/dashboard/admin/forms", label: "Attendee forms", description: "View submitted attendee forms", icon: FileText },
@@ -7,6 +7,7 @@ import { apiFetch } from "@/lib/api";
import { scoreUser } from "@/lib/fuzzyMatch";
import { useDismissingState } from "@/hooks/useDismissingState";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
import { TransferTicketModal, canOfferTransfer } from "@/components/shared/TransferTicketModal";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react";
@@ -1230,14 +1231,16 @@ type OptionsModalProps = {
};
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)
.filter(([, qty]) => qty > 0)
.map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
});
// Bundle deals apply to the whole registration, so this holds for edits too.
const bundleQuote = useBundleQuote({ eventId, basket, token, forUserId: couponForUserId, enabled: open });
if (!open) return null;
const safeOptions: EventOption[] = options || [];
@@ -1249,7 +1252,8 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
return sum + (quantities[o.id] || 0) * optionUnitNow(o);
}, 0);
const belowPaid = isEdit && total < totalPaid;
const afterBundles = bundleQuote ? bundleQuote.total : total;
const belowPaid = isEdit && afterBundles < totalPaid;
const belowIssued = isEdit && Object.entries(minQuantities).some(
([key, minQty]) => minQty > 0 && (quantities[key] || 0) < minQty
);
@@ -1365,7 +1369,8 @@ function OptionsModal({ open, onClose, options, quantities, setQuantities, minQu
{coupon && coupon.discount > 0 && !isEdit && (
<div className="text-xs text-gray-500"><span className="line-through">R {coupon.subtotal.toFixed(2)}</span> <span className="text-green-700">−R {coupon.discount.toFixed(2)}</span></div>
)}
<div className="text-lg font-semibold">Total: R {(coupon && !isEdit ? coupon.total : total).toFixed(2)}</div>
<BundleSavings applications={bundleQuote?.bundles} className="text-xs" />
<div className="text-lg font-semibold">Total: R {(coupon && !isEdit ? coupon.total : afterBundles).toFixed(2)}</div>
{coupon && isEdit && <div className="text-xs text-green-700">Code {coupon.code} is applied when you save</div>}
</div>
<div className="flex gap-2">
@@ -0,0 +1,389 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Gift, Plus, X, Trash2 } from "lucide-react";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import type { EventBundle } from "@/types";
type OptionLite = { id: string; name: string; price: number; variants?: { id: string; name: string; price?: number | null }[] };
type EventLite = { id: string; title: string; startDate: string; endDate?: string; eventOptions: OptionLite[] };
type ItemDraft = { eventOptionId: string; variantId: string | null; quantity: string };
type Draft = {
name: string;
description: string;
price: string;
items: ItemDraft[];
validFrom: string;
validUntil: string;
isActive: boolean;
};
const blankDraft = (options: OptionLite[]): Draft => ({
name: "", description: "", price: "",
items: options.slice(0, 2).map(o => ({ eventOptionId: o.id, variantId: null, quantity: "1" })),
validFrom: "", validUntil: "", isActive: true,
});
// <input type="datetime-local"> wants local "YYYY-MM-DDTHH:mm".
const toLocalInput = (iso: string | null | undefined) => {
if (!iso) return "";
const d = new Date(iso);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
const draftFromBundle = (b: EventBundle): Draft => ({
name: b.name, description: b.description || "", price: String(b.price),
items: b.items.map(i => ({ eventOptionId: i.eventOptionId, variantId: i.variantId || null, quantity: String(i.quantity) })),
validFrom: toLocalInput(b.validFrom), validUntil: toLocalInput(b.validUntil), isActive: b.isActive,
});
const fmtDate = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : "");
const fmtRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
/** Standard price of one unit of an item (variant price, else the option's). */
function unitPrice(options: OptionLite[], item: { eventOptionId: string; variantId: string | null }) {
const o = options.find(x => x.id === item.eventOptionId);
if (!o) return 0;
const v = item.variantId ? (o.variants || []).find(x => x.id === item.variantId) : null;
return Number(v && v.price !== null && v.price !== undefined ? v.price : o.price) || 0;
}
function bundleStatus(b: EventBundle): { label: string; cls: string } {
const now = Date.now();
if (!b.isActive) return { label: "Off", cls: "bg-gray-100 text-gray-600" };
if (b.validUntil && new Date(b.validUntil).getTime() < now) return { label: "Ended", cls: "bg-gray-100 text-gray-600" };
if (b.validFrom && new Date(b.validFrom).getTime() > now) return { label: "Scheduled", cls: "bg-amber-100 text-amber-800" };
return { label: "On sale", cls: "bg-green-100 text-green-800" };
}
export default function BundlesPage() {
const { user, loading, token } = useAuth();
const router = useRouter();
const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]);
useEffect(() => {
if (loading) return;
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<EventLite[]>([]);
const [eventId, setEventId] = useState("");
const [bundles, setBundles] = useState<EventBundle[]>([]);
const [fetching, setFetching] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
const [editing, setEditing] = useState<{ id: string | null; draft: Draft } | null>(null);
useEffect(() => {
if (!token || !canView) return;
apiFetch<EventLite[]>("/api/events/all?includePast=true", { authToken: token })
.then(list => {
const sorted = (list || []).slice().sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime());
setEvents(sorted);
// Start on the next upcoming event, the one most likely to need a deal.
const upcoming = sorted.filter(e => new Date(e.endDate || e.startDate).getTime() >= Date.now());
setEventId(prev => prev || (upcoming[upcoming.length - 1] || sorted[0])?.id || "");
})
.catch(e => setError(errorMessage(e) || "Failed to load events"));
}, [token, canView, setError]);
const event = events.find(e => e.id === eventId) || null;
const load = useCallback(async () => {
if (!token || !eventId) return;
setFetching(true);
try {
setBundles(await apiFetch<EventBundle[]>(`/api/bundles/event/${eventId}`, { authToken: token }) || []);
} catch (e) {
setError(errorMessage(e) || "Failed to load bundles");
} finally {
setFetching(false);
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
const toggleActive = async (b: EventBundle) => {
try {
await apiFetch(`/api/bundles/${b.id}`, { method: "PUT", authToken: token!, body: { isActive: !b.isActive } });
setInfo(`${b.name} turned ${b.isActive ? "off" : "on"}.`);
load();
} catch (e) {
setError(errorMessage(e) || "Failed to update bundle");
}
};
const remove = async (b: EventBundle) => {
if (!window.confirm(`Delete "${b.name}"?`)) return;
try {
const res = await apiFetch<{ message: string }>(`/api/bundles/${b.id}`, { method: "DELETE", authToken: token! });
setInfo(res?.message || "Bundle deleted");
load();
} catch (e) {
setError(errorMessage(e) || "Failed to delete bundle");
}
};
return (
<div className="max-w-6xl mx-auto w-full p-6">
<div className="flex items-center justify-between gap-3 mb-4 flex-wrap">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
<Gift className="w-5 h-5 text-brand-600" />
</div>
<div>
<BackLink href="/dashboard" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Bundle deals</h1>
<p className="text-sm text-gray-500">Sell a set of tickets together for one price, e.g. 5 adults + 3 children for R500</p>
</div>
</div>
{canView && event && (
<button
onClick={() => setEditing({ id: null, draft: blankDraft(event.eventOptions || []) })}
disabled={(event.eventOptions || []).length === 0}
className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50"
>
<Plus className="w-4 h-4" /> New bundle
</button>
)}
</div>
{!canView && (
<div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need supervisor access to manage bundle deals.</div>
)}
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
{info && <div className="mb-3 p-3 border rounded bg-green-50 text-green-800 text-sm">{info}</div>}
{canView && (
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="mb-3 w-full sm:w-96">
<label className="block text-sm font-medium text-gray-700 mb-1">Event</label>
<select className={inputCls} value={eventId} onChange={e => setEventId(e.target.value)}>
{events.map(ev => <option key={ev.id} value={ev.id}>{ev.title} · {fmtDate(ev.startDate)}</option>)}
</select>
</div>
<p className="text-xs text-gray-500 mb-3">
Bundles apply automatically, as many times as someone&apos;s tickets allow, and only when they&apos;re cheaper than the tickets
at today&apos;s prices (early-bird or staff prices included). Coupon codes come off afterwards.
</p>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Bundle</TableHead>
<TableHead>Price</TableHead>
<TableHead>Used</TableHead>
<TableHead>Available</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bundles.map(b => {
const status = bundleStatus(b);
const save = b.standardValue - b.price;
return (
<TableRow key={b.id}>
<TableCell>
<div className="font-semibold text-gray-900">{b.name}</div>
<div className="text-xs text-gray-600">{b.summary}</div>
{b.description && <div className="text-xs text-gray-500">{b.description}</div>}
</TableCell>
<TableCell className="text-sm">
{fmtRand(b.price)}
<div className={`text-xs ${save > 0 ? "text-green-700" : "text-amber-700"}`}>
{save > 0 ? `Saves ${fmtRand(save)} on ${fmtRand(b.standardValue)}` : `No saving on ${fmtRand(b.standardValue)}`}
</div>
</TableCell>
<TableCell className="text-sm">
{b.uses || 0}× <span className="text-xs text-gray-500">on {b.registrations || 0} registration{b.registrations === 1 ? "" : "s"}</span>
<div className="text-xs text-gray-500">{fmtRand(b.totalDiscount || 0)} given</div>
</TableCell>
<TableCell className="text-xs text-gray-600">
{b.validFrom || b.validUntil ? `${b.validFrom ? fmtDate(b.validFrom) : "Now"} – ${b.validUntil ? fmtDate(b.validUntil) : "no end"}` : "Always"}
</TableCell>
<TableCell><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${status.cls}`}>{status.label}</span></TableCell>
<TableCell className="text-right whitespace-nowrap">
<button className="px-2 py-1 text-xs rounded border hover:bg-gray-50 mr-1" onClick={() => setEditing({ id: b.id, draft: draftFromBundle(b) })}>Edit</button>
<button className={`px-2 py-1 text-xs rounded text-white mr-1 ${b.isActive ? "bg-amber-500 hover:bg-amber-600" : "bg-green-600 hover:bg-green-700"}`} onClick={() => toggleActive(b)}>
{b.isActive ? "Turn off" : "Turn on"}
</button>
<button className="px-2 py-1 text-xs rounded border text-red-700 hover:bg-red-50" onClick={() => remove(b)} aria-label={`Delete ${b.name}`}><Trash2 className="w-3.5 h-3.5" /></button>
</TableCell>
</TableRow>
);
})}
{!fetching && bundles.length === 0 && (
<TableRow><TableCell colSpan={6} className="text-center text-sm text-gray-500 py-8">{event ? "No bundle deals for this event yet." : "Choose an event."}</TableCell></TableRow>
)}
</TableBody>
</Table>
</div>
</div>
)}
{editing && event && (
<BundleModal
token={token!}
event={event}
bundleId={editing.id}
initial={editing.draft}
onClose={() => setEditing(null)}
onSaved={(msg) => { setEditing(null); setInfo(msg); load(); }}
/>
)}
</div>
);
}
function BundleModal({ token, event, bundleId, initial, onClose, onSaved }: {
token: string;
event: EventLite;
bundleId: string | null;
initial: Draft;
onClose: () => void;
onSaved: (message: string) => void;
}) {
const [d, setD] = useState<Draft>(initial);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setD(prev => ({ ...prev, [key]: value }));
const options = event.eventOptions || [];
const setItem = (i: number, patch: Partial<ItemDraft>) => set("items", d.items.map((it, j) => (j === i ? { ...it, ...patch } : it)));
const standardValue = d.items.reduce((s, it) => s + unitPrice(options, it) * (Number(it.quantity) || 0), 0);
const saving_ = standardValue - (Number(d.price) || 0);
const save = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSaving(true);
try {
const body = {
name: d.name.trim(),
description: d.description.trim() || null,
price: Number(d.price),
items: d.items.map(it => ({ eventOptionId: it.eventOptionId, variantId: it.variantId, quantity: Number(it.quantity) })),
validFrom: d.validFrom ? new Date(d.validFrom).toISOString() : null,
validUntil: d.validUntil ? new Date(d.validUntil).toISOString() : null,
isActive: d.isActive,
};
if (bundleId) {
await apiFetch(`/api/bundles/${bundleId}`, { method: "PUT", authToken: token, body });
onSaved(`${body.name} saved.`);
} else {
await apiFetch(`/api/bundles/event/${event.id}`, { method: "POST", authToken: token, body });
onSaved(`${body.name} created.`);
}
} catch (err) {
setError(errorMessage(err) || "Failed to save");
} finally {
setSaving(false);
}
};
return (
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={onClose}>
<form onSubmit={save} className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col" onClick={e => e.stopPropagation()}>
<div className="flex items-center justify-between p-4 border-b">
<h2 className="font-semibold">{bundleId ? "Edit bundle" : "New bundle deal"} <span className="text-sm font-normal text-gray-500">· {event.title}</span></h2>
<button type="button" onClick={onClose} aria-label="Close"><X className="w-5 h-5 text-gray-500" /></button>
</div>
<div className="p-4 space-y-5 overflow-y-auto">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
<input className={inputCls} value={d.name} onChange={e => set("name", e.target.value)} placeholder="Family deal" required maxLength={80} />
<p className="text-xs text-gray-500 mt-1">Shown to buyers and on receipts.</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Description (optional)</label>
<input className={inputCls} value={d.description} onChange={e => set("description", e.target.value)} placeholder="Bring the whole family" />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Tickets in the bundle</label>
<div className="space-y-2">
{d.items.map((it, i) => {
const opt = options.find(o => o.id === it.eventOptionId);
return (
<div key={i} className="flex flex-wrap sm:flex-nowrap items-center gap-2">
<input type="number" min="1" step="1" className={`${inputCls} w-20 shrink-0`} value={it.quantity} onChange={e => setItem(i, { quantity: e.target.value })} aria-label="Quantity" required />
<span className="text-sm text-gray-500">×</span>
<select className={`${inputCls} min-w-0`} value={it.eventOptionId} onChange={e => setItem(i, { eventOptionId: e.target.value, variantId: null })}>
{options.map(o => <option key={o.id} value={o.id}>{o.name} ({fmtRand(o.price)})</option>)}
</select>
{(opt?.variants || []).length > 0 && (
<select className={`${inputCls} min-w-0`} value={it.variantId || ""} onChange={e => setItem(i, { variantId: e.target.value || null })} aria-label="Variant">
<option value="">Any variant</option>
{(opt?.variants || []).map(v => <option key={v.id} value={v.id}>{v.name}</option>)}
</select>
)}
<button type="button" onClick={() => set("items", d.items.filter((_, j) => j !== i))} disabled={d.items.length <= 1}
className="p-2 rounded border text-gray-500 hover:bg-gray-50 disabled:opacity-40" aria-label="Remove ticket">
<X className="w-4 h-4" />
</button>
</div>
);
})}
</div>
<button type="button" onClick={() => set("items", [...d.items, { eventOptionId: options[0]?.id || "", variantId: null, quantity: "1" }])}
className="mt-2 inline-flex items-center gap-1 text-sm text-brand-700 hover:underline">
<Plus className="w-4 h-4" /> Add a ticket type
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Bundle price (R)</label>
<input type="number" min="0" step="0.01" className={inputCls} value={d.price} onChange={e => set("price", e.target.value)} required />
</div>
<div className="flex items-end">
<div className={`text-sm ${saving_ > 0 ? "text-green-700" : "text-amber-700"}`}>
Separately: {fmtRand(standardValue)}
{d.price !== "" && (saving_ > 0 ? ` · saves ${fmtRand(saving_)}` : " · no saving at the standard price")}
</div>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Available from</label>
<input type="datetime-local" className={inputCls} value={d.validFrom} onChange={e => set("validFrom", e.target.value)} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Available until</label>
<input type="datetime-local" className={inputCls} value={d.validUntil} onChange={e => set("validUntil", e.target.value)} />
</div>
</div>
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" checked={d.isActive} onChange={e => set("isActive", e.target.checked)} /> On sale
</label>
<p className="text-xs text-gray-500 -mt-3">Registrations that already have this bundle keep it if you turn it off or change it later.</p>
{error && <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
</div>
<div className="flex justify-end gap-3 p-4 border-t">
<button type="button" onClick={onClose} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
<button type="submit" disabled={saving} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{saving ? "Saving…" : bundleId ? "Save changes" : "Create bundle"}
</button>
</div>
</form>
</div>
);
}
@@ -7,6 +7,7 @@ import { apiFetch, fetchAllUsers } from "@/lib/api";
import { scoreUser } from "@/lib/fuzzyMatch";
import { useDismissingState } from "@/hooks/useDismissingState";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { UserPlus, CreditCard } from "lucide-react";
import { errorMessage } from "@/lib/utils";
@@ -275,6 +276,13 @@ export default function ManualRegistrationPage() {
}, 0);
}, [options, quantities]);
const basket = useMemo(() => Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
}), [quantities]);
const bundleQuote = useBundleQuote({ eventId: selectedEventId, basket, token, forUserId: pickedUserId });
const payable = coupon ? coupon.total : bundleQuote ? bundleQuote.total : totalDue;
const submit = async () => {
if (!token) return;
setError(null);
@@ -614,10 +622,7 @@ export default function ManualRegistrationPage() {
<div className="mt-6 max-w-md">
<CouponCodeField
eventId={selectedEventId}
basket={Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
})}
basket={basket}
token={token}
forUserId={pickedUserId}
applied={coupon}
@@ -628,8 +633,9 @@ export default function ManualRegistrationPage() {
<div className="flex items-center justify-between mt-6">
<div className="text-sm">
Total due: <span className="font-semibold">R {(coupon ? coupon.total : totalDue).toFixed(2)}</span>
{coupon && coupon.discount > 0 && <span className="ml-2 text-xs text-gray-500 line-through">R {totalDue.toFixed(2)}</span>}
<BundleSavings applications={bundleQuote?.bundles} />
Total due: <span className="font-semibold">R {payable.toFixed(2)}</span>
{payable < totalDue - 0.005 && <span className="ml-2 text-xs text-gray-500 line-through">R {totalDue.toFixed(2)}</span>}
</div>
<button disabled={submitting} onClick={submit} className="px-4 py-2 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 shadow-sm">{submitting ? 'Creating…' : 'Create registration'}</button>
</div>
@@ -30,6 +30,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks },
{ href: "/dashboard/supervisor/consent", label: "Parental consent", description: "Youth events: consent status and medical list", icon: ShieldCheck },
{ href: "/dashboard/supervisor/coupons", label: "Coupon codes", description: "Discounts for staff, leaders and promotions", icon: TicketPercent },
{ href: "/dashboard/supervisor/bundles", label: "Bundle deals", description: "Tickets sold together for one price", icon: Gift },
{ href: "/dashboard/staff/ticket-scanning", label: "Open scanner", description: "Use your device camera to validate tickets", icon: QrCode },
{ href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen },
{ href: "/dashboard/supervisor/reports", label: "Reports", description: "View, export, and email reports", icon: BarChart2 },
@@ -14,6 +14,7 @@ import { TransferTicketModal, canOfferTransfer } from "@/components/shared/Trans
import { ClipboardList, Calendar, Ticket, ChevronRight } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { registrationOptionUnitPrice } from "@/lib/pricing";
import { BundleSavings } from "@/components/shared/BundleDeals";
import type { Event, EventOption, Payment, Registration, RegistrationOption, Ticket as TicketRecord } from "@/types";
// Helper formatters
@@ -1096,9 +1097,10 @@ export default function UserDashboardPage() {
<div>
{renderGroup('Early bird', earlyBirdRows)}
{renderGroup('Standard price', standardRows)}
{Number(activeReg.discountTotal || 0) > 0 && (
<BundleSavings applications={activeReg.bundleApplications} className="mt-2" />
{Number(activeReg.discountTotal || 0) - Number(activeReg.bundleDiscount || 0) > 0.005 && (
<div className="text-sm text-green-700 mt-2">
Discount code{activeCoupon?.coupon?.code ? <> <span className="font-mono font-semibold">{activeCoupon.coupon.code}</span></> : null} — −{formatRand(Number(activeReg.discountTotal))}
Discount code{activeCoupon?.coupon?.code ? <> <span className="font-mono font-semibold">{activeCoupon.coupon.code}</span></> : null} — −{formatRand(Number(activeReg.discountTotal) - Number(activeReg.bundleDiscount || 0))}
</div>
)}
{canModifyActive && activeBill && activeBill.outstanding > 0 && !activeCoupon && (
@@ -45,11 +45,14 @@ type Event = {
location?: string | null;
waitlistEnabled?: boolean;
allowSponsorships?: boolean;
bundles?: PublicBundle[];
};
import { apiFetch, ApiError, resolveToApiOrigin } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { formatDateTimeRange } from "@/lib/date";
import { BundleOffers } from "@/components/shared/BundleDeals";
import type { PublicBundle } from "@/types";
// Tiered low-stock threshold: larger events use a smaller percentage.
// Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made
@@ -262,6 +265,7 @@ function TicketList({ event }: { event: Event }) {
}
return (
<div className="space-y-2">
<BundleOffers bundles={event.bundles} />
{options.map((opt) => {
const hasVariants = Array.isArray(opt.variants) && opt.variants.length > 0;
const soldOut = (opt.stockLimit ?? 0) > 0 && opt.availableCount !== undefined && opt.availableCount <= 0;
@@ -4,6 +4,8 @@ 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 { PublicBundle } from "@/types";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
import { analyticsSessionId } from "@/lib/analytics";
@@ -49,6 +51,7 @@ export type RegisterEvent = {
requiresParentalConsent?: boolean;
collectGender?: boolean;
waitlistEnabled?: boolean;
bundles?: PublicBundle[];
};
type WaitlistOffer = { eventOptionId: string; variantId: string | null; quantity: number; expiresAt: string; optionName: string; variantName: string | null };
@@ -359,8 +362,10 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
}, [event]);
const basket = useMemo(() => buildItems(), [quantities]); // eslint-disable-line react-hooks/exhaustive-deps
// The server prices the basket (staff price, tiers) when checking a code, so its total wins.
const payable = coupon ? coupon.total : total;
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;
function buildItems() {
const items: { eventOptionId: string; quantity: number; variantId?: string }[] = [];
@@ -544,6 +549,8 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
</div>
)}
{!eventSoldOut && <BundleOffers bundles={event.bundles} className="mb-3" />}
<div className="space-y-3">
{(event.eventOptions || []).map((opt) => (
<OptionCard
@@ -556,6 +563,16 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
))}
</div>
{!eventSoldOut && (
<BundleBuilder
className="mt-3"
bundles={event.bundles}
options={event.eventOptions || []}
qty={qtyFor}
onSetQuantity={(optionId, variantId, quantity) => handleQtyChange(variantId ? `${optionId}:${variantId}` : optionId, quantity)}
/>
)}
{(() => {
// Collect all upcoming early-bird tiers across all options
const now = new Date();
@@ -599,11 +616,12 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
<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-gray-500">
<span className="line-through">R{coupon.subtotal.toFixed(2)}</span>
<span className="ml-2 text-green-700">−R{coupon.discount.toFixed(2)}</span>
</div>
<div className="text-sm text-green-700">Code {coupon.code} −R{coupon.discount.toFixed(2)}</div>
)}
<div className="text-lg font-semibold">Total: R{payable.toFixed(2)}</div>
</div>
@@ -5,6 +5,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { apiFetch } from "@/lib/api";
import { AuthResponse, TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { errorMessage } from "@/lib/utils";
import type { Registration } from "@/types";
@@ -217,6 +218,12 @@ export default function SelfServicePage() {
}, 0);
}, [selectedEvent, quantities]);
const kioskBasket = useMemo(() => Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
}), [quantities]);
const bundleQuote = useBundleQuote({ eventId: selectedEventId || "", basket: kioskBasket, token: supervisorToken, forUserId: matchedAccount?.id ?? null });
// Does the selected event have a required form?
const eventHasRequiredForm = useMemo(() => {
return !!(selectedEvent?.form?.isRequired && (selectedEvent.form.fields || []).some(f => f.type !== 'statement'));
@@ -1034,10 +1041,7 @@ export default function SelfServicePage() {
<div className="mt-4">
<CouponCodeField
eventId={selectedEventId}
basket={Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
})}
basket={kioskBasket}
token={supervisorToken}
forUserId={matchedAccount?.id ?? null}
applied={kioskCoupon}
@@ -1047,10 +1051,11 @@ export default function SelfServicePage() {
)}
{total > 0 && (
<div className="mt-3 text-right text-base font-semibold text-gray-800">
{kioskCoupon && kioskCoupon.discount > 0 && (
<span className="mr-2 text-sm font-normal text-gray-500 line-through">{fmtCurrency(kioskCoupon.subtotal)}</span>
<BundleSavings applications={bundleQuote?.bundles} className="flex flex-col items-end font-normal" />
{((kioskCoupon && kioskCoupon.discount > 0) || bundleQuote) && (
<span className="mr-2 text-sm font-normal text-gray-500 line-through">{fmtCurrency(kioskCoupon?.subtotal ?? bundleQuote?.subtotal ?? total)}</span>
)}
Total: {fmtCurrency(kioskCoupon ? kioskCoupon.total : total)}
Total: {fmtCurrency(kioskCoupon ? kioskCoupon.total : bundleQuote ? bundleQuote.total : total)}
</div>
)}
</div>