Add multi-day events (frontend), attendance register and certificates

Event wizard: one date or multiple sessions with a repeat-pattern builder,
and a new Attendance step (late joining and pricing, check-in window,
session reminders, certificates with preview). Public pages show the
schedule and late prices; the scanner picks today's session; new
attendance register page, My Certificates, and a public verify page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 14:53:39 +02:00
co-authored by Claude Opus 5.5
parent 623c85ccc5
commit f4b358e5c8
37 changed files with 1670 additions and 77 deletions
@@ -0,0 +1,61 @@
import { Metadata } from "next";
import { BadgeCheck, ShieldX } from "lucide-react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { apiFetch } from "@/lib/api";
import { formatDate } from "@/lib/date";
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
title: "Verify a certificate",
robots: { index: false },
};
type Verification = { valid: boolean; revoked?: boolean; name?: string; event?: string; completedOn?: string; issuedAt?: string };
// Public check for the QR code / code printed on a completion certificate. Shows only the
// name, event and dates — nothing else about the person.
export default async function VerifyCertificatePage({ params }: { params: Promise<{ code: string }> }) {
const { code } = await params;
let result: Verification = { valid: false };
try {
result = await apiFetch<Verification>(`/api/attendance/certificates/verify/${encodeURIComponent(code)}`, { nextOptions: { cache: "no-store" } });
} catch {
result = { valid: false };
}
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-1 py-12 px-4 max-w-lg mx-auto w-full">
<div className="border rounded-xl p-6 bg-white shadow-sm text-center">
{result.valid ? (
<>
<BadgeCheck className="w-12 h-12 text-green-600 mx-auto mb-3" />
<h1 className="text-xl font-semibold text-gray-900">Valid certificate</h1>
<p className="text-gray-700 mt-3"><span className="font-semibold">{result.name}</span> completed</p>
<p className="text-lg font-medium text-brand-700 mt-1">{result.event}</p>
<p className="text-sm text-gray-500 mt-3">
{result.completedOn && <>Completed {formatDate(new Date(result.completedOn))} · </>}
{result.issuedAt && <>Issued {formatDate(new Date(result.issuedAt))}</>}
</p>
</>
) : (
<>
<ShieldX className="w-12 h-12 text-red-500 mx-auto mb-3" />
<h1 className="text-xl font-semibold text-gray-900">{result.revoked ? "This certificate was withdrawn" : "Certificate not found"}</h1>
<p className="text-sm text-gray-500 mt-3">
{result.revoked
? "The organiser has withdrawn this certificate, so it's no longer valid."
: "Check the code on the certificate and try again. Codes look like K7M2Q-9XRTB."}
</p>
</>
)}
<p className="text-xs text-gray-400 mt-6 font-mono">{decodeURIComponent(code).toUpperCase()}</p>
</div>
</main>
<Footer />
</div>
);
}
@@ -8,7 +8,7 @@ import { useStableState } from "@/hooks/useStableState";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -30,6 +30,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet },
{ href: "/dashboard/supervisor/allocations", label: "Rooms & groups", description: "Put attendees into rooms, groups or buses", icon: BedDouble },
{ href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session, and certificates", icon: ClipboardCheck },
{ 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 },
@@ -6,7 +6,7 @@ import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { useStableState } from "@/hooks/useStableState";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { QrCode, Ticket, Activity, UserCheck, Clock, Users } from "lucide-react";
import { QrCode, Ticket, Activity, UserCheck, Clock, Users, ClipboardCheck } from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import type { DashboardStats, RecentScan, ScanStats } from "@/types";
@@ -15,6 +15,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode },
{ href: "/dashboard/staff/event-tickets", label: "Event tickets & printing", description: "Browse event tickets and print lists", icon: Ticket },
{ href: "/dashboard/staff/my-groups", label: "My groups", description: "Rooms and groups you lead", icon: Users },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session of an event", icon: ClipboardCheck },
] as const;
export default function StaffDashboardPage() {
@@ -11,6 +11,7 @@ import { OfflineScanPanel } from "@/components/scanner/OfflineScanPanel";
import type { SnapshotTicket } from "@/lib/offlineScan";
import { errorMessage } from "@/lib/utils";
import type { Event, RecentScan, ScanStats, Section } from "@/types";
import { activeSessions, currentSessionLabel, formatSessionWhen, sessionLabel } from "@/lib/sessions";
import { BackLink } from "@/components/shared/BackLink";
// GET /api/tickets/scan-preview/:qr — just the fields the confirm step needs. Offline
@@ -30,6 +31,10 @@ type ScanTicket = {
attendee?: { name: string } | null;
user?: { name?: string; email?: string } | null;
usages?: { id: string; scannedAt: string; quantityRedeemed?: number }[];
// Multi-day events: the session this scan counts for, and what's left for it.
remaining?: number;
session?: { id: string; label: string } | null;
sessionError?: string | null;
};
export default function TicketScanningPage() {
@@ -73,6 +78,8 @@ export default function TicketScanningPage() {
const [sections, setSections] = useState<Section[]>([]);
const [selectedSectionId, setSelectedSectionId] = useState<string>("all");
const [loadingSections, setLoadingSections] = useState(false);
// Multi-day events: "auto" = today's session (the server picks it).
const [selectedSessionId, setSelectedSessionId] = useState<string>("auto");
// All events from API (including past); frontend filters to 12h window or all past
useEffect(() => {
@@ -100,6 +107,11 @@ export default function TicketScanningPage() {
});
}, [allEvents, includePastEvents]);
const selectedEvent = useMemo(() => allEvents.find(ev => ev.id === selectedEventId) || null, [allEvents, selectedEventId]);
const eventSessions = useMemo(() => selectedEvent?.scheduleType === "sessions" ? activeSessions(selectedEvent.sessions) : [], [selectedEvent]);
useEffect(() => { setSelectedSessionId("auto"); }, [selectedEventId]);
const sessionParam = selectedEventId !== "all" && selectedSessionId !== "auto" ? selectedSessionId : null;
useEffect(() => {
(async () => {
if (!token || !selectedEventId || selectedEventId === "all") {
@@ -136,7 +148,7 @@ export default function TicketScanningPage() {
useEffect(() => {
if (isFirstFilterRender.current) { isFirstFilterRender.current = false; return; }
scannerRef.current?.stop();
}, [selectedEventId, selectedSectionId]);
}, [selectedEventId, selectedSectionId, selectedSessionId]);
async function handleResult(text: string) {
setError(null);
@@ -177,7 +189,7 @@ export default function TicketScanningPage() {
// Uses the lightweight scan-preview endpoint (only fetches fields needed for the confirm modal)
let preview: ScanTicket;
try {
preview = await apiFetch<ScanTicket>(`/api/tickets/scan-preview/${encodeURIComponent(text)}`, { authToken: token });
preview = await apiFetch<ScanTicket>(`/api/tickets/scan-preview/${encodeURIComponent(text)}${sessionParam ? `?sessionId=${encodeURIComponent(sessionParam)}` : ""}`, { authToken: token });
} catch (pe) {
setErrorModal(errorMessage(pe) || 'Failed to validate ticket');
return;
@@ -208,13 +220,19 @@ export default function TicketScanningPage() {
}
}
// Compute remaining qty
// Multi-day events: no session open for check-in now (wrong day, cancelled…).
if (preview?.sessionError) {
setErrorModal(preview.sessionError);
return;
}
// Compute remaining qty (the server counts it per session for multi-day events)
const ticketQty = preview?.quantity || 1;
const totalRedeemed = (preview?.usages || []).reduce((s, u) => s + (u.quantityRedeemed || 1), 0);
const remaining = ticketQty - totalRedeemed;
const remaining = typeof preview?.remaining === "number" ? preview.remaining : ticketQty - totalRedeemed;
if (remaining <= 0) {
setAlreadyUsedModal({ message: 'Ticket has already been fully used', ticket: preview });
setAlreadyUsedModal({ message: preview?.session ? `Already checked in for ${preview.session.label}` : 'Ticket has already been fully used', ticket: preview });
return;
}
@@ -236,7 +254,7 @@ export default function TicketScanningPage() {
const baseName = ticket?.registrationOption?.eventOption?.name || "Ticket";
const variantName = ticket?.registrationOption?.variant?.name;
const optionName = variantName ? `${baseName} — ${variantName}` : baseName;
const eventTitle = ticket?.event?.title || 'Event';
const eventTitle = `${ticket?.event?.title || 'Event'}${ticket?.session ? ` — ${ticket.session.label}` : ''}`;
const idPart = ticket?.id ? String(ticket.id).slice(0, 6) : '';
const newRemaining = remaining - qty;
@@ -276,6 +294,7 @@ export default function TicketScanningPage() {
qty,
deviceId: offline.deviceId(),
...(selectedSectionId && selectedSectionId !== "all" ? { sectionId: selectedSectionId } : {}),
...(ticket?.session ? { sessionId: ticket.session.id } : {}),
...(overrideConsent ? { overrideConsent: true } : {}),
},
});
@@ -378,6 +397,23 @@ export default function TicketScanningPage() {
</div>
)}
{eventSessions.length > 0 && (
<div className="flex flex-col sm:flex-row sm:items-center gap-2 mb-3">
<label className="text-sm text-gray-700 shrink-0">Session</label>
<select
className="border rounded px-3 py-2 w-full sm:w-72 max-w-full"
value={selectedSessionId}
onChange={(e) => setSelectedSessionId(e.target.value)}
disabled={!!offline.lock}
>
<option value="auto">Today&apos;s session{currentSessionLabel(selectedEvent) ? ` (${currentSessionLabel(selectedEvent)})` : ""}</option>
{eventSessions.map(s => (
<option key={s.id} value={s.id}>{sessionLabel(s, selectedEvent?.sessions)} — {formatSessionWhen(s)}</option>
))}
</select>
</div>
)}
<OfflineScanPanel
offline={offline}
token={token}
@@ -467,6 +503,7 @@ export default function TicketScanningPage() {
<div className="bg-gray-50 border rounded-lg p-4 mb-4 space-y-1 text-sm">
<div><span className="font-medium">Ticket type:</span> {confirmModal.ticket?.registrationOption?.eventOption?.name || 'Ticket'}{confirmModal.ticket?.registrationOption?.variant?.name ? ` — ${confirmModal.ticket.registrationOption.variant.name}` : ''}</div>
<div><span className="font-medium">Event:</span> {confirmModal.ticket?.event?.title || '—'}</div>
{confirmModal.ticket?.session && <div><span className="font-medium">Session:</span> {confirmModal.ticket.session.label}</div>}
<div><span className="font-medium">Holder:</span> {confirmModal.ticket?.attendee?.name || confirmModal.ticket?.user?.name || confirmModal.ticket?.registrationOption?.registration?.user?.name || '—'}</div>
{confirmModal.ticket?.attendee?.name && confirmModal.ticket?.user?.name && (
<div className="text-xs text-gray-500">Booked by {confirmModal.ticket.user.name}</div>
@@ -0,0 +1,291 @@
"use client";
import React, { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ClipboardCheck, Check, Download, FileSpreadsheet, FileText, Send, Award, Search, Ban } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, API_BASE } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { errorMessage } from "@/lib/utils";
import { formatDate } from "@/lib/date";
import { fetchApiFile, saveBlob } from "@/lib/export";
import type { AttendanceRegister, AttendanceRow, Event } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
type Filter = "all" | "completed" | "not_completed" | "missed_recent";
const colDate = new Intl.DateTimeFormat("en-GB", { weekday: "short", day: "numeric", month: "short" });
function AttendancePageInner() {
const { user, loading, token } = useAuth();
const router = useRouter();
const search = useSearchParams();
const canView = ["admin", "supervisor", "staff"].includes(user?.role || "");
const canManage = user?.role === "admin" || user?.role === "supervisor";
useEffect(() => {
if (loading) return;
if (!user) router.replace("/login");
}, [user, loading, router]);
const [events, setEvents] = useState<Event[]>([]);
const [eventId, setEventId] = useState(search.get("eventId") || "");
const [reg, setReg] = useState<AttendanceRegister | null>(null);
const [busy, setBusy] = useState(false);
const [pending, setPending] = useState<string | null>(null);
const [query, setQuery] = useState("");
const [filter, setFilter] = useState<Filter>("all");
const [showCancelled, setShowCancelled] = useState(false);
const [error, setError] = useDismissingState<string | null>(null);
const [info, setInfo] = useDismissingState<string | null>(null);
useEffect(() => {
if (!token || !canView) return;
apiFetch<Event[]>("/api/events/all?includePast=true", { authToken: token })
.then(evs => {
// Multi-day events first (that's what the register is mostly for), newest first.
const list = (evs || []).filter(e => e.requiresRegistration !== false)
.sort((a, b) => Number(b.scheduleType === "sessions") - Number(a.scheduleType === "sessions") || new Date(b.startDate).getTime() - new Date(a.startDate).getTime());
setEvents(list);
if (!eventId && list.length) setEventId(list[0].id);
})
.catch(e => setError(errorMessage(e) || "Failed to load events"));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [token, canView]);
const load = useCallback(async () => {
if (!token || !eventId) return;
setBusy(true);
try {
setReg(await apiFetch<AttendanceRegister>(`/api/attendance/${encodeURIComponent(eventId)}`, { authToken: token }));
} catch (e) {
setError(errorMessage(e) || "Failed to load the register");
} finally {
setBusy(false);
}
}, [token, eventId, setError]);
useEffect(() => { load(); }, [load]);
const columns = useMemo(() => (reg?.columns || []).filter(c => showCancelled || !c.cancelled), [reg, showCancelled]);
const multi = reg?.event.scheduleType === "sessions";
// Sessions already held (for "missed the last two").
const heldIds = useMemo(() => (reg?.columns || []).filter(c => !c.cancelled && new Date(c.startsAt).getTime() < Date.now()).map(c => c.id), [reg]);
const rows = useMemo(() => {
const q = query.trim().toLowerCase();
return (reg?.rows || []).filter(r => {
if (q && ![r.name, r.bookedBy, r.email, r.phone].some(v => v?.toLowerCase().includes(q))) return false;
if (filter === "completed") return r.completed;
if (filter === "not_completed") return !r.completed;
if (filter === "missed_recent") {
const lastTwo = heldIds.slice(-2);
return lastTwo.length > 0 && lastTwo.every(id => !r.checkIns[id]);
}
return true;
});
}, [reg, query, filter, heldIds]);
const toggle = async (row: AttendanceRow, sessionId: string) => {
if (!canManage || !token) return;
const present = !row.checkIns[sessionId];
const key = `${row.ticketId}:${sessionId}`;
setPending(key);
try {
await apiFetch(`/api/attendance/${eventId}/mark`, { method: "POST", authToken: token, body: { ticketId: row.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();
} catch (e) {
setError(errorMessage(e) || "Couldn't update attendance");
} finally {
setPending(null);
}
};
const post = async (path: string, body: object, done: (r: Record<string, number>) => string) => {
if (!token) return;
setBusy(true);
try {
const r = await apiFetch<Record<string, number>>(path, { method: "POST", authToken: token, body });
setInfo(done(r));
await load();
} catch (e) {
setError(errorMessage(e) || "Something went wrong");
} finally {
setBusy(false);
}
};
const download = async (path: string, filename: string) => {
if (!token) return;
try {
saveBlob(await fetchApiFile(API_BASE, token, path), filename);
} catch (e) {
setError(errorMessage(e) || "Download failed");
}
};
const safeTitle = (reg?.event.title || "event").replace(/[^a-z0-9 -]/gi, "").slice(0, 60);
const certsOn = !!reg?.event.certificatesEnabled;
const issued = (reg?.rows || []).filter(r => r.certificate && !r.certificate.revokedAt).length;
const unsent = (reg?.rows || []).filter(r => r.certificate && !r.certificate.revokedAt && !r.certificate.emailedAt).length;
const completed = (reg?.rows || []).filter(r => r.completed).length;
return (
<div className="max-w-7xl mx-auto w-full p-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
<ClipboardCheck 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">Attendance</h1>
<p className="text-sm text-gray-500">Who came to each session, and completion certificates</p>
</div>
</div>
{!canView && <div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">You need staff access to view attendance.</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 space-y-4">
<div className="flex flex-wrap items-end gap-3">
<div>
<label className="block text-xs text-gray-600 mb-1">Event</label>
<select className="border rounded-lg px-3 py-2 text-sm min-w-[16rem] max-w-full" value={eventId} onChange={e => setEventId(e.target.value)}>
{events.length === 0 && <option value="">No events</option>}
{events.map(ev => (
<option key={ev.id} value={ev.id}>{ev.title} ({formatDate(new Date(ev.startDate))}{ev.scheduleType === "sessions" ? ` · ${(ev.sessions || []).filter(s => !s.cancelled).length} sessions` : ""})</option>
))}
</select>
</div>
<div className="relative">
<Search className="w-4 h-4 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input className="border rounded-lg pl-8 pr-3 py-2 text-sm w-56" placeholder="Search name, email, phone" value={query} onChange={e => setQuery(e.target.value)} />
</div>
<select className="border rounded-lg px-3 py-2 text-sm" value={filter} onChange={e => setFilter(e.target.value as Filter)}>
<option value="all">Everyone</option>
<option value="completed">Completed</option>
<option value="not_completed">Not completed</option>
{multi && <option value="missed_recent">Missed the last two sessions</option>}
</select>
{multi && (reg?.columns || []).some(c => c.cancelled) && (
<label className="flex items-center gap-1.5 text-sm text-gray-600">
<input type="checkbox" checked={showCancelled} onChange={e => setShowCancelled(e.target.checked)} /> Show cancelled sessions
</label>
)}
<div className="ml-auto flex flex-wrap gap-2">
<button type="button" disabled={!reg} onClick={() => download(`/api/attendance/${eventId}/export?format=xlsx`, `Attendance - ${safeTitle}.xlsx`)} className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border bg-white hover:bg-gray-50 disabled:opacity-50"><FileSpreadsheet className="w-4 h-4" /> Excel</button>
<button type="button" disabled={!reg} onClick={() => download(`/api/attendance/${eventId}/export?format=pdf`, `Attendance - ${safeTitle}.pdf`)} className="inline-flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border bg-white hover:bg-gray-50 disabled:opacity-50"><FileText className="w-4 h-4" /> PDF</button>
</div>
</div>
{reg && (
<div className="flex flex-wrap gap-2 text-xs">
<span className="px-2 py-1 rounded bg-gray-100 text-gray-700">{reg.rows.length} attendee{reg.rows.length === 1 ? "" : "s"}</span>
<span className="px-2 py-1 rounded bg-green-50 text-green-800">{completed} completed</span>
{certsOn && <span className="px-2 py-1 rounded bg-brand-50 text-brand-800">{issued} certificate{issued === 1 ? "" : "s"} issued</span>}
{!multi && <span className="px-2 py-1 rounded bg-gray-50 text-gray-500">Single-date event — one check-in column</span>}
</div>
)}
{reg && certsOn && canManage && (
<div className="flex flex-wrap items-center gap-2 p-3 rounded-lg bg-brand-50/50 border border-brand-100">
<Award className="w-4 h-4 text-brand-600" />
<span className="text-sm text-gray-700 mr-auto">Certificates are issued automatically when the event ends. You can also:</span>
<button type="button" disabled={busy} onClick={() => post(`/api/attendance/${eventId}/certificates`, {}, r => `${r.issued} certificate${r.issued === 1 ? "" : "s"} issued.`)} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">Issue now</button>
<button type="button" disabled={busy || unsent === 0} onClick={() => post(`/api/attendance/${eventId}/certificates/send`, {}, r => `${r.sent} certificate${r.sent === 1 ? "" : "s"} sent${r.skipped ? `, ${r.skipped} couldn't be sent` : ""}.`)} className="inline-flex items-center gap-1 px-3 py-1.5 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><Send className="w-3.5 h-3.5" /> Send unsent ({unsent})</button>
<button type="button" disabled={issued === 0} onClick={() => download(`/api/attendance/${eventId}/certificates.pdf`, `Certificates - ${safeTitle}.pdf`)} className="inline-flex items-center gap-1 px-3 py-1.5 text-xs rounded border bg-white hover:bg-gray-50 disabled:opacity-50"><Download className="w-3.5 h-3.5" /> Download all</button>
</div>
)}
{busy && !reg && <p className="text-sm text-gray-500">Loading…</p>}
{reg && rows.length === 0 && <p className="text-sm text-gray-500 py-6 text-center">{reg.rows.length === 0 ? "No tickets for this event yet." : "Nobody matches."}</p>}
{reg && rows.length > 0 && (
<div className="overflow-x-auto border rounded-lg">
<table className="min-w-full text-sm">
<thead className="bg-gray-50 text-xs text-gray-600">
<tr>
<th className="sticky left-0 z-10 bg-gray-50 text-left font-medium px-3 py-2 min-w-[12rem]">Name</th>
{columns.map(c => (
<th key={c.id} className={`font-medium px-2 py-2 text-center whitespace-nowrap ${c.cancelled ? "text-gray-400 line-through" : ""}`}>
<div>{c.label}</div>
<div className="text-[10px] font-normal text-gray-400">{multi ? colDate.format(new Date(c.startsAt)) : ""}</div>
</th>
))}
<th className="font-medium px-2 py-2 text-center">Total</th>
{certsOn && <th className="font-medium px-3 py-2 text-left">Certificate</th>}
</tr>
</thead>
<tbody className="divide-y">
{rows.map(r => (
<tr key={r.ticketId} className="hover:bg-gray-50/60">
<td className="sticky left-0 z-10 bg-white px-3 py-2">
<div className="font-medium text-gray-900">{r.name || "—"}{r.quantity > 1 && <span className="ml-1 text-xs text-gray-500">×{r.quantity}</span>}</div>
<div className="text-[11px] text-gray-500">{r.variant ? `${r.option} — ${r.variant}` : r.option}{r.bookedBy ? ` · booked by ${r.bookedBy}` : ""}</div>
</td>
{columns.map(c => {
const qty = r.checkIns[c.id] || 0;
const key = `${r.ticketId}:${c.id}`;
const disabled = !canManage || c.cancelled || pending !== null || reg.event.cashupStatus === "closed";
return (
<td key={c.id} className="px-2 py-2 text-center">
<button type="button" disabled={disabled} onClick={() => toggle(r, c.id)}
title={canManage ? (qty ? "Present — click to mark absent" : "Absent — click to mark present") : undefined}
className={`inline-flex items-center justify-center w-7 h-7 rounded-md border text-xs ${qty ? "bg-green-50 border-green-300 text-green-700" : "bg-white border-gray-200 text-gray-300"} ${disabled ? "cursor-default" : "hover:border-brand-400"} ${pending === key ? "opacity-50" : ""}`}>
{qty ? (r.quantity > 1 ? qty : <Check className="w-4 h-4" />) : "·"}
</button>
</td>
);
})}
<td className="px-2 py-2 text-center">
<span className={`text-xs font-medium px-1.5 py-0.5 rounded ${r.completed ? "bg-green-50 text-green-800" : "text-gray-600"}`}>{r.attended}/{r.total}</span>
</td>
{certsOn && (
<td className="px-3 py-2 whitespace-nowrap">
{r.certificate && !r.certificate.revokedAt ? (
<div className="flex items-center gap-2 text-xs">
<span className="font-mono text-gray-700">{r.certificate.code}</span>
<button type="button" className="text-brand-700 hover:underline" onClick={() => download(`/api/attendance/certificates/${r.certificate!.id}/pdf`, `Certificate - ${r.name}.pdf`)}>PDF</button>
{canManage && <button type="button" className="text-brand-700 hover:underline" onClick={() => post(`/api/attendance/${eventId}/certificates/send`, { certificateId: r.certificate!.id }, x => (x.sent ? `Certificate sent to ${r.name}.` : `Couldn't send — ${r.name} has no email or WhatsApp on file.`))}>{r.certificate.emailedAt ? "Resend" : "Send"}</button>}
{canManage && <button type="button" className="text-red-600 hover:underline inline-flex items-center gap-0.5" onClick={() => post(`/api/attendance/certificates/${r.certificate!.id}/revoke`, {}, () => `Certificate for ${r.name} revoked.`)}><Ban className="w-3 h-3" />Revoke</button>}
</div>
) : canManage ? (
<button type="button" className="text-xs text-brand-700 hover:underline" onClick={() => post(`/api/attendance/${eventId}/certificates`, { ticketId: r.ticketId }, () => `Certificate issued to ${r.name}.`)}>
{r.certificate?.revokedAt ? "Re-issue" : r.completed ? "Issue" : "Issue anyway"}
</button>
) : <span className="text-xs text-gray-400">—</span>}
</td>
)}
</tr>
))}
</tbody>
<tfoot className="bg-gray-50 text-xs text-gray-600">
<tr>
<td className="sticky left-0 bg-gray-50 px-3 py-2 font-medium">Present</td>
{columns.map(c => <td key={c.id} className="px-2 py-2 text-center font-medium">{c.cancelled ? "—" : reg.totals[c.id] || 0}</td>)}
<td />
{certsOn && <td />}
</tr>
</tfoot>
</table>
</div>
)}
{reg && canManage && (
<p className="text-[11px] text-gray-400">Click a box to mark someone present or absent (e.g. they were let in without a scan). Changes are recorded in the audit log.</p>
)}
</div>
)}
</div>
);
}
export default function AttendancePage() {
return (
<Suspense fallback={null}>
<AttendancePageInner />
</Suspense>
);
}
@@ -4,7 +4,7 @@ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSta
import { createPortal } from "react-dom";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { apiFetch, API_BASE } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
@@ -13,6 +13,12 @@ import { ChoicesEditor } from "@/components/shared/FormFieldExtras";
import { errorMessage } from "@/lib/utils";
import type { Event, EventAttachment, EventFormField, EventOption, Paginated, Section } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import {
SessionsEditor, AttendanceSettings, keyed, sortSessions, sessionsProblem, defaultCertificate,
type KeyedSession, type AttendanceDraft,
} from "@/components/events/ScheduleEditor";
import { toSessionDraft, scheduleSummary } from "@/lib/sessions";
import { fetchApiFile, openBlob } from "@/lib/export";
// ─── helpers ────────────────────────────────────────────────────────────────
@@ -803,8 +809,8 @@ function NotifyRecipientsManager({ eventId, creator, initialRecipients }: { even
// ─── steps ───────────────────────────────────────────────────────────────────
const STEPS = ["Basic Details", "Items & Pricing", "Sections", "Form", "Visibility", "Notifications", "Attachments", "Feedback"] as const;
type StepIdx = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
const STEPS = ["Basic Details", "Items & Pricing", "Sections", "Form", "Visibility", "Notifications", "Attachments", "Feedback", "Attendance"] as const;
type StepIdx = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
const PRICING_SUBSTEPS = ["Options", "Variants", "Early Birds"] as const;
type PricingSubstep = 0 | 1 | 2;
@@ -819,6 +825,7 @@ interface EventDraft {
waitlistEnabled: boolean; waitlistOfferHours: string; waitlistPartialOffers: boolean;
allowTicketTransfer: boolean; collectGender: boolean;
allowSponsorships: boolean; sponsorshipGoalSpots: string; showSponsorshipProgress: boolean;
scheduleType: "single" | "sessions";
}
const blankDraft = (location = ""): EventDraft => ({
@@ -832,8 +839,12 @@ const blankDraft = (location = ""): EventDraft => ({
waitlistEnabled: false, waitlistOfferHours: "24", waitlistPartialOffers: true,
allowTicketTransfer: true, collectGender: false,
allowSponsorships: false, sponsorshipGoalSpots: "", showSponsorshipProgress: true,
scheduleType: "single",
});
// "YYYY-MM-DDTHH:MM" (local) → ISO
const isoOf = (local: string) => new Date(local).toISOString();
const blankOptions = (): OptionDraft[] => [
{ name: "Ticket", price: "", isMainTicket: true, stockLimit: "0", earlyBirdTiers: [], variants: [] }
];
@@ -874,8 +885,35 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
allowSponsorships: !!ev.allowSponsorships, sponsorshipGoalSpots: ev.sponsorshipGoalSpots ? String(ev.sponsorshipGoalSpots) : "", showSponsorshipProgress: ev.showSponsorshipProgress !== false,
contactName: ev.contactName || "", contactPhone: ev.contactPhone || "", contactEmail: ev.contactEmail || "",
location: ev.location || "",
scheduleType: ev.scheduleType === "sessions" ? "sessions" : "single",
} : blankDraft(settings.org_address || ""));
// ── multi-day schedule + attendance settings ──
const [sessions, setSessions] = useState<KeyedSession[]>(() => (ev?.sessions || []).map(s => keyed(toSessionDraft(s))));
const [attendance, setAttendance] = useState<AttendanceDraft>(() => ({
lateJoinEnabled: !!ev?.lateJoinEnabled,
lateJoinUntilKey: ev?.lateJoinUntilSessionId || "",
latePricing: ev?.latePricing || "full",
lateFixedPrice: ev?.lateFixedPrice !== null && ev?.lateFixedPrice !== undefined ? String(ev.lateFixedPrice) : "",
checkInWindow: ev?.checkInWindow || "whole_day",
remindersEnabled: !!ev?.sessionReminders,
reminderOffsets: ev?.sessionReminders?.offsets || [180],
reminderChannels: ev?.sessionReminders?.channels || ["email", "whatsapp"],
certificatesEnabled: !!ev?.certificatesEnabled,
certificate: { ...defaultCertificate(), ...(ev?.certificateConfig || {}) },
}));
const updAttendance = (patch: Partial<AttendanceDraft>) => setAttendance(a => ({ ...a, ...patch }));
const multi = draft.scheduleType === "sessions";
// 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);
if (!active.length) return null;
const end = active.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), active[0].endsAt);
return { start: active[0].startsAt, end };
}, [sessions]);
// Shown after saving when sessions moved or were cancelled, to offer telling registrants.
const [changedNotice, setChangedNotice] = useState<{ eventId: string; moved: number; cancelled: number } | null>(null);
// ── options (with per-variant tiers) ──
const [options, setOptions] = useState<OptionDraft[]>(() => {
if (!ev?.eventOptions?.length) return blankOptions();
@@ -951,8 +989,9 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
{ type: "text", label: "What could we do better?", isRequired: false, helpText: "" },
] });
}
if (on && !fbSettings.sendAt && draft.endDate) {
const next = new Date(draft.endDate);
const endForFeedback = multi ? scheduleBounds?.end : draft.endDate;
if (on && !fbSettings.sendAt && endForFeedback) {
const next = new Date(endForFeedback);
next.setDate(next.getDate() + 1);
next.setHours(9, 0, 0, 0);
setFbSettings(s => ({ ...s, sendAt: toLocalDT(next) }));
@@ -1176,16 +1215,35 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
const handleSave = async () => {
if (!draft.title.trim()) { setError("Title is required"); setStep(0); return; }
if (!draft.startDate || !draft.endDate) { setError("Start and end dates are required"); setStep(0); return; }
if (multi) {
const problem = sessionsProblem(sessions);
if (problem) { setError(problem); setStep(0); return; }
if (attendance.lateJoinEnabled && !attendance.lateJoinUntilKey) { setError("Choose until which session late joining is allowed"); setStep(8); return; }
if (attendance.lateJoinEnabled && attendance.latePricing === "fixed" && attendance.lateFixedPrice.trim() === "") { setError("Enter the fixed late price"); setStep(8); return; }
} else if (!draft.startDate || !draft.endDate) { setError("Start and end dates are required"); setStep(0); return; }
if (mode === "create" && draft.requiresRegistration) {
if (isPriceInvalid(draft.price)) { setError("Base price is required (enter 0 for a free event)"); setStep(0); return; }
if (options.some(o => isPriceInvalid(o.price))) { setError("Every option needs a price (enter 0 for a free option)"); setStep(1); setPricingSubstep(0); return; }
}
setSaving(true); setError(null);
try {
const sortedSessions = sortSessions(sessions);
const body: Record<string, unknown> = {
title: draft.title.trim(), description: draft.description || undefined,
startDate: new Date(draft.startDate).toISOString(), endDate: new Date(draft.endDate).toISOString(),
startDate: multi && scheduleBounds ? isoOf(scheduleBounds.start) : new Date(draft.startDate).toISOString(),
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 })),
lateJoinEnabled: attendance.lateJoinEnabled,
lateJoinUntilSessionIndex: attendance.lateJoinEnabled ? sortedSessions.findIndex(s => s.key === attendance.lateJoinUntilKey) : -1,
latePricing: attendance.latePricing,
lateFixedPrice: attendance.latePricing === "fixed" ? attendance.lateFixedPrice : null,
checkInWindow: attendance.checkInWindow,
sessionReminders: attendance.remindersEnabled ? { offsets: attendance.reminderOffsets, channels: attendance.reminderChannels } : null,
} : {}),
certificatesEnabled: attendance.certificatesEnabled,
certificateConfig: attendance.certificate,
registrationDeadline: draft.registrationDeadline ? new Date(draft.registrationDeadline).toISOString() : undefined,
goLiveAt: draft.goLiveAt ? new Date(draft.goLiveAt).toISOString() : undefined,
price: draft.requiresRegistration ? (draft.price ? parseFloat(draft.price) : 0) : 0,
@@ -1212,13 +1270,16 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
location: draft.location.trim(),
};
let notice: { eventId: string; moved: number; cancelled: number } | null = null;
if (mode === "edit") {
body.isActive = draft.isActive;
if (!ev) throw new Error("No event loaded to save");
await apiFetch(`/api/events/${ev.id}`, { method: "PUT", authToken: token || undefined, body });
const saved = await apiFetch<Event & { sessionChanges?: { moved: number; cancelled: number } | null }>(`/api/events/${ev.id}`, { method: "PUT", authToken: token || undefined, body });
await saveOptions(ev.id);
// Form is saved inside saveOptions for edit mode; avoid double call
await saveFeedback(ev.id);
const ch = saved?.sessionChanges;
if (ch && (ch.moved > 0 || ch.cancelled > 0)) notice = { eventId: ev.id, moved: ch.moved, cancelled: ch.cancelled };
} else {
if (formDef.isRequired || formDef.fields.length > 0) {
body.form = { isRequired: !!formDef.isRequired, fields: formDef.fields.filter(f => f.label?.trim()).map((f, i) => ({ type: f.type, label: f.label, isRequired: !!f.isRequired, order: i, helpText: f.helpText || null, options: f.type === "multiple_choice" ? cleanChoices(f.options) : undefined })) };
@@ -1247,7 +1308,9 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
}
}
onSuccess(); onClose();
onSuccess();
if (notice) setChangedNotice(notice);
else onClose();
} catch (e) {
setError(errorMessage(e) || "Failed to save event");
} finally {
@@ -1282,7 +1345,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
const isOnLastSubstep = step !== 1 || pricingSubstep === 2;
// Basic Details step requires title, start/end dates, and a base price before moving on
// (mirrors handleSave's own checks). Base price is only compulsory when creating a new event.
const basicDetailsIncomplete = step === 0 && (!draft.title.trim() || !draft.startDate || !draft.endDate || (mode === "create" && draft.requiresRegistration && isPriceInvalid(draft.price)));
const basicDetailsIncomplete = step === 0 && (!draft.title.trim() || (multi ? !!sessionsProblem(sessions) : (!draft.startDate || !draft.endDate)) || (mode === "create" && draft.requiresRegistration && isPriceInvalid(draft.price)));
// Items & Pricing: every option needs a valid price before leaving the step (checked across
// all pricing substeps so switching to Variants/Early Birds can't be used to skip the gate).
// Not applicable to contact-only events, which have no ticket options at all.
@@ -1339,6 +1402,18 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
</div>
)}
{error && <div className="p-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
{changedNotice && (
<div className="p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm space-y-2">
<p>
Saved. You {[changedNotice.moved ? `moved ${changedNotice.moved} session${changedNotice.moved === 1 ? "" : "s"}` : "", changedNotice.cancelled ? `cancelled ${changedNotice.cancelled}` : ""].filter(Boolean).join(" and ")}.
Tickets and calendar files show the new schedule, but people who registered aren&apos;t told automatically.
</p>
<div className="flex gap-2">
<a href={`/dashboard/supervisor/email-attendees?eventId=${changedNotice.eventId}`} className="px-3 py-1.5 text-xs rounded bg-brand-600 text-white hover:bg-brand-700">Message attendees</a>
<button type="button" onClick={onClose} className="px-3 py-1.5 text-xs rounded border bg-white hover:bg-gray-50">Done</button>
</div>
</div>
)}
{/* ── Step 0: Basic Details ── */}
{step === 0 && (
@@ -1351,10 +1426,26 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
<label className="block text-xs text-gray-600 mb-1">Description</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={3} value={draft.description} onChange={e => upd({ description: e.target.value })} />
</div>
<div>
<div className="block text-xs text-gray-600 mb-1">When <span className="text-red-500">*</span></div>
<div className="inline-flex rounded-lg border p-0.5 bg-gray-50">
{([["single", "One date"], ["sessions", "Multiple sessions"]] as const).map(([v, label]) => (
<button key={v} type="button" onClick={() => upd({ scheduleType: v })}
className={`px-3 py-1.5 text-xs rounded-md ${draft.scheduleType === v ? "bg-white shadow-sm text-brand-700 font-medium" : "text-gray-600 hover:text-gray-900"}`}>{label}</button>
))}
</div>
{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} />
) : (
<div className="grid sm:grid-cols-2 gap-3">
<DTInput label="Start" required value={draft.startDate} onChange={v => upd({ startDate: v })} />
<DTInput label="End" required value={draft.endDate} onChange={v => upd({ endDate: v })} />
</div>
)}
<div className="grid sm:grid-cols-2 gap-3">
<DTInput label="Start" required value={draft.startDate} onChange={v => upd({ startDate: v })} />
<DTInput label="End" required value={draft.endDate} onChange={v => upd({ endDate: v })} />
<DTInput label="Registration Deadline (optional)" value={draft.registrationDeadline} onChange={v => upd({ registrationDeadline: v })} />
<DTInput label="Registration Deadline (optional)" value={draft.registrationDeadline} onChange={v => upd({ registrationDeadline: v })} hint={multi ? "Registration closes when the first session starts unless late joining is on (Attendance step)" : undefined} />
<DTInput label="Go Live At (optional)" value={draft.goLiveAt} onChange={v => upd({ goLiveAt: v })} hint="Leave blank to show immediately" />
</div>
<div>
@@ -1431,6 +1522,22 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
</div>
)}
{/* ── Step 8: Attendance (late joining, check-in, reminders, certificates) ── */}
{step === 8 && (
<AttendanceSettings
value={attendance}
onChange={updAttendance}
multi={multi}
sessions={sessions}
mainPrice={parseFloat(options.find(o => o.isMainTicket)?.price || draft.price || "0") || 0}
uploadButton={(onUploaded) => <UploadImageButton onUploaded={onUploaded} label="Upload" />}
onPreview={async () => {
if (!token) return;
openBlob(await fetchApiFile(API_BASE, token, "/api/attendance/certificates/preview", { method: "POST", body: { title: draft.title || "Your event", config: attendance.certificate } }));
}}
/>
)}
{/* ── Step 2: Sections ── */}
{step === 2 && (
<div>
@@ -1714,7 +1821,7 @@ function EventCard({ ev, onEdit }: { ev: Event; onEdit: () => void }) {
{isClosed && <span className="text-[10px] px-1.5 py-0.5 rounded bg-rose-50 text-rose-700">Closed</span>}
</div>
<div className="text-xs text-gray-500 mt-0.5">
{ev.startDate ? new Date(ev.startDate).toLocaleDateString() : ""}{ev.endDate ? ` – ${new Date(ev.endDate).toLocaleDateString()}` : ""}
{scheduleSummary(ev) || <>{ev.startDate ? new Date(ev.startDate).toLocaleDateString() : ""}{ev.endDate ? ` – ${new Date(ev.endDate).toLocaleDateString()}` : ""}</>}
{ev.price != null ? <span className="ml-2">R{Number(ev.price).toFixed(0)}</span> : ""}
</div>
</div>
@@ -8,7 +8,7 @@ import { useStableState } from "@/hooks/useStableState";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, DoorOpen, Wallet,
UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter,
UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -27,6 +27,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet },
{ href: "/dashboard/supervisor/allocations", label: "Rooms & groups", description: "Put attendees into rooms, groups or buses", icon: BedDouble },
{ href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session, and certificates", icon: ClipboardCheck },
{ 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 },
@@ -16,6 +16,7 @@ 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 { MyCertificates } from "@/components/events/MyCertificates";
import type { Event, EventOption, Payment, Registration, RegistrationOption, Ticket as TicketRecord } from "@/types";
// Helper formatters
@@ -774,6 +775,8 @@ export default function UserDashboardPage() {
</div>
)}
<MyCertificates token={token} />
<div className="grid lg:grid-cols-2 gap-6">
<section className="mb-8 border rounded-xl p-5 bg-white shadow-sm">
<div className="flex items-center gap-2 mb-3">
@@ -47,13 +47,19 @@ type Event = {
waitlistEnabled?: boolean;
allowSponsorships?: boolean;
bundles?: PublicBundle[];
scheduleType?: "single" | "sessions";
sessions?: EventSession[];
registrationClosesAt?: string;
lateJoin?: LateJoinInfo | null;
};
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";
import type { EventSession, LateJoinInfo, PublicBundle } from "@/types";
import { latePrice, registrationClosesAt, scheduleSummary } from "@/lib/sessions";
import { SessionSchedule } from "@/components/events/SessionSchedule";
import { appUrl, appName } from "@/lib/siteConfig";
import { getServerSettings } from "@/lib/serverSettings";
import { eventJsonLd, jsonLdString } from "@/lib/eventSchema";
@@ -82,11 +88,10 @@ function RegisterCta({ event }: { event: Event }) {
);
}
const now = new Date();
const end = new Date(event.endDate);
const deadline = event.registrationDeadline ? new Date(event.registrationDeadline) : null;
const goLive = event.goLiveAt ? new Date(event.goLiveAt) : null;
const notYetOpen = goLive ? now < goLive : false;
const closed = (deadline ? now >= deadline : false) || now >= end;
// Multi-day events close when the first session starts (or later with late joining).
const closed = now >= registrationClosesAt(event);
const limitedOpts = (event.eventOptions || []).filter(o => (o.stockLimit ?? 0) > 0);
const eventSoldOut = limitedOpts.length > 0 && limitedOpts.every(o => o.availableCount !== undefined && o.availableCount <= 0);
@@ -203,7 +208,7 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id
<h1 className="text-3xl font-bold text-gray-900">{event.title}</h1>
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-2">
<Calendar className="w-4 h-4 shrink-0" />
{formatDateTimeRange(event.startDate, event.endDate)}
{scheduleSummary(event) || formatDateTimeRange(event.startDate, event.endDate)}
</p>
<div className="mt-3">
<ClientActions event={event} />
@@ -212,6 +217,10 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id
<p className="text-gray-700 whitespace-pre-line">{event.description}</p>
{event.scheduleType === "sessions" && (event.sessions || []).length > 0 && (
<SessionSchedule sessions={event.sessions || []} defaultLocation={event.location} />
)}
{event.location && (
<div className="border rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-base font-semibold text-gray-900 mb-3">Location</h2>
@@ -281,16 +290,24 @@ function TicketList({ event }: { event: Event }) {
</div>
);
}
// 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);
return (
<div className="space-y-2">
<BundleOffers bundles={event.bundles} />
{late && (
<p className="text-xs text-brand-800 bg-brand-50 border border-brand-200 rounded-lg px-3 py-2">
Joining late? {late.sessionsLeft} of {late.totalSessions} sessions are still to come, so the ticket price below is {late.mode === "prorata" ? "for the sessions left" : "the late-joiner price"}.
</p>
)}
{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;
const nearlyOut = !soldOut && (opt.stockLimit ?? 0) > 0 && opt.availableCount !== undefined && opt.availableCount <= lowStockThreshold(opt.stockLimit ?? 0);
if (hasVariants) {
const prices = opt.variants!.map((v) => v.price !== null && v.price !== undefined ? v.price : opt.price);
const prices = opt.variants!.map((v) => forLate(opt, v.price !== null && v.price !== undefined ? v.price : opt.price));
const minPrice = Math.min(...prices);
const maxPrice = Math.max(...prices);
const priceLabel = minPrice === 0 && maxPrice === 0 ? "Free" : minPrice === maxPrice ? `R${minPrice.toFixed(2)}` : minPrice === 0 ? `Free – R${maxPrice.toFixed(2)}` : `From R${minPrice.toFixed(2)}`;
@@ -306,7 +323,7 @@ function TicketList({ event }: { event: Event }) {
</div>
<ul className="divide-y">
{opt.variants!.slice().sort((a, b) => (a.order ?? 0) - (b.order ?? 0)).map((v) => {
const vPrice = v.price !== null && v.price !== undefined ? v.price : opt.price;
const vPrice = forLate(opt, v.price !== null && v.price !== undefined ? v.price : opt.price);
const vSoldOut = (v.stockLimit ?? 0) > 0 && v.availableCount !== undefined && v.availableCount <= 0;
const vNearlyOut = !vSoldOut && (v.stockLimit ?? 0) > 0 && v.availableCount !== undefined && v.availableCount <= lowStockThreshold(v.stockLimit ?? 0);
return (
@@ -330,7 +347,7 @@ function TicketList({ event }: { event: Event }) {
const activeTiers = (opt.earlyBirdTiers || [])
.filter((t) => now < new Date(t.deadline))
.sort((a, b) => a.price - b.price);
const displayPrice = activeTiers.length > 0 ? activeTiers[0].price : opt.price;
const displayPrice = forLate(opt, activeTiers.length > 0 ? activeTiers[0].price : opt.price);
return (
<div key={opt.id} className="flex items-center justify-between border rounded-lg px-3 py-2 text-sm text-gray-700">
+3 -1
View File
@@ -20,6 +20,8 @@ type Event = {
startDate: string;
endDate: string;
registrationDeadline?: string | null;
// Multi-day events: listed by their next session, not their first.
nextSession?: { startsAt: string } | null;
goLiveAt?: string;
price: number;
picture?: string;
@@ -35,7 +37,7 @@ export default async function EventsPage() {
const t = new Date(e.endDate || e.startDate).getTime();
return !isNaN(t) && t > now;
});
const sorted = [...upcoming].sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
return (
<div className="min-h-screen flex flex-col">
+3 -1
View File
@@ -19,6 +19,8 @@ type Event = {
startDate: string;
endDate: string;
registrationDeadline?: string | null;
// Multi-day events: listed by their next session, not their first.
nextSession?: { startsAt: string } | null;
goLiveAt?: string;
price: number;
picture?: string;
@@ -55,7 +57,7 @@ export default async function HomePage() {
const t = new Date(e.endDate || e.startDate).getTime();
return !isNaN(t) && t > now;
});
const sorted = [...upcoming].sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime());
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
return (
<div className="min-h-screen flex flex-col">
@@ -5,7 +5,8 @@ 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 type { EventSession, LateJoinInfo, PublicBundle } from "@/types";
import { latePrice, registrationClosesAt } from "@/lib/sessions";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { JoinWaitlistButton } from "@/components/events/JoinWaitlistButton";
import { analyticsSessionId } from "@/lib/analytics";
@@ -52,8 +53,28 @@ export type RegisterEvent = {
collectGender?: boolean;
waitlistEnabled?: boolean;
bundles?: PublicBundle[];
scheduleType?: "single" | "sessions";
sessions?: EventSession[];
registrationClosesAt?: string;
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 : {
...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; quantity: number; expiresAt: string; optionName: string; variantName: string | null };
// Key format: "optionId" for no-variant options, "optionId:variantId" for variant options
@@ -350,10 +371,11 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
.catch((e: unknown) => setOfferError(errorMessage(e) || "This waitlist link is not valid."));
}, []);
const event = useMemo<RegisterEvent>(() => {
if (!offer) return baseEvent;
const priced = withLatePrices(baseEvent);
if (!offer) return priced;
return {
...baseEvent,
eventOptions: (baseEvent.eventOptions || []).map(o => {
...priced,
eventOptions: (priced.eventOptions || []).map(o => {
if (o.id !== offer.eventOptionId) return o;
return {
...o,
@@ -400,11 +422,11 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
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)) {
if ((deadline && now >= deadline) || (end && now >= end) || now >= registrationClosesAt(event)) {
window.location.replace('/events');
}
} catch {}
}, [event.endDate, event.registrationDeadline]);
}, [event]);
const handleQtyChange = (key: string, val: number) => {
setQuantities((q) => ({ ...q, [key]: val }));
@@ -672,6 +694,12 @@ export default function RegisterForm({ event: baseEvent }: { event: RegisterEven
</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();