Add parental consent for youth events

Youth events need a name and date of birth for every attendee, and a
parent/guardian's details for under-18s. Parents get an email and
WhatsApp link to a consent page that records the signed name, time, IP,
device and exact consent text; medical and emergency details are stored
encrypted. Tickets are issued but check-in is blocked until consent is
given (supervisor override audited). A daily job sends reminders and
purges medical details after the retention period. Adds a supervisor
consent tracker, consent status and medical list reports, and clears
consent data when an account is anonymised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 13:24:44 +02:00
co-authored by Claude Opus 5.5
parent 03b79972e6
commit f55353ecc6
41 changed files with 1988 additions and 88 deletions
@@ -22,6 +22,9 @@ const ACTIONS = [
"coupon_updated",
"coupon_disabled",
"coupon_applied_manual",
"consent_override",
"consent_rerequested",
"medical_list_viewed",
] as const;
const ACTION_LABELS: Record<string, string> = {
@@ -38,6 +41,9 @@ const ACTION_LABELS: Record<string, string> = {
coupon_updated: "Coupon edited",
coupon_disabled: "Coupon turned off",
coupon_applied_manual: "Coupon applied/removed by staff",
consent_override: "Consent overridden at check-in",
consent_rerequested: "Consent re-requested",
medical_list_viewed: "Medical list viewed",
};
interface AuditLogEntry {
@@ -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,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck,
} 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/manual", label: "Manual registration", description: "Register a guest and issue tickets", icon: UserPlus },
{ href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen },
{ href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet },
{ 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 },
{ href: "/dashboard/staff/ticket-scanning", label: "Open scanner", description: "Use your device camera to validate tickets", icon: QrCode },
{ href: "/dashboard/supervisor/reports", label: "Reports", description: "View, export, and email reports", icon: BarChart2 },
@@ -136,6 +136,7 @@ function SiteSettingsPageInner() {
const [legalIoEmail, setLegalIoEmail] = useState("");
const [legalWebsiteUrl, setLegalWebsiteUrl] = useState("");
const [legalEffectiveDate, setLegalEffectiveDate] = useState("");
const [consentRetentionDays, setConsentRetentionDays] = useState("30");
// ── Load all settings once ────────────────────────────────────────────────
useEffect(() => {
@@ -171,6 +172,7 @@ function SiteSettingsPageInner() {
setLegalIoEmail(s.legal_io_email || "");
setLegalWebsiteUrl(s.legal_website_url || "");
setLegalEffectiveDate(s.legal_effective_date || "");
setConsentRetentionDays(s.consent_medical_retention_days || "30");
})
.catch((e: any) => setResult({ ok: false, message: e?.message || "Failed to load settings" }))
.finally(() => setLoadingInitial(false));
@@ -319,6 +321,7 @@ function SiteSettingsPageInner() {
legal_io_email: legalIoEmail.trim(),
legal_website_url: legalWebsiteUrl.trim(),
legal_effective_date: legalEffectiveDate.trim(),
consent_medical_retention_days: String(Math.max(0, parseInt(consentRetentionDays, 10) || 0)),
});
const handleTestSmtp = async () => {
@@ -658,6 +661,15 @@ function SiteSettingsPageInner() {
</div>
</div>
<div className="border-t pt-4">
<p className="text-sm font-medium text-gray-700 mb-3">Youth events</p>
<Field label="Delete medical & emergency details this many days after an event">
<input type="number" min="0" className={`${inputCls} sm:w-32`}
value={consentRetentionDays} onChange={e => setConsentRetentionDays(e.target.value)} />
</Field>
<p className="text-xs text-gray-500 mt-1">Collected on parental consent forms. The consent record itself (who agreed, and when) is kept.</p>
</div>
<SaveBar saving={saving} onSave={saveLegal} result={result} />
</div>
)}
@@ -36,6 +36,9 @@ export default function TicketScanningPage() {
remaining: number;
} | null>(null);
const [confirmQty, setConfirmQty] = useState(1);
// Youth events: the preview says whether parental consent allows check-in.
const consentBlocked = !!confirmModal && !['not_required', 'given', undefined].includes(confirmModal.ticket?.consentStatus);
const canOverrideConsent = user?.role === 'admin' || user?.role === 'supervisor';
const [confirmQtyRaw, setConfirmQtyRaw] = useState("1");
// Event selection state
@@ -165,7 +168,7 @@ export default function TicketScanningPage() {
}
}
async function commitScan() {
async function commitScan(overrideConsent = false) {
if (!confirmModal || !token) return;
// Capture everything before clearing modal state
@@ -199,7 +202,7 @@ export default function TicketScanningPage() {
await apiFetch<any>(url, {
method: "POST",
authToken: token,
body: { qty },
body: { qty, ...(overrideConsent ? { overrideConsent: true } : {}) },
});
refreshStatsAndRecent();
} catch (e: any) {
@@ -383,6 +386,17 @@ export default function TicketScanningPage() {
<div><span className="font-medium">Remaining:</span> <span className={confirmModal.remaining < (confirmModal.ticket?.quantity || 1) ? 'text-amber-600 font-semibold' : 'text-green-700 font-semibold'}>{confirmModal.remaining}</span></div>
</div>
{consentBlocked && (
<div className="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
<div className="font-semibold">
{confirmModal.ticket?.consentStatus === 'declined' ? 'Parental consent was declined'
: confirmModal.ticket?.consentStatus === 'pending' ? 'Parental consent is still pending'
: 'Parental consent is missing'}
</div>
<div className="mt-1">This person can&apos;t be checked in until a parent or guardian gives consent.{canOverrideConsent ? ' As a supervisor you can override this — it is recorded in the audit log.' : ' Ask a supervisor.'}</div>
</div>
)}
{(confirmModal.ticket?.quantity || 1) > 1 && (
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-1">Qty to redeem (max {confirmModal.remaining})</label>
@@ -411,12 +425,23 @@ export default function TicketScanningPage() {
>
Cancel
</button>
<button
onClick={commitScan}
className="flex-1 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700"
>
Confirm Scan
</button>
{consentBlocked ? (
canOverrideConsent && (
<button
onClick={() => commitScan(true)}
className="flex-1 px-4 py-2 rounded-lg bg-red-600 text-white text-sm font-semibold hover:bg-red-700"
>
Override and check in
</button>
)
) : (
<button
onClick={() => commitScan()}
className="flex-1 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700"
>
Confirm Scan
</button>
)}
</div>
</div>
</div>
@@ -7,7 +7,7 @@ import { apiFetch } from "@/lib/api";
import { scoreUser } from "@/lib/fuzzyMatch";
import { useDismissingState } from "@/hooks/useDismissingState";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload } from "@/components/shared/AttendeeNamesEditor";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { DoorOpen, UserPlus, CreditCard, CheckSquare, Ticket, RotateCcw, type LucideIcon } from "lucide-react";
type Mode = "registration" | "payment" | "checkin" | "tickets" | "refund";
@@ -104,6 +104,7 @@ export default function AtTheDoorPage() {
const [pendingUser, setPendingUser] = useState<any | null>(null);
const [doorCoupon, setDoorCoupon] = useState<AppliedCoupon | null>(null);
const [doorAllowsNames, setDoorAllowsNames] = useState(false);
const [doorYouthStart, setDoorYouthStart] = useState<string | null>(null);
const [doorNaming, setDoorNaming] = useState(false);
const [doorEntries, setDoorEntries] = useState<AttendeeEntries>({});
const [doorDelivery, setDoorDelivery] = useState<TicketDelivery>("payer");
@@ -160,7 +161,8 @@ export default function AtTheDoorPage() {
});
setEventOptions(ev.options || ev.eventOptions || []);
setDoorAllowsNames(!!ev.allowNamedAttendees);
setDoorAllowsNames(!!ev.allowNamedAttendees || !!ev.requiresParentalConsent);
setDoorYouthStart(ev.requiresParentalConsent ? ev.startDate : null);
} catch {
setEventOptions([]);
}
@@ -230,6 +232,11 @@ export default function AtTheDoorPage() {
}
}
if (!pendingEditReg && doorYouthStart) {
const missing = consentDetailsMissing(eventOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries, doorYouthStart);
if (missing) { setError(missing); return; }
}
setConfirming(true);
try {
if (pendingEditReg) {
@@ -272,7 +279,7 @@ export default function AtTheDoorPage() {
options: opts,
notificationPreference: pendingUser.notifPref,
...(doorCoupon ? { couponCode: doorCoupon.code } : {}),
...(doorAllowsNames && doorNaming && attendeesPayload(eventOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries).length > 0
...(doorAllowsNames && (doorNaming || doorYouthStart) && attendeesPayload(eventOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries).length > 0
? { attendees: attendeesPayload(eventOptions, (o, v) => quantities[v ? `${o}::${v}` : o] || 0, doorEntries), ticketDelivery: doorDelivery }
: {}),
}
@@ -505,6 +512,7 @@ export default function AtTheDoorPage() {
enabled: doorNaming, onEnabledChange: setDoorNaming,
entries: doorEntries, onEntriesChange: setDoorEntries,
delivery: doorDelivery, onDeliveryChange: setDoorDelivery,
consentEventStart: doorYouthStart || undefined,
} : null}
/>
<DonationModal
@@ -0,0 +1,251 @@
"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";
type ConsentRow = {
attendeeId: string;
name: string;
dateOfBirth: string | null;
minor: boolean;
parentName: string | null;
parentEmail: string | null;
parentPhone: string | null;
registrationStatus: string;
bookedBy: { name: string; email: string };
status: "not_required" | "missing" | "pending" | "given" | "declined";
request: { id: string; status: string; textVersion: number; signedName: string | null; respondedAt: string | null; lastSentAt: string; remindersSent: number; photoConsent: boolean | null; outdated: boolean } | null;
};
type MedicalRow = {
name: string; dateOfBirth: string | null; parentName: string | null; parentPhone: string | null; parentEmail: string | null;
medical: { allergies: string; medication: string; conditions: string; medicalAid: string } | null;
emergency: { name: string; phone: string; relationship: string } | null;
photoConsent: boolean | null; purged: boolean;
};
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<any[]>([]);
const [eventId, setEventId] = useState<string>(search.get("eventId") || "");
const [data, setData] = useState<{ event: any; 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<any[]>("/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: any) {
setError(e?.message || "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: any) {
setError(e?.message || "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: any; 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: any) {
setError(e?.message || "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>
<button className="text-xs text-brand-600 hover:underline" onClick={() => router.push("/dashboard")}>← Back to dashboard</button>
<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>
);
}
@@ -770,6 +770,8 @@ interface EventDraft {
redirectUrl: string; isActive: boolean; isHidden: boolean; requiresAuth: boolean;
requiresRegistration: boolean; contactName: string; contactPhone: string; contactEmail: string;
location: string; allowNamedAttendees: boolean;
requiresParentalConsent: boolean; consentText: string;
consentCollectMedical: boolean; consentCollectEmergency: boolean; consentCollectPhoto: boolean;
}
const blankDraft = (location = ""): EventDraft => ({
@@ -778,6 +780,8 @@ const blankDraft = (location = ""): EventDraft => ({
redirectUrl: "", isActive: true, isHidden: false, requiresAuth: true,
requiresRegistration: true, contactName: "", contactPhone: "", contactEmail: "",
location, allowNamedAttendees: false,
requiresParentalConsent: false, consentText: "",
consentCollectMedical: true, consentCollectEmergency: true, consentCollectPhoto: true,
});
const blankOptions = (): OptionDraft[] => [
@@ -813,6 +817,8 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
isActive: ev.isActive !== false, isHidden: !!ev.isHidden, requiresAuth: ev.requiresAuth !== false,
requiresRegistration: ev.requiresRegistration !== false,
allowNamedAttendees: !!ev.allowNamedAttendees,
requiresParentalConsent: !!ev.requiresParentalConsent, consentText: ev.consentText || "",
consentCollectMedical: !!ev.consentCollectMedical, consentCollectEmergency: !!ev.consentCollectEmergency, consentCollectPhoto: !!ev.consentCollectPhoto,
contactName: ev.contactName || "", contactPhone: ev.contactPhone || "", contactEmail: ev.contactEmail || "",
location: ev.location || "",
} : blankDraft(settings.org_address || ""));
@@ -1086,7 +1092,12 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
picture: draft.picture || undefined, isHidden: draft.isHidden, requiresAuth: draft.requiresAuth,
redirectUrl: draft.redirectUrl?.trim().replace(/\s+/g, "-") || undefined,
requiresRegistration: draft.requiresRegistration,
allowNamedAttendees: draft.allowNamedAttendees,
allowNamedAttendees: draft.allowNamedAttendees || draft.requiresParentalConsent,
requiresParentalConsent: draft.requiresParentalConsent,
consentText: draft.consentText,
consentCollectMedical: draft.consentCollectMedical,
consentCollectEmergency: draft.consentCollectEmergency,
consentCollectPhoto: draft.consentCollectPhoto,
contactName: draft.contactName || undefined,
contactPhone: draft.contactPhone || undefined,
contactEmail: draft.contactEmail || undefined,
@@ -1352,6 +1363,28 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
</label>
)}
</div>
<div className="border rounded-lg p-4 bg-gray-50 space-y-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Youth event</div>
<label className="flex items-start gap-2 text-sm cursor-pointer">
<input type="checkbox" className="mt-0.5" checked={draft.requiresParentalConsent} onChange={e => upd({ requiresParentalConsent: e.target.checked, ...(e.target.checked ? { allowNamedAttendees: true } : {}) })} />
<span><strong>Requires parental consent</strong> — every attendee gives a date of birth; for anyone under 18, a parent or guardian is asked by email and WhatsApp to give consent before they can be checked in</span>
</label>
{draft.requiresParentalConsent && (
<>
<div>
<label className="block text-xs text-gray-600 mb-1">Consent text (shown to the parent)</label>
<textarea className="w-full border rounded px-2 py-1.5 text-sm" rows={6} value={draft.consentText} onChange={e => upd({ consentText: e.target.value })}
placeholder="e.g. I give permission for my child to take part in all activities, including transport, and for leaders to arrange medical treatment in an emergency." />
{mode === "edit" && <p className="text-[11px] text-gray-500 mt-1">Changing this starts a new version. Parents who already agreed keep their record; use &quot;Re-request consent&quot; on the Parental consent page to ask them again.</p>}
</div>
<div className="text-xs text-gray-600">Also ask the parent for:</div>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectMedical} onChange={e => upd({ consentCollectMedical: e.target.checked })} /> Medical info (allergies, medication, conditions, medical aid)</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectEmergency} onChange={e => upd({ consentCollectEmergency: e.target.checked })} /> An emergency contact</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={draft.consentCollectPhoto} onChange={e => upd({ consentCollectPhoto: e.target.checked })} /> Photo consent (yes/no)</label>
</>
)}
</div>
</div>
)}
@@ -7,7 +7,7 @@ import { apiFetch, fetchAllUsers } from "@/lib/api";
import { scoreUser } from "@/lib/fuzzyMatch";
import { useDismissingState } from "@/hooks/useDismissingState";
import { CouponCodeField, AppliedCoupon } from "@/components/shared/CouponCodeField";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload } from "@/components/shared/AttendeeNamesEditor";
import { AttendeeNamesEditor, AttendeeEntries, TicketDelivery, attendeesPayload, consentDetailsMissing } from "@/components/shared/AttendeeNamesEditor";
import { UserPlus, CreditCard } from "lucide-react";
// ─── Pricing helpers ─────────────────────────────────────────────────────────
@@ -224,7 +224,9 @@ export default function ManualRegistrationPage() {
const [attendeeEntries, setAttendeeEntries] = useState<AttendeeEntries>({});
const [delivery, setDelivery] = useState<TicketDelivery>("payer");
const manualQtyFor = (optionId: string, variantId: string | null) => quantities[variantId ? `${optionId}::${variantId}` : optionId] || 0;
const selectedEventAllowsNames = !!events.find(ev => ev.id === selectedEventId)?.allowNamedAttendees;
const selectedEv = events.find(ev => ev.id === selectedEventId);
const selectedIsYouth = !!selectedEv?.requiresParentalConsent;
const selectedEventAllowsNames = !!selectedEv?.allowNamedAttendees || selectedIsYouth;
const [pickedUserId, setPickedUserId] = useState<string | null>(null);
const selectUser = (u: any) => {
@@ -307,6 +309,10 @@ export default function ManualRegistrationPage() {
return { eventOptionId, quantity, ...(variantId ? { variantId } : {}) };
});
if (opts.length === 0) { setError("Please select at least one ticket option."); return; }
if (selectedIsYouth) {
const missing = consentDetailsMissing(options, manualQtyFor, attendeeEntries, selectedEv.startDate);
if (missing) { setError(missing); return; }
}
try {
setSubmitting(true);
@@ -322,7 +328,7 @@ export default function ManualRegistrationPage() {
user: guest,
notificationPreference: resolvedPref,
...(coupon ? { couponCode: coupon.code } : {}),
...(selectedEventAllowsNames && namingOthers && attendeesPayload(options, manualQtyFor, attendeeEntries).length > 0
...(selectedEventAllowsNames && (namingOthers || selectedIsYouth) && attendeesPayload(options, manualQtyFor, attendeeEntries).length > 0
? { attendees: attendeesPayload(options, manualQtyFor, attendeeEntries), ticketDelivery: delivery }
: {}),
}
@@ -617,6 +623,7 @@ export default function ManualRegistrationPage() {
delivery={delivery}
onDeliveryChange={setDelivery}
payerLabel="the person registering"
consentEventStart={selectedIsYouth ? selectedEv.startDate : undefined}
/>
</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,
UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -24,6 +24,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/manual", label: "Manual registration", description: "Register a guest and issue tickets", icon: UserPlus },
{ href: "/dashboard/supervisor/events", label: "Manage events", description: "Create, edit, and update ticket types", icon: Calendar },
{ href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet },
{ 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 },
{ href: "/dashboard/staff/ticket-scanning", label: "Open scanner", description: "Use your device camera to validate tickets", icon: QrCode },
{ href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen },