Pick sessions (frontend), roadmap and handover docs

Event wizard: how people book (whole course / pick sessions), capacity
per session and per-option session mode. Session picker on the public
registration page, Manual registration and the kiosk; at the door points
to Manual registration. Register, tickets and My Events handle picked
sessions. Adds docs/ROADMAP-v2.md and docs/HANDOVER.md so work can carry
on from another machine, and a pick-sessions e2e test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 09:25:21 +02:00
co-authored by Claude Opus 5.5
parent e22566bdeb
commit abf9ca714d
24 changed files with 1756 additions and 81 deletions
@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
@@ -15,7 +16,7 @@ import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type Lu
import { errorMessage } from "@/lib/utils";
import { optionUnitNow, variantUnitNow } from "@/lib/pricing";
import { printTicketCards, ticketTypeLabel as ticketLabel } from "@/lib/ticketPrint";
import { todaysSession } from "@/lib/sessions";
import { isPickOption, todaysSession } from "@/lib/sessions";
import type { Event, EventOption, PublicBundle, Registration, Ticket as TicketRecord, UserSummary } from "@/types";
type NewAttendee = { name: string; email: string | null; phone: string | null; notifPref: "email" | "whatsapp" | "both" };
@@ -96,6 +97,7 @@ export default function AtTheDoorPage() {
const [eventId, setEventId] = useState("");
const [eventOptions, setEventOptions] = useState<EventOption[]>([]);
const [doorHasPickOptions, setDoorHasPickOptions] = useState(false);
const [showOptionsModal, setShowOptionsModal] = useState(false);
const [pendingUser, setPendingUser] = useState<NewAttendee | null>(null);
const [doorCoupon, setDoorCoupon] = useState<AppliedCoupon | null>(null);
@@ -158,7 +160,11 @@ export default function AtTheDoorPage() {
authToken: token
});
setEventOptions(ev.options || ev.eventOptions || []);
// Per-session tickets ("pick sessions") are booked from Manual registration,
// which has the session picker.
const all = ev.options || ev.eventOptions || [];
setEventOptions(all.filter(o => !isPickOption(ev, o)));
setDoorHasPickOptions(all.some(o => isPickOption(ev, o)));
setDoorAllowsNames(!!ev.allowNamedAttendees || !!ev.requiresParentalConsent);
setDoorYouthStart(ev.requiresParentalConsent ? ev.startDate : null);
setDoorCollectGender(!!ev.collectGender);
@@ -493,6 +499,11 @@ export default function AtTheDoorPage() {
{mode === "refund" && (
<DoorRefundPanel token={token} eventId={eventId} setInfo={setInfo} />
)}
{doorHasPickOptions && (
<div className="mt-4 p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm">
This event has per-session tickets. Book those from <Link className="underline font-medium" href="/dashboard/supervisor/manual">Manual registration</Link>, which lets you choose the sessions.
</div>
)}
<OptionsModal
open={showOptionsModal}
onClose={() => { setShowOptionsModal(false); setPendingEditReg(null); }}
@@ -91,7 +91,9 @@ function AttendancePageInner() {
const key = `${row.ticketId}:${sessionId}`;
setPending(key);
try {
await apiFetch(`/api/attendance/${eventId}/mark`, { method: "POST", authToken: token, body: { ticketId: row.ticketId, sessionId, present } });
// Picked sessions have a ticket per session.
const ticketId = row.sessionTickets?.[sessionId] || row.ticketId;
await apiFetch(`/api/attendance/${eventId}/mark`, { method: "POST", authToken: token, body: { ticketId, sessionId, present } });
const col = reg?.columns.find(c => c.id === sessionId);
setInfo(`${row.name || "Attendee"} marked ${present ? "present" : "absent"}${multi && col ? ` for ${col.label}` : ""}.`);
await load();
@@ -229,6 +231,9 @@ function AttendancePageInner() {
{columns.map(c => {
const qty = r.checkIns[c.id] || 0;
const key = `${r.ticketId}:${c.id}`;
if (r.bookedSessions && !r.bookedSessions.includes(c.id)) {
return <td key={c.id} className="px-2 py-2 text-center text-gray-300" title="Not booked for this session">—</td>;
}
const disabled = !canManage || c.cancelled || pending !== null || reg.event.cashupStatus === "closed";
return (
<td key={c.id} className="px-2 py-2 text-center">
@@ -95,6 +95,7 @@ type OptionDraft = {
staffPrice?: string; // empty → no staff price
earlyBirdTiers: Tier[]; // option-level (used only when no variants)
variants: Variant[];
sessionMode?: "all" | "pick"; // "pick sessions" events only
};
type SectionDraft = {
@@ -209,7 +210,7 @@ function FormBuilder({ value, onChange, title = "Registration Form Fields", gate
// ─── Items & Pricing substep editors ────────────────────────────────────────
/** Substep 0 — bare option rows */
function OptionsEditor({ options, onChange, required }: { options: OptionDraft[]; onChange: (o: OptionDraft[]) => void; required?: boolean }) {
function OptionsEditor({ options, onChange, required, pickMode }: { options: OptionDraft[]; onChange: (o: OptionDraft[]) => void; required?: boolean; pickMode?: boolean }) {
const upd = (i: number, patch: Partial<OptionDraft>) => { const c = options.slice(); c[i] = { ...c[i], ...patch }; onChange(c); };
const rem = (i: number) => { const c = options.slice(); c.splice(i, 1); onChange(c); };
const add = () => {
@@ -245,6 +246,15 @@ function OptionsEditor({ options, onChange, required }: { options: OptionDraft[]
<input type="number" step="1" min="0" className="border rounded px-2 py-1.5 text-sm w-24" placeholder="(none)"
value={opt.staffPrice ?? ""} onChange={e => upd(i, { staffPrice: e.target.value })} />
</div>
{pickMode && (
<div>
<label className="block text-[10px] text-gray-500 mb-0.5" title="Pick sessions: bought per session — the price and stock are per session">Sessions</label>
<select className="border rounded px-2 py-1.5 text-sm" value={opt.sessionMode || "all"} onChange={e => upd(i, { sessionMode: e.target.value as "all" | "pick" })}>
<option value="all">All sessions</option>
<option value="pick">Pick sessions (price per session)</option>
</select>
</div>
)}
<div className="flex items-center gap-3 pb-1">
<label className="text-xs flex items-center gap-1 cursor-pointer whitespace-nowrap">
<input type="checkbox" checked={opt.isMainTicket} onChange={e => upd(i, { isMainTicket: e.target.checked })} /> Main ticket
@@ -826,6 +836,7 @@ interface EventDraft {
allowTicketTransfer: boolean; collectGender: boolean;
allowSponsorships: boolean; sponsorshipGoalSpots: string; showSponsorshipProgress: boolean;
scheduleType: "single" | "sessions";
attendanceMode: "whole" | "pick";
}
const blankDraft = (location = ""): EventDraft => ({
@@ -840,6 +851,7 @@ const blankDraft = (location = ""): EventDraft => ({
allowTicketTransfer: true, collectGender: false,
allowSponsorships: false, sponsorshipGoalSpots: "", showSponsorshipProgress: true,
scheduleType: "single",
attendanceMode: "whole",
});
// "YYYY-MM-DDTHH:MM" (local) → ISO
@@ -886,6 +898,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
contactName: ev.contactName || "", contactPhone: ev.contactPhone || "", contactEmail: ev.contactEmail || "",
location: ev.location || "",
scheduleType: ev.scheduleType === "sessions" ? "sessions" : "single",
attendanceMode: ev.attendanceMode === "pick" ? "pick" : "whole",
} : blankDraft(settings.org_address || ""));
// ── multi-day schedule + attendance settings ──
@@ -904,6 +917,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
}));
const updAttendance = (patch: Partial<AttendanceDraft>) => setAttendance(a => ({ ...a, ...patch }));
const multi = draft.scheduleType === "sessions";
const pickMode = multi && draft.attendanceMode === "pick";
// A multi-session event's dates come from its sessions.
const scheduleBounds = useMemo(() => {
const active = sortSessions(sessions).filter(s => !s.cancelled && s.startsAt && s.endsAt);
@@ -926,6 +940,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
isMainTicket: !!o.isMainTicket,
stockLimit: String(o.stockLimit ?? "0"),
staffPrice: o.staffPrice !== null && o.staffPrice !== undefined ? String(o.staffPrice) : "",
sessionMode: o.sessionMode || "all",
// Option-level tiers only (no variantId)
earlyBirdTiers: allTiers
.filter((t) => !t.variantId)
@@ -1075,7 +1090,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
// Update option + variants first to get/confirm variant IDs
const updated = await apiFetch<EventOption>(`/api/events/options/${opt.id}`, {
method: "PUT", authToken: token || undefined,
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, variants: variantsPayload }
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all", variants: variantsPayload }
});
// Build variant tiers with confirmed IDs from response
@@ -1107,7 +1122,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
// New option added during edit
const created = await apiFetch<EventOption>(`/api/events/${eventId}/options`, {
method: "POST", authToken: token || undefined,
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null }
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
});
if (created?.id) {
const updated = await apiFetch<EventOption>(`/api/events/options/${created.id}`, {
@@ -1154,13 +1169,13 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
// Update the auto-created main ticket
await apiFetch(`/api/events/options/${existingMain.id}`, {
method: "PUT", authToken: token || undefined,
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: true, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null }
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: true, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
});
optId = existingMain.id;
} else {
const created = await apiFetch<EventOption>(`/api/events/${eventId}/options`, {
method: "POST", authToken: token || undefined,
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null }
body: { name: opt.name, price: parseFloat(opt.price || "0"), isMainTicket: opt.isMainTicket, stockLimit: parseInt(opt.stockLimit || "0"), staffPrice: opt.staffPrice ? parseFloat(opt.staffPrice) : null, sessionMode: pickMode ? opt.sessionMode || "all" : "all" }
});
optId = created?.id;
}
@@ -1234,7 +1249,8 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
endDate: multi && scheduleBounds ? isoOf(scheduleBounds.end) : new Date(draft.endDate).toISOString(),
scheduleType: draft.scheduleType,
...(multi ? {
sessions: sortedSessions.map(s => ({ id: s.id, label: s.label.trim() || null, startsAt: isoOf(s.startsAt), endsAt: isoOf(s.endsAt), location: s.location.trim() || null, cancelled: s.cancelled })),
attendanceMode: draft.attendanceMode,
sessions: sortedSessions.map(s => ({ id: s.id, label: s.label.trim() || null, startsAt: isoOf(s.startsAt), endsAt: isoOf(s.endsAt), location: s.location.trim() || null, cancelled: s.cancelled, capacity: pickMode && s.capacity.trim() ? parseInt(s.capacity, 10) : null })),
lateJoinEnabled: attendance.lateJoinEnabled,
lateJoinUntilSessionIndex: attendance.lateJoinEnabled ? sortedSessions.findIndex(s => s.key === attendance.lateJoinUntilKey) : -1,
latePricing: attendance.latePricing,
@@ -1437,7 +1453,16 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
{multi && <p className="text-[10px] text-gray-400 mt-1">One registration and one ticket for every session, e.g. every Wednesday for 5 weeks. Check-in is per session.</p>}
</div>
{multi ? (
<SessionsEditor sessions={sessions} onChange={setSessions} defaultLocation={draft.location} />
<>
<SessionsEditor sessions={sessions} onChange={setSessions} defaultLocation={draft.location} showCapacity={pickMode} />
<div>
<div className="block text-xs text-gray-600 mb-1">How people book</div>
<div className="space-y-1">
<label className="flex items-start gap-2 text-sm"><input type="radio" className="mt-1" name="attendance-mode" checked={draft.attendanceMode === "whole"} onChange={() => upd({ attendanceMode: "whole" })} /><span><span className="font-medium">The whole course</span><span className="block text-xs text-gray-500">One ticket for every session.</span></span></label>
<label className="flex items-start gap-2 text-sm"><input type="radio" className="mt-1" name="attendance-mode" disabled={draft.requiresParentalConsent} checked={draft.attendanceMode === "pick"} onChange={() => upd({ attendanceMode: "pick" })} /><span><span className="font-medium">Pick sessions</span><span className="block text-xs text-gray-500">People choose which sessions to come to (e.g. day passes or a drop-in class). Set which tickets are per session in Items &amp; Pricing, and an optional capacity per session above.{draft.requiresParentalConsent ? " Not available on youth events." : ""}</span></span></label>
</div>
</div>
</>
) : (
<div className="grid sm:grid-cols-2 gap-3">
<DTInput label="Start" required value={draft.startDate} onChange={v => upd({ startDate: v })} />
@@ -1506,7 +1531,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
{step === 1 && pricingSubstep === 0 && (
<div>
<p className="text-xs text-gray-500 mb-3">Define your ticket types or purchasable items. Variants and early-bird pricing are configured in the next two steps.</p>
<OptionsEditor options={options} onChange={handleOptionsChange} required={mode === "create"} />
<OptionsEditor options={options} onChange={handleOptionsChange} required={mode === "create"} pickMode={pickMode} />
</div>
)}
{step === 1 && pricingSubstep === 1 && (
@@ -12,6 +12,8 @@ import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload,
import { UserPlus, CreditCard } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { optionUnitNow, variantUnitNow } from "@/lib/pricing";
import { isPickOption } from "@/lib/sessions";
import { SessionPicker } from "@/components/events/SessionPicker";
import type { Event, EventOption, PublicBundle, Registration, RegistrationOption, User } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
@@ -268,29 +270,45 @@ export default function ManualRegistrationPage() {
}
}, [selectedEventId, events]);
// The events list doesn't carry bundle deals; the single-event response does.
// The events list doesn't carry bundle deals or places per session; the single-event
// response does.
const [fullEvent, setFullEvent] = useState<Event | null>(null);
useEffect(() => {
if (!selectedEventId) { setBundles([]); return; }
if (!selectedEventId) { setBundles([]); setFullEvent(null); return; }
let cancelled = false;
apiFetch<Event>(`/api/events/${selectedEventId}`, { authToken: token || undefined })
.then(ev => { if (!cancelled) setBundles(ev?.bundles || []); })
.catch(() => { if (!cancelled) setBundles([]); });
.then(ev => { if (!cancelled) { setBundles(ev?.bundles || []); setFullEvent(ev || null); } })
.catch(() => { if (!cancelled) { setBundles([]); setFullEvent(null); } });
return () => { cancelled = true; };
}, [selectedEventId, token]);
// "Pick sessions" options: the sessions chosen per quantity key.
const [picks, setPicks] = useState<Record<string, string[]>>({});
useEffect(() => { setPicks({}); }, [selectedEventId]);
const pickOpt = (optionId: string) => {
const o = (fullEvent?.eventOptions || []).find(x => x.id === optionId);
return fullEvent && o && isPickOption(fullEvent, o) ? o : null;
};
const times = (key: string) => (pickOpt(key.split("::")[0]) ? (picks[key] || []).length : 1);
const picker = (key: string, optionId: string) => {
const o = pickOpt(optionId);
if (!o || !fullEvent || !(quantities[key] > 0)) return null;
return <SessionPicker event={fullEvent} option={o} staff quantity={quantities[key]} selected={picks[key] || []} onChange={ids => setPicks(p => ({ ...p, [key]: ids }))} />;
};
const totalDue = useMemo(() => {
return options.reduce((sum, o) => {
if ((o.variants || []).length > 0) {
return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * variantUnitNow(o, v), 0);
return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * times(`${o.id}::${v.id}`) * variantUnitNow(o, v), 0);
}
return sum + (quantities[o.id] || 0) * optionUnitNow(o);
return sum + (quantities[o.id] || 0) * times(o.id) * optionUnitNow(o);
}, 0);
}, [options, quantities]);
}, [options, quantities, picks, fullEvent]); // eslint-disable-line react-hooks/exhaustive-deps
const basket = useMemo(() => Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, variantId: variantId || null };
}), [quantities]);
return { eventOptionId, quantity, variantId: variantId || null, ...(pickOpt(eventOptionId) ? { sessionIds: picks[key] || [] } : {}) };
}), [quantities, picks, fullEvent]); // eslint-disable-line react-hooks/exhaustive-deps
const bundleQuote = useBundleQuote({ eventId: selectedEventId, basket, token, forUserId: pickedUserId });
const payable = coupon ? coupon.total : bundleQuote ? bundleQuote.total : totalDue;
@@ -304,9 +322,11 @@ export default function ManualRegistrationPage() {
.filter(([, qty]) => qty > 0)
.map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}) };
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}), ...(pickOpt(eventOptionId) ? { sessionIds: picks[key] || [] } : {}) };
});
if (opts.length === 0) { setError("Please select at least one ticket option."); return; }
const noSessions = opts.find(o => "sessionIds" in o && o.sessionIds && o.sessionIds.length === 0);
if (noSessions) { setError(`Choose the sessions for "${options.find(o => o.id === noSessions.eventOptionId)?.name || "the ticket"}".`); return; }
if (selectedIsYouth) {
const missing = consentDetailsMissing(options, manualQtyFor, attendeeEntries, selectedEv.startDate);
if (missing) { setError(missing); return; }
@@ -564,7 +584,8 @@ export default function ManualRegistrationPage() {
const basePrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const key = `${opt.id}::${v.id}`;
return (
<div key={v.id} className="flex items-center justify-between px-3 py-2 border-b last:border-b-0">
<div key={v.id} className="border-b last:border-b-0">
<div className="flex items-center justify-between px-3 py-2">
<div>
<div className="text-sm">{v.name}</div>
<div className="text-xs text-gray-500">
@@ -582,6 +603,8 @@ export default function ManualRegistrationPage() {
/>
</div>
</div>
{picker(key, opt.id) && <div className="px-3 pb-2">{picker(key, opt.id)}</div>}
</div>
);
})}
</div>
@@ -605,6 +628,7 @@ export default function ManualRegistrationPage() {
onChange={e => setQuantities(q => ({ ...q, [opt.id]: Math.max(0, parseInt(e.target.value || '0')) }))}
/>
</div>
{picker(opt.id, opt.id)}
</div>
);
})}
@@ -17,6 +17,7 @@ import { errorMessage } from "@/lib/utils";
import { registrationOptionUnitPrice } from "@/lib/pricing";
import { BundleSavings } from "@/components/shared/BundleDeals";
import { MyCertificates } from "@/components/events/MyCertificates";
import { isPickOption } from "@/lib/sessions";
import type { Event, EventOption, Payment, Registration, RegistrationOption, Ticket as TicketRecord } from "@/types";
// Helper formatters
@@ -484,8 +485,13 @@ export default function UserDashboardPage() {
return !isEventOver(activeReg.event);
}, [activeReg]);
// Picked-session lines can't be edited here (book more by registering), but still count.
const pickedLinesTotal = useMemo(() => (activeReg?.registrationOptions || [])
.filter(ro => ro.sessionId)
.reduce((s, ro) => s + (ro.lineTotal ?? (ro.quantity || 0) * (ro.priceSnapshot || 0)), 0), [activeReg]);
const editTotal = useMemo(() => {
return editEventOptions.reduce((sum, eo) => {
return pickedLinesTotal + editEventOptions.reduce((sum, eo) => {
if (Array.isArray(eo.variants) && eo.variants.length > 0) {
return sum + eo.variants.reduce((vsum, v) => {
const qty = editQuantities[`${eo.id}:${v.id}`] || 0;
@@ -494,7 +500,7 @@ export default function UserDashboardPage() {
}
return sum + (editQuantities[eo.id] || 0) * effectiveEventOptionUnitPrice(eo, null);
}, 0);
}, [editEventOptions, editQuantities]);
}, [editEventOptions, editQuantities, pickedLinesTotal]);
const beginEdit = async () => {
if (!activeReg || !token) return;
@@ -503,13 +509,13 @@ export default function UserDashboardPage() {
try {
// Load event options (with variants) for this event
const eventData = await apiFetch<Event>(`/api/events/${encodeURIComponent(activeReg.eventId)}`);
const eventOptions = eventData?.eventOptions || [];
const eventOptions = (eventData?.eventOptions || []).filter((eo) => !isPickOption(eventData, eo));
const regOptById = new Map<string, RegistrationOption>((activeReg.registrationOptions || []).map((o) => [o.id, o]));
// Prefill quantities from the current registration
const qtyMap: Record<string, number> = {};
for (const ro of (activeReg.registrationOptions || [])) {
for (const ro of (activeReg.registrationOptions || []).filter(r => !r.sessionId)) {
const key = ro.variantId ? `${ro.eventOptionId}:${ro.variantId}` : ro.eventOptionId;
qtyMap[key] = (qtyMap[key] || 0) + (ro.quantity || 0);
}
@@ -519,7 +525,7 @@ export default function UserDashboardPage() {
const minQtyMap: Record<string, number> = {};
for (const t of tickets) {
const ro = t.registrationOptionId ? regOptById.get(t.registrationOptionId) : undefined;
if (!ro) continue;
if (!ro || ro.sessionId) continue;
const key = ro.variantId ? `${ro.eventOptionId}:${ro.variantId}` : ro.eventOptionId;
minQtyMap[key] = (minQtyMap[key] || 0) + (t.quantity || 0);
}
@@ -21,6 +21,7 @@ type EventOption = {
stockLimit?: number;
availableCount?: number;
isMainTicket?: boolean;
sessionMode?: "all" | "pick";
earlyBirdTiers?: { id: string; deadline: string; price: number; stockLimit?: number }[];
variants?: OptionVariant[];
};
@@ -48,6 +49,7 @@ type Event = {
allowSponsorships?: boolean;
bundles?: PublicBundle[];
scheduleType?: "single" | "sessions";
attendanceMode?: "whole" | "pick";
sessions?: EventSession[];
registrationClosesAt?: string;
lateJoin?: LateJoinInfo | null;
@@ -58,7 +60,7 @@ import { ApiImage } from "@/components/shared/ApiImage";
import { formatDateTimeRange } from "@/lib/date";
import { BundleOffers } from "@/components/shared/BundleDeals";
import type { EventSession, LateJoinInfo, PublicBundle } from "@/types";
import { latePrice, registrationClosesAt, scheduleSummary } from "@/lib/sessions";
import { isPickOption, latePrice, registrationClosesAt, scheduleSummary } from "@/lib/sessions";
import { SessionSchedule } from "@/components/events/SessionSchedule";
import { appUrl, appName } from "@/lib/siteConfig";
import { getServerSettings } from "@/lib/serverSettings";
@@ -292,7 +294,8 @@ function TicketList({ event }: { event: Event }) {
}
// Late joiners on a multi-day event pay a lower main-ticket price.
const late = event.lateJoin?.active ? event.lateJoin : null;
const forLate = (opt: EventOption, price: number) => (late && opt.isMainTicket ? latePrice(price, late) : price);
const forLate = (opt: EventOption, price: number) => (late && opt.isMainTicket && opt.sessionMode !== "pick" ? latePrice(price, late) : price);
const perSession = (opt: EventOption) => (isPickOption(event, opt) ? " per session" : "");
return (
<div className="space-y-2">
<BundleOffers bundles={event.bundles} />
@@ -316,7 +319,7 @@ function TicketList({ event }: { event: Event }) {
<div className="flex items-center justify-between px-3 py-2 bg-gray-50 border-b">
<span className="font-medium text-sm">{opt.name}</span>
<div className="flex items-center gap-2">
<span className="text-sm text-gray-600">{priceLabel}</span>
<span className="text-sm text-gray-600">{priceLabel}{perSession(opt)}</span>
{soldOut && <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>}
{nearlyOut && !soldOut && <span className="text-xs font-medium text-orange-600 bg-orange-50 border border-orange-200 rounded px-1.5 py-0.5">{opt.availableCount} remaining</span>}
</div>
@@ -360,7 +363,7 @@ function TicketList({ event }: { event: Event }) {
<span className="text-xs text-brand-600">Early bird</span>
</>
) : (
<span>{displayPrice === 0 ? "Free" : `R${displayPrice.toFixed(2)}`}</span>
<span>{displayPrice === 0 ? "Free" : `R${displayPrice.toFixed(2)}${perSession(opt)}`}</span>
)}
{soldOut && <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>}
{nearlyOut && !soldOut && <span className="text-xs font-medium text-orange-600 bg-orange-50 border border-orange-200 rounded px-1.5 py-0.5">{opt.availableCount} remaining</span>}
@@ -6,7 +6,8 @@ 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 { latePrice, registrationClosesAt } from "@/lib/sessions";
import { 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";
@@ -33,6 +34,8 @@ type EventOption = {
isMainTicket?: boolean;
earlyBirdTiers?: EarlyBirdTier[];
variants?: OptionVariant[];
sessionMode?: "all" | "pick";
sessionAvailability?: Record<string, number>;
};
export type RegisterEvent = {
@@ -54,8 +57,10 @@ export type RegisterEvent = {
waitlistEnabled?: boolean;
bundles?: PublicBundle[];
scheduleType?: "single" | "sessions";
attendanceMode?: "whole" | "pick";
sessions?: EventSession[];
registrationClosesAt?: string;
wholeCourseClosesAt?: string | null;
lateJoin?: LateJoinInfo | null;
};
@@ -66,7 +71,7 @@ function withLatePrices(event: RegisterEvent): RegisterEvent {
if (!late) return event;
return {
...event,
eventOptions: (event.eventOptions || []).map(o => (!o.isMainTicket ? o : {
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) })),
@@ -156,18 +161,27 @@ function QtyControl({
);
}
// A "pick sessions" option: the sessions chosen per quantity key, and the event's schedule.
type PickProps = { event: RegisterEvent; picks: Record<string, string[]>; onPick: (key: string, ids: string[]) => void };
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 ? " per session" : "";
const picker = (key: string, qty: number, unit: number) => (pick && qty > 0 ? (
<SessionPicker event={pick.event} option={opt} selected={pick.picks[key] || []} onChange={(ids) => pick.onPick(key, ids)} quantity={qty} unitPrice={unit} />
) : null);
const isSoldOut = (opt.stockLimit ?? 0) > 0 && opt.availableCount !== undefined && opt.availableCount <= 0;
if (hasVariants) {
@@ -177,7 +191,7 @@ function OptionCard({
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)}`;
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">
@@ -214,10 +228,11 @@ function OptionCard({
: undefined;
return (
<div key={variant.id} className="flex items-center justify-between px-4 py-2.5">
<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)}</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}
@@ -231,6 +246,8 @@ function OptionCard({
max={maxQty}
/>
</div>
{picker(key, qty, unitPrice)}
</div>
);
})}
</div>
@@ -248,7 +265,8 @@ function OptionCard({
: undefined;
return (
<div className="flex items-center justify-between border rounded-lg p-3 bg-white shadow-sm">
<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">
@@ -260,7 +278,7 @@ function OptionCard({
</span>
</>
) : (
<span>R{price.toFixed(2)}</span>
<span>R{price.toFixed(2)}{perSession}</span>
)}
<StockBadge stockLimit={opt.stockLimit} availableCount={opt.availableCount} />
{waitlist && isSoldOut && (
@@ -275,6 +293,8 @@ function OptionCard({
max={maxQty}
/>
</div>
{picker(key, qty, price)}
</div>
);
}
@@ -432,18 +452,26 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
setQuantities((q) => ({ ...q, [key]: val }));
};
// "Pick sessions" options: the sessions chosen for each quantity key. Whole-course
// tickets on such an event stop selling when the course starts.
const [picks, setPicks] = useState<Record<string, string[]>>({});
const wholeCourseClosed = event.attendanceMode === "pick" && !!event.wholeCourseClosesAt && Date.now() >= new Date(event.wholeCourseClosesAt).getTime();
const pickFor = (opt: EventOption) => isPickOption(event, opt);
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 qty = quantities[`${opt.id}:${v.id}`] || 0;
return vsum + qty * effectiveUnitForVariant(opt, 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) * effectiveUnitForOption(opt);
return sum + (quantities[opt.id] || 0) * sessionsFor(opt.id, opt) * effectiveUnitForOption(opt);
}, 0);
}, [event, quantities]);
}, [event, quantities, picks]); // eslint-disable-line react-hooks/exhaustive-deps
const isGuestEligible = !!(event.requiresAuth === false);
const isLoggedIn = !!user || !!token;
@@ -454,7 +482,7 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
return limitedOpts.length > 0 && limitedOpts.every(o => o.availableCount !== undefined && o.availableCount <= 0);
}, [event]);
const basket = useMemo(() => buildItems(), [quantities]); // eslint-disable-line react-hooks/exhaustive-deps
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.
@@ -472,15 +500,13 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
: 0;
function buildItems() {
const items: { eventOptionId: string; quantity: number; variantId?: string }[] = [];
const items: { eventOptionId: string; quantity: number; variantId?: string; sessionIds?: string[] }[] = [];
Object.entries(quantities).forEach(([key, qty]) => {
if (qty <= 0) return;
if (key.includes(":")) {
const [eventOptionId, variantId] = key.split(":");
items.push({ eventOptionId, quantity: qty, variantId });
} else {
items.push({ eventOptionId: key, quantity: qty });
}
const [eventOptionId, variantId] = key.includes(":") ? key.split(":") : [key, undefined];
const opt = (event.eventOptions || []).find(o => o.id === eventOptionId);
const sessionIds = opt && pickFor(opt) ? picks[key] || [] : undefined;
items.push({ eventOptionId, quantity: qty, ...(variantId ? { variantId } : {}), ...(sessionIds ? { sessionIds } : {}) });
});
return items;
}
@@ -491,6 +517,11 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
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; }
@@ -660,14 +691,18 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
{!eventSoldOut && <BundleOffers bundles={event.bundles} className="mb-3" />}
{wholeCourseClosed && (
<p className="mb-3 text-sm text-gray-600 bg-gray-50 border rounded-lg px-3 py-2">The course has started, so whole-course tickets are no longer on sale — choose the sessions you&apos;d like to come to.</p>
)}
<div className="space-y-3">
{(event.eventOptions || []).map((opt) => (
{(event.eventOptions || []).filter(opt => !(wholeCourseClosed && !pickFor(opt))).map((opt) => (
<OptionCard
key={opt.id}
opt={opt}
quantities={quantities}
onQtyChange={handleQtyChange}
waitlist={event.waitlistEnabled ? { eventId, guestsAllowed: event.requiresAuth === false } : null}
pick={pickFor(opt) ? { event, picks, onPick: (key, ids) => setPicks(p => ({ ...p, [key]: ids })) } : null}
/>
))}
</div>
@@ -8,7 +8,9 @@ import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeFi
import { BundleBuilder, BundleOffers, BundleSavings, useBundleQuote } from "@/components/shared/BundleDeals";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { errorMessage } from "@/lib/utils";
import type { PublicBundle, Registration } from "@/types";
import type { Event, PublicBundle, Registration } from "@/types";
import { isPickOption } from "@/lib/sessions";
import { SessionPicker } from "@/components/events/SessionPicker";
// ─── Types ────────────────────────────────────────────────────────────────────
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
@@ -209,25 +211,41 @@ export default function SelfServicePage() {
[events, selectedEventId]
);
// The events list doesn't carry bundle deals or places per session; the single-event
// response does.
const [kioskFull, setKioskFull] = useState<Event | null>(null);
useEffect(() => {
if (!selectedEventId) { setKioskBundles([]); setKioskFull(null); return; }
let cancelled = false;
apiFetch<Event>(`/api/events/${selectedEventId}`, { authToken: supervisorToken || undefined })
.then(ev => { if (!cancelled) { setKioskBundles(ev?.bundles || []); setKioskFull(ev || null); } })
.catch(() => { if (!cancelled) { setKioskBundles([]); setKioskFull(null); } });
return () => { cancelled = true; };
}, [selectedEventId, supervisorToken]);
// "Pick sessions" options: the sessions chosen per quantity key.
const [picks, setPicks] = useState<Record<string, string[]>>({});
useEffect(() => { setPicks({}); }, [selectedEventId]);
const pickOpt = (optionId: string) => {
const o = (kioskFull?.eventOptions || []).find(x => x.id === optionId);
return kioskFull && o && isPickOption(kioskFull, o) ? o : null;
};
const times = (key: string) => (pickOpt(key.split("::")[0]) ? (picks[key] || []).length : 1);
const picker = (key: string, optionId: string) => {
const o = pickOpt(optionId);
if (!o || !kioskFull || !(quantities[key] > 0)) return null;
return <SessionPicker event={kioskFull} option={o} quantity={quantities[key]} selected={picks[key] || []} onChange={ids => setPicks(p => ({ ...p, [key]: ids }))} />;
};
const total = useMemo(() => {
if (!selectedEvent) return 0;
return (selectedEvent.eventOptions || []).reduce((sum, o) => {
if ((o.variants || []).length > 0) {
return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * effectiveVariantUnit(o, v), 0);
return sum + (o.variants || []).reduce((vs, v) => vs + (quantities[`${o.id}::${v.id}`] || 0) * times(`${o.id}::${v.id}`) * effectiveVariantUnit(o, v), 0);
}
return sum + (quantities[o.id] || 0) * effectiveUnit(o);
return sum + (quantities[o.id] || 0) * times(o.id) * effectiveUnit(o);
}, 0);
}, [selectedEvent, quantities]);
// The events list doesn't carry bundle deals; the single-event response does.
useEffect(() => {
if (!selectedEventId) { setKioskBundles([]); return; }
let cancelled = false;
apiFetch<{ bundles?: PublicBundle[] }>(`/api/events/${selectedEventId}`, { authToken: supervisorToken || undefined })
.then(ev => { if (!cancelled) setKioskBundles(ev?.bundles || []); })
.catch(() => { if (!cancelled) setKioskBundles([]); });
return () => { cancelled = true; };
}, [selectedEventId, supervisorToken]);
}, [selectedEvent, quantities, picks, kioskFull]); // eslint-disable-line react-hooks/exhaustive-deps
const kioskBasket = useMemo(() => Object.entries(quantities).map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
@@ -438,7 +456,7 @@ export default function SelfServicePage() {
.filter(([, qty]) => qty > 0)
.map(([key, quantity]) => {
const [eventOptionId, variantId] = key.split("::");
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}) };
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}), ...(pickOpt(eventOptionId) ? { sessionIds: picks[key] || [] } : {}) };
}),
user,
// If the visitor declined to create an account, don't push an unsolicited
@@ -973,7 +991,8 @@ export default function SelfServicePage() {
const baseVariantPrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const key = `${opt.id}::${v.id}`;
return (
<div key={v.id} className="flex items-center justify-between px-4 py-3">
<div key={v.id}>
<div className="flex items-center justify-between px-4 py-3">
<div>
<p className="text-gray-800">{v.name}</p>
<p className="text-sm text-gray-500">
@@ -999,6 +1018,8 @@ export default function SelfServicePage() {
</button>
</div>
</div>
{picker(key, opt.id) && <div className="px-4 pb-3">{picker(key, opt.id)}</div>}
</div>
);
})}
</div>
@@ -1007,7 +1028,8 @@ export default function SelfServicePage() {
}
const unit = effectiveUnit(opt);
return (
<div key={opt.id} className="flex items-center justify-between border border-gray-200 rounded-xl px-4 py-3.5">
<div key={opt.id} className="border border-gray-200 rounded-xl px-4 py-3.5">
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-gray-800">{opt.name}</p>
<p className="text-sm text-gray-500">{fmtCurrency(unit)}{unit !== opt.price && opt.price > 0 ? ` (was ${fmtCurrency(opt.price)})` : ""}</p>
@@ -1030,6 +1052,8 @@ export default function SelfServicePage() {
</button>
</div>
</div>
{picker(opt.id, opt.id)}
</div>
);
})}
</div>
@@ -115,7 +115,7 @@ function PatternBuilder({ onGenerate }: { onGenerate: (rows: SessionDraft[], mod
);
}
export function SessionsEditor({ sessions, onChange, defaultLocation }: { sessions: KeyedSession[]; onChange: (s: KeyedSession[]) => void; defaultLocation?: string }) {
export function SessionsEditor({ sessions, onChange, defaultLocation, showCapacity }: { sessions: KeyedSession[]; onChange: (s: KeyedSession[]) => void; defaultLocation?: string; showCapacity?: boolean }) {
const [showPattern, setShowPattern] = useState(sessions.length === 0);
const sorted = sortSessions(sessions);
const activeCount = sessions.filter(s => !s.cancelled).length;
@@ -137,7 +137,7 @@ export function SessionsEditor({ sessions, onChange, defaultLocation }: { sessio
const start = new Date(base.getTime() + (last ? 7 * 24 * 60 * 60 * 1000 : 0));
const p = (n: number) => String(n).padStart(2, "0");
const fmt = (d: Date) => `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
onChange([...sessions, keyed({ label: "", startsAt: fmt(start), endsAt: fmt(new Date(start.getTime() + dur)), location: "", cancelled: false })]);
onChange([...sessions, keyed({ label: "", startsAt: fmt(start), endsAt: fmt(new Date(start.getTime() + dur)), location: "", cancelled: false, capacity: last?.capacity || "" })]);
};
let position = 0;
@@ -180,7 +180,7 @@ export function SessionsEditor({ sessions, onChange, defaultLocation }: { sessio
)}
</div>
{!s.cancelled && (
<div className="grid sm:grid-cols-3 gap-2 pl-8">
<div className={`grid gap-2 pl-8 ${showCapacity ? "sm:grid-cols-4" : "sm:grid-cols-3"}`}>
<label className="text-[11px] text-gray-500">Starts
<input type="datetime-local" className="mt-0.5 w-full border rounded px-2 py-1 text-sm" value={s.startsAt} onChange={e => {
const v = e.target.value;
@@ -197,6 +197,11 @@ export function SessionsEditor({ sessions, onChange, defaultLocation }: { sessio
<label className="text-[11px] text-gray-500">Location (optional)
<input className="mt-0.5 w-full border rounded px-2 py-1 text-sm" placeholder={defaultLocation || "Event location"} value={s.location} onChange={e => update(s.key, { location: e.target.value })} />
</label>
{showCapacity && (
<label className="text-[11px] text-gray-500" title="Most people at this session (picked places plus whole-course tickets). Blank = no limit.">Capacity
<input type="number" min={1} className="mt-0.5 w-full border rounded px-2 py-1 text-sm" placeholder="No limit" value={s.capacity} onChange={e => update(s.key, { capacity: e.target.value })} />
</label>
)}
</div>
)}
{s.hasCheckIns && <p className="pl-8 text-[10px] text-gray-400">Has check-ins — it can be cancelled but not removed.</p>}
@@ -0,0 +1,43 @@
"use client";
import React from "react";
import type { Event } from "@/types";
import { bookableSessions, formatSessionWhen, sessionLabel } from "@/lib/sessions";
// Tick boxes for the sessions of a "pick sessions" ticket. Full sessions (or ones with
// fewer places than `quantity`) can't be ticked.
export function SessionPicker({ event, option, selected, onChange, quantity = 1, staff = false, unitPrice }: {
event: Pick<Event, "sessions">;
option: { id: string; sessionAvailability?: Record<string, number> };
selected: string[];
onChange: (ids: string[]) => void;
quantity?: number;
staff?: boolean;
unitPrice?: number;
}) {
const sessions = bookableSessions(event, option, staff);
if (sessions.length === 0) return <p className="text-xs text-gray-500 mt-2">No sessions left to book.</p>;
const toggle = (id: string) => onChange(selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id]);
const allOpen = sessions.filter(s => s.left === null || s.left >= Math.max(1, quantity)).map(s => s.id);
return (
<div className="mt-2 space-y-1" role="group" aria-label="Choose sessions">
<div className="flex items-center justify-between text-xs text-gray-500">
<span>Choose your sessions{unitPrice !== undefined ? ` — R${unitPrice.toFixed(2)} each` : ""}</span>
<button type="button" className="text-brand-700 hover:underline" onClick={() => onChange(selected.length === allOpen.length ? [] : allOpen)}>
{selected.length === allOpen.length && allOpen.length > 0 ? "Clear" : "Select all"}
</button>
</div>
{sessions.map(s => {
const full = s.left !== null && s.left < Math.max(1, quantity);
return (
<label key={s.id} className={`flex items-center gap-2 rounded border px-2 py-1.5 text-sm ${full ? "bg-gray-50 text-gray-400" : selected.includes(s.id) ? "border-brand-300 bg-brand-50" : "hover:bg-gray-50"}`}>
<input type="checkbox" disabled={full && !selected.includes(s.id)} checked={selected.includes(s.id)} onChange={() => toggle(s.id)} />
<span className="font-medium">{sessionLabel(s, event.sessions)}</span>
<span className="text-gray-500">{formatSessionWhen(s)}</span>
<span className="ml-auto text-xs">{s.left === null ? "" : s.left <= 0 ? "Full" : `${s.left} left`}</span>
</label>
);
})}
</div>
);
}
@@ -37,6 +37,9 @@ export const supervisorEventsHelpContent: HelpContent = {
<GuideItem icon={CalendarDays} title="Multiple sessions" tone="brand">
Choose &quot;Multiple sessions&quot; for one event on several dates — e.g. every Wednesday 18:30–20:30 for 5 weeks. Use the repeat pattern to create the dates, then edit any of them, add a label (&quot;Week 1 — …&quot;), a different location, or an extra date. People register and pay once and get one ticket for every session. Cancel a session (e.g. a public holiday) rather than deleting it once people have been checked in. Registration closes when the first session starts unless you turn on late joining.
</GuideItem>
<GuideItem icon={CalendarDays} title="Pick sessions" tone="violet">
For day passes or a drop-in class, set &quot;How people book&quot; to &quot;Pick sessions&quot;, give sessions an optional capacity, and in Items &amp; Pricing set a ticket to &quot;Pick sessions (price per session)&quot;. People tick the sessions they want; each one is its own ticket. Whole-course tickets can still be sold too, until the course starts.
</GuideItem>
<GuideItem icon={ListChecks} title="Items & pricing" tone="green">
Ticket options and stock, variants of each option, and early-bird pricing tiers. An optional staff price is charged automatically to Staff and above when it&apos;s lower than the normal price.
</GuideItem>
+22 -2
View File
@@ -22,6 +22,7 @@ export type SessionDraft = {
endsAt: string;
location: string;
cancelled: boolean;
capacity: string; // "pick sessions" events; blank = no limit
hasCheckIns?: boolean;
};
@@ -54,7 +55,7 @@ export function generateSessions(p: SessionPattern): SessionDraft[] {
const start = atTime(day, p.startTime);
let end = atTime(day, p.endTime);
if (end <= start) end = new Date(end.getTime() + 24 * 60 * 60 * 1000);
out.push({ label: "", startsAt: localDT(start), endsAt: localDT(end), location: "", cancelled: false });
out.push({ label: "", startsAt: localDT(start), endsAt: localDT(end), location: "", cancelled: false, capacity: "" });
};
if (p.frequency === "daily") {
@@ -83,7 +84,7 @@ export function generateSessions(p: SessionPattern): SessionDraft[] {
}
export function toSessionDraft(s: EventSession & { hasCheckIns?: boolean }): SessionDraft {
return { id: s.id, label: s.label || "", startsAt: localDT(new Date(s.startsAt)), endsAt: localDT(new Date(s.endsAt)), location: s.location || "", cancelled: !!(s.cancelled || s.cancelledAt), hasCheckIns: s.hasCheckIns };
return { id: s.id, label: s.label || "", startsAt: localDT(new Date(s.startsAt)), endsAt: localDT(new Date(s.endsAt)), location: s.location || "", cancelled: !!(s.cancelled || s.cancelledAt), capacity: s.capacity ? String(s.capacity) : "", hasCheckIns: s.hasCheckIns };
}
/** Sessions that aren't cancelled, earliest first. */
@@ -172,3 +173,22 @@ export function todaysSession(event: Pick<Event, "scheduleType" | "sessions"> |
const list = activeSessions(event.sessions).filter(x => new Date(x.startsAt).toDateString() === today);
return list.find(s => now <= new Date(s.endsAt).getTime()) || list[list.length - 1] || null;
}
/** Whether an option is bought per session (only in "pick sessions" events). */
export function isPickOption(event: Pick<Event, "scheduleType" | "attendanceMode"> | null | undefined, option: { sessionMode?: "all" | "pick" } | null | undefined): boolean {
return event?.scheduleType === "sessions" && event?.attendanceMode === "pick" && option?.sessionMode === "pick";
}
/**
* Sessions a pick option can still be booked for, with places left (null = no limit).
* Public: before the session starts; staff: until it ends.
*/
export function bookableSessions(event: Pick<Event, "sessions">, option: { sessionAvailability?: Record<string, number> }, staff = false): (EventSession & { left: number | null })[] {
const now = Date.now();
return activeSessions(event.sessions)
.filter(s => new Date(staff ? s.endsAt : s.startsAt).getTime() > now)
.map(s => {
const limits = [s.placesLeft, option.sessionAvailability?.[s.id]].filter((n): n is number => typeof n === "number");
return { ...s, left: limits.length ? Math.min(...limits) : null };
});
}
+7 -3
View File
@@ -1,6 +1,6 @@
import type { Ticket as TicketRecord } from "@/types";
import { formatDate } from "@/lib/date";
import { scheduleSummary } from "@/lib/sessions";
import { formatSessionWhen, scheduleSummary } from "@/lib/sessions";
// One ticket design for every printed ticket (user dashboard, staff event tickets, at the
// door). The emailed/WhatsApp PDF in backend/src/controllers/ticketController.js mirrors it.
@@ -18,8 +18,12 @@ export function ticketTypeLabel(t: TicketRecord): string {
/** A ticket card. `buyerName` adds a "Purchased by" line. */
export function ticketCardHtml(t: TicketRecord, buyerName?: string | null): string {
const eventTitle = t.event?.title || t.eventId || "Event";
// Multi-day events: "5 sessions · Wed 4 Nov – Wed 2 Dec" — one ticket for every session.
const dateStr = (t.event && scheduleSummary(t.event)) || (t.event?.startDate ? formatDate(t.event.startDate) : "");
// Multi-day events: "5 sessions · Wed 4 Nov – Wed 2 Dec" — one ticket for every session;
// a picked-session ticket shows its own session.
const session = t.registrationOption?.session;
const dateStr = session
? `${session.label || "Session"} · ${formatSessionWhen(session)}`
: (t.event && scheduleSummary(t.event)) || (t.event?.startDate ? formatDate(t.event.startDate) : "");
const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=320x320&data=${encodeURIComponent(t.qrCode || t.id)}`;
return `
<div class="ticket">
+17
View File
@@ -73,6 +73,10 @@ export type EventOption = {
earlyBirdTiers?: EarlyBirdTier[];
createdAt?: string;
updatedAt?: string;
// "Pick sessions" events: `pick` options are bought per session (price per session).
sessionMode?: "all" | "pick";
// Pick options with a stock limit: places left per session id.
sessionAvailability?: Record<string, number>;
};
export type FormFieldType =
@@ -158,6 +162,8 @@ export type Event = {
// When public registration closes: the deadline, the first session (or session N with
// late joining), or the end date — whichever applies.
registrationClosesAt?: string;
// "Pick sessions" events: when whole-course tickets stop selling.
wholeCourseClosesAt?: string | null;
lateJoinEnabled?: boolean;
lateJoinUntilSessionId?: string | null;
latePricing?: "full" | "prorata" | "fixed";
@@ -182,6 +188,11 @@ export type EventSession = {
cancelledAt?: string | null;
cancelled?: boolean;
order?: number;
// "Pick sessions" events: optional limit on people, and (single-event responses) how
// many are booked and how many places are left (null = no limit).
capacity?: number | null;
booked?: number;
placesLeft?: number | null;
};
export type LateJoinInfo = {
@@ -208,6 +219,9 @@ export type CertificateConfig = {
export type AttendanceColumn = { id: string; label: string; startsAt: string; endsAt: string; cancelled: boolean };
export type AttendanceRow = {
ticketId: string;
// Picked-session bookings: the sessions booked (null = all) and the ticket for each.
bookedSessions?: string[] | null;
sessionTickets?: Record<string, string> | null;
name: string;
bookedBy: string;
email: string;
@@ -458,6 +472,9 @@ export type RegistrationOption = {
appliedTierId?: string | null;
eventOption?: EventOption;
variant?: OptionVariant | null;
// Picked-session lines: the one session this line (and its ticket) is for.
sessionId?: string | null;
session?: EventSession | null;
// One entry per price the line was bought at (e.g. some before an early-bird tier expired).
tranches?: { id: string; quantity: number; priceSnapshot: number; appliedTierId?: string | null }[];
tickets?: { id: string; quantity?: number }[];