"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([]); const [eventId, setEventId] = useState(search.get("eventId") || ""); const [reg, setReg] = useState(null); const [busy, setBusy] = useState(false); const [pending, setPending] = useState(null); const [query, setQuery] = useState(""); const [filter, setFilter] = useState("all"); const [showCancelled, setShowCancelled] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); useEffect(() => { if (!token || !canView) return; apiFetch("/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(`/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 { // 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(); } catch (e) { setError(errorMessage(e) || "Couldn't update attendance"); } finally { setPending(null); } }; const post = async (path: string, body: object, done: (r: Record) => string) => { if (!token) return; setBusy(true); try { const r = await apiFetch>(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 (

Attendance

Who came to each session, and completion certificates

{!canView &&
You need staff access to view attendance.
} {error &&
{error}
} {info &&
{info}
} {canView && (
setQuery(e.target.value)} />
{multi && (reg?.columns || []).some(c => c.cancelled) && ( )}
{reg && (
{reg.rows.length} attendee{reg.rows.length === 1 ? "" : "s"} {completed} completed {certsOn && {issued} certificate{issued === 1 ? "" : "s"} issued} {!multi && Single-date event — one check-in column}
)} {reg && certsOn && canManage && (
Certificates are issued automatically when the event ends. You can also:
)} {busy && !reg &&

Loading…

} {reg && rows.length === 0 &&

{reg.rows.length === 0 ? "No tickets for this event yet." : "Nobody matches."}

} {reg && rows.length > 0 && (
{columns.map(c => ( ))} {certsOn && } {rows.map(r => ( {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 ; } const disabled = !canManage || c.cancelled || pending !== null || reg.event.cashupStatus === "closed"; return ( ); })} {certsOn && ( )} ))} {columns.map(c => )}
Name
{c.label}
{multi ? colDate.format(new Date(c.startsAt)) : ""}
TotalCertificate
{r.name || "—"}{r.quantity > 1 && ×{r.quantity}}
{r.variant ? `${r.option} — ${r.variant}` : r.option}{r.bookedBy ? ` · booked by ${r.bookedBy}` : ""}
— {r.attended}/{r.total} {r.certificate && !r.certificate.revokedAt ? (
{r.certificate.code} {canManage && } {canManage && }
) : canManage ? ( ) : —}
Present{c.cancelled ? "—" : reg.totals[c.id] || 0} {certsOn && }
)} {reg && canManage && (

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.

)}
)}
); } export default function AttendancePage() { return ( ); }