"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter, useSearchParams } from "next/navigation"; import { fetchManagedEvents } from "@/lib/api"; import { formatDate } from "@/lib/date"; import { useDismissingState } from "@/hooks/useDismissingState"; import { ShieldCheck, Send, RefreshCw, HeartPulse, Printer } from "lucide-react"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"; import { errorMessage } from "@/lib/utils"; import type { Event, ConsentRow, MedicalRow } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker, defaultEventId } from "@/components/shared/EventPicker"; import { apiV2Data } from "@/lib/apiV2"; const STATUS_STYLE: Record = { not_required: { label: "Not needed (18+)", cls: "bg-gray-100 text-gray-600" }, missing: { label: "No request", cls: "bg-red-100 text-red-800" }, pending: { label: "Pending", cls: "bg-amber-100 text-amber-800" }, given: { label: "Given", cls: "bg-green-100 text-green-800" }, declined: { label: "Declined", cls: "bg-red-100 text-red-800" }, }; const esc = (s: unknown) => String(s ?? "").replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c] as string)); export default function ConsentTrackerPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const search = useSearchParams(); const canView = useMemo(() => ["admin", "supervisor", "staff"].includes(user?.role || ""), [user]); const isSupervisor = 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") || ""); type ConsentData = { event: Pick; counts: Record; rows: ConsentRow[] }; const [data, setData] = useState(null); const [filter, setFilter] = useState<"minors" | "all" | "waiting">("minors"); const [busy, setBusy] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); useEffect(() => { if (!token || !canView) return; fetchManagedEvents(token, { past: true }) .then(evs => { const youth = (evs || []).filter(e => e.requiresParentalConsent); setEvents(youth); if (!eventId && youth.length) setEventId(defaultEventId(youth)); }) .catch(e => setError(e?.message || "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 { setData(await (apiV2Data("get", "/events/{id}/consent", { params: { id: eventId }, authToken: token }) as Promise)); } catch (e) { setError(errorMessage(e) || "Failed to load consent status"); } finally { setBusy(false); } }, [token, eventId, setError]); useEffect(() => { load(); }, [load]); const rows = useMemo(() => { const all = data?.rows || []; if (filter === "all") return all; if (filter === "waiting") return all.filter(r => ["missing", "pending", "declined"].includes(r.status) || r.request?.outdated); return all.filter(r => r.minor); }, [data, filter]); const outdatedCount = (data?.rows || []).filter(r => r.request?.outdated || (r.minor && r.status === "missing")).length; const act = async (fn: () => Promise) => { setBusy(true); try { const res = (await fn()) as { message: string }; setInfo(res.message); await load(); } catch (e) { setError(errorMessage(e) || "Something went wrong"); } finally { setBusy(false); } }; const resendOne = (r: ConsentRow) => act(() => apiV2Data("post", "/consent-requests/{id}/resend", { params: { id: r.request!.id }, authToken: token, body: {} })); const resendAll = () => act(() => apiV2Data("post", "/events/{id}/consent/resend-pending", { params: { id: eventId }, authToken: token, body: {} })); const rerequest = () => act(() => apiV2Data("post", "/events/{id}/consent/rerequest", { params: { id: eventId }, authToken: token, body: {} })); // Printable list for camp leaders. Opening it is recorded in the audit log. const printMedical = async () => { try { const res = await (apiV2Data("get", "/events/{id}/consent/medical", { params: { id: eventId }, authToken: token }) as Promise<{ event: Pick; rows: MedicalRow[] }>); const w = window.open("", "_blank"); if (!w) { setError("Allow pop-ups to print the medical list."); return; } const rowsHtml = res.rows.map(r => ` ${esc(r.name)}
${r.dateOfBirth ? esc(formatDate(new Date(r.dateOfBirth))) : ""} ${r.purged ? "Deleted after the event" : ` ${r.medical?.allergies ? `
Allergies: ${esc(r.medical.allergies)}
` : ""} ${r.medical?.medication ? `
Medication: ${esc(r.medical.medication)}
` : ""} ${r.medical?.conditions ? `
Conditions: ${esc(r.medical.conditions)}
` : ""} ${r.medical?.medicalAid ? `
Medical aid: ${esc(r.medical.medicalAid)}
` : ""}`} ${r.emergency ? `${esc(r.emergency.name)}${r.emergency.relationship ? ` (${esc(r.emergency.relationship)})` : ""}
${esc(r.emergency.phone)}` : ""} ${esc(r.parentName)}
${esc(r.parentPhone)} ${r.photoConsent === null ? "" : r.photoConsent ? "Yes" : "No"} `).join(""); w.document.write(`Medical & emergency list — ${esc(res.event.title)}

Medical & emergency list — ${esc(res.event.title)}

Confidential — for event leaders only. Do not leave unattended; destroy after the event.

${rowsHtml || ''}
AttendeeMedicalEmergency contactParent / guardianPhotos
No consent given yet.
`); w.document.close(); } catch (e) { setError(errorMessage(e) || "Failed to load the medical list"); } }; return (

Parental consent

Youth events: who still needs a parent's consent before check-in

{!canView &&
You need staff access to view consent status.
} {error &&
{error}
} {info &&
{info}
} {canView && (
{ setEventId(id); }} placeholder="No youth events" />
{isSupervisor && eventId && (
)}
{data && (
{(["given", "pending", "declined", "missing"] as const).map(s => ( {STATUS_STYLE[s].label}: {data.counts?.[s] || 0} ))}
)}
Attendee Parent / guardian Consent Booked by Actions {rows.map(r => { const st = STATUS_STYLE[r.status]; return (
{r.name}
{r.dateOfBirth ? formatDate(new Date(r.dateOfBirth)) : "No date of birth"}
{r.parentName ? <>
{r.parentName}
{[r.parentEmail, r.parentPhone].filter(Boolean).join(" · ")}
: —}
{st.label} {r.request?.outdated &&
Given on an older version of the text
} {r.request?.respondedAt &&
{r.request.signedName} · {formatDate(new Date(r.request.respondedAt))}
} {r.status === "pending" && r.request &&
Sent {formatDate(new Date(r.request.lastSentAt))}{r.request.remindersSent ? ` · ${r.request.remindersSent} reminder(s)` : ""}
}
{r.bookedBy?.name}
{r.registrationStatus}
{r.status === "pending" && r.request && ( )}
); })} {!busy && rows.length === 0 && ( {eventId ? "No attendees to show." : "Pick a youth event."} )}

Reminders go out automatically 2 days after a request, then every 3 days until the event. Medical details are deleted a set number of days after the event (Site Settings → Legal).

)}
); }