This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/app/dashboard/supervisor/consent/page.tsx
T
joshuaandClaude Opus 5.5 9be78c3c34 Use one back link style across the dashboards
Every dashboard page now uses the shared BackLink, the small
"← Back to dashboard" link above the page title that the Waitlist page
already had, instead of a mix of grey Back buttons in different places.
Pages that had no way back (site settings, profile, donate, manual
registration) get one too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:25:04 +02:00

236 lines
13 KiB
TypeScript

"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter, useSearchParams } from "next/navigation";
import { apiFetch } 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";
const STATUS_STYLE: Record<ConsentRow["status"], { label: string; cls: string }> = {
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 => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[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<Event[]>([]);
const [eventId, setEventId] = useState<string>(search.get("eventId") || "");
const [data, setData] = useState<{ event: Pick<Event, "id" | "title">; counts: Record<string, number>; rows: ConsentRow[] } | null>(null);
const [filter, setFilter] = useState<"minors" | "all" | "waiting">("minors");
const [busy, setBusy] = 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 => {
const youth = (evs || []).filter(e => e.requiresParentalConsent);
setEvents(youth);
if (!eventId && youth.length) setEventId(youth[youth.length - 1].id);
})
.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 apiFetch(`/api/consent/events/${encodeURIComponent(eventId)}`, { authToken: token }));
} 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<{ message: string }>) => {
setBusy(true);
try {
const res = await fn();
setInfo(res.message);
await load();
} catch (e) {
setError(errorMessage(e) || "Something went wrong");
} finally {
setBusy(false);
}
};
const resendOne = (r: ConsentRow) => act(() => apiFetch(`/api/consent/requests/${r.request!.id}/resend`, { method: "POST", authToken: token! }));
const resendAll = () => act(() => apiFetch(`/api/consent/events/${eventId}/resend-pending`, { method: "POST", authToken: token! }));
const rerequest = () => act(() => apiFetch(`/api/consent/events/${eventId}/rerequest`, { method: "POST", authToken: token! }));
// Printable list for camp leaders. Opening it is recorded in the audit log.
const printMedical = async () => {
try {
const res = await apiFetch<{ event: Pick<Event, "id" | "title">; rows: MedicalRow[] }>(`/api/consent/events/${eventId}/medical`, { authToken: token! });
const w = window.open("", "_blank");
if (!w) { setError("Allow pop-ups to print the medical list."); return; }
const rowsHtml = res.rows.map(r => `
<tr>
<td><strong>${esc(r.name)}</strong><br/><small>${r.dateOfBirth ? esc(formatDate(new Date(r.dateOfBirth))) : ""}</small></td>
<td>${r.purged ? "<em>Deleted after the event</em>" : `
${r.medical?.allergies ? `<div><b>Allergies:</b> ${esc(r.medical.allergies)}</div>` : ""}
${r.medical?.medication ? `<div><b>Medication:</b> ${esc(r.medical.medication)}</div>` : ""}
${r.medical?.conditions ? `<div><b>Conditions:</b> ${esc(r.medical.conditions)}</div>` : ""}
${r.medical?.medicalAid ? `<div><b>Medical aid:</b> ${esc(r.medical.medicalAid)}</div>` : ""}`}</td>
<td>${r.emergency ? `${esc(r.emergency.name)}${r.emergency.relationship ? ` (${esc(r.emergency.relationship)})` : ""}<br/>${esc(r.emergency.phone)}` : ""}</td>
<td>${esc(r.parentName)}<br/>${esc(r.parentPhone)}</td>
<td>${r.photoConsent === null ? "" : r.photoConsent ? "Yes" : "No"}</td>
</tr>`).join("");
w.document.write(`<!doctype html><html><head><meta charset="utf-8"/><title>Medical &amp; emergency list — ${esc(res.event.title)}</title>
<style>body{font-family:system-ui,sans-serif;margin:24px;font-size:12px}h1{font-size:18px;margin:0 0 4px}p{color:#555;margin:0 0 12px}
table{width:100%;border-collapse:collapse}th,td{border:1px solid #ccc;padding:6px;vertical-align:top;text-align:left}th{background:#f3f4f6}
.conf{color:#b91c1c;font-weight:600}</style></head><body>
<h1>Medical &amp; emergency list — ${esc(res.event.title)}</h1>
<p class="conf">Confidential — for event leaders only. Do not leave unattended; destroy after the event.</p>
<table><thead><tr><th>Attendee</th><th>Medical</th><th>Emergency contact</th><th>Parent / guardian</th><th>Photos</th></tr></thead>
<tbody>${rowsHtml || '<tr><td colspan="5">No consent given yet.</td></tr>'}</tbody></table>
<script>window.onload=()=>window.print()</script></body></html>`);
w.document.close();
} catch (e) {
setError(errorMessage(e) || "Failed to load the medical list");
}
};
return (
<div className="max-w-6xl 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">
<ShieldCheck 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">Parental consent</h1>
<p className="text-sm text-gray-500">Youth events: who still needs a parent&apos;s consent before check-in</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 consent status.</div>}
{error && <div className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
{info && <div className="mb-3 p-3 border rounded bg-green-50 text-green-800 text-sm">{info}</div>}
{canView && (
<div className="border rounded-xl p-4 bg-white shadow-sm">
<div className="flex flex-wrap items-end gap-3 mb-4">
<div>
<label className="block text-xs text-gray-600 mb-1">Youth event</label>
<select className="border rounded-lg px-3 py-2 text-sm min-w-[16rem]" value={eventId} onChange={e => setEventId(e.target.value)}>
{events.length === 0 && <option value="">No youth events</option>}
{events.map(ev => <option key={ev.id} value={ev.id}>{ev.title} ({formatDate(new Date(ev.startDate))})</option>)}
</select>
</div>
<div>
<label className="block text-xs text-gray-600 mb-1">Show</label>
<select className="border rounded-lg px-3 py-2 text-sm" value={filter} onChange={e => setFilter(e.target.value as typeof filter)}>
<option value="minors">Under 18s</option>
<option value="waiting">Still to sort out</option>
<option value="all">Everyone</option>
</select>
</div>
{isSupervisor && eventId && (
<div className="flex flex-wrap gap-2 ml-auto">
<button onClick={resendAll} disabled={busy || !(data?.counts?.pending)} className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50"><Send className="w-4 h-4" /> Resend to all pending</button>
<button onClick={rerequest} disabled={busy || outdatedCount === 0} title="For consent given on an older version of the text, or under 18s who never got a request" className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border text-sm hover:bg-gray-50 disabled:opacity-50"><RefreshCw className="w-4 h-4" /> Re-request consent ({outdatedCount})</button>
<button onClick={printMedical} disabled={busy} className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50"><HeartPulse className="w-4 h-4" /> <Printer className="w-4 h-4" /> Medical &amp; emergency list</button>
</div>
)}
</div>
{data && (
<div className="flex flex-wrap gap-2 mb-3 text-xs">
{(["given", "pending", "declined", "missing"] as const).map(s => (
<span key={s} className={`px-2 py-1 rounded-full font-medium ${STATUS_STYLE[s].cls}`}>{STATUS_STYLE[s].label}: {data.counts?.[s] || 0}</span>
))}
</div>
)}
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Attendee</TableHead>
<TableHead>Parent / guardian</TableHead>
<TableHead>Consent</TableHead>
<TableHead>Booked by</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map(r => {
const st = STATUS_STYLE[r.status];
return (
<TableRow key={r.attendeeId}>
<TableCell>
<div className="font-medium">{r.name}</div>
<div className="text-xs text-gray-500">{r.dateOfBirth ? formatDate(new Date(r.dateOfBirth)) : "No date of birth"}</div>
</TableCell>
<TableCell className="text-sm">
{r.parentName ? <>
<div>{r.parentName}</div>
<div className="text-xs text-gray-500">{[r.parentEmail, r.parentPhone].filter(Boolean).join(" · ")}</div>
</> : <span className="text-gray-400">—</span>}
</TableCell>
<TableCell>
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${st.cls}`}>{st.label}</span>
{r.request?.outdated && <div className="text-xs text-amber-700 mt-1">Given on an older version of the text</div>}
{r.request?.respondedAt && <div className="text-xs text-gray-500 mt-1">{r.request.signedName} · {formatDate(new Date(r.request.respondedAt))}</div>}
{r.status === "pending" && r.request && <div className="text-xs text-gray-500 mt-1">Sent {formatDate(new Date(r.request.lastSentAt))}{r.request.remindersSent ? ` · ${r.request.remindersSent} reminder(s)` : ""}</div>}
</TableCell>
<TableCell className="text-sm">{r.bookedBy?.name}<div className="text-xs text-gray-500">{r.registrationStatus}</div></TableCell>
<TableCell className="text-right">
{r.status === "pending" && r.request && (
<button onClick={() => resendOne(r)} disabled={busy} className="px-2 py-1 text-xs rounded border hover:bg-gray-50">Resend</button>
)}
</TableCell>
</TableRow>
);
})}
{!busy && rows.length === 0 && (
<TableRow><TableCell colSpan={5} className="text-center text-sm text-gray-500 py-8">{eventId ? "No attendees to show." : "Pick a youth event."}</TableCell></TableRow>
)}
</TableBody>
</Table>
</div>
<p className="text-xs text-gray-500 mt-3">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).</p>
</div>
)}
</div>
);
}