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:
@@ -0,0 +1,181 @@
|
||||
"use client";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Navbar } from "@/components/layout/Navbar";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import { ShieldCheck, CheckCircle2, XCircle } from "lucide-react";
|
||||
|
||||
type ConsentInfo = {
|
||||
status: "pending" | "given" | "declined";
|
||||
superseded: boolean;
|
||||
expired: boolean;
|
||||
respondedAt: string | null;
|
||||
attendeeName: string;
|
||||
parentName: string | null;
|
||||
consentText: string;
|
||||
event: { title: string; startDate: string; endDate: string; location: string | null };
|
||||
collect: { medical: boolean; emergency: boolean; photo: boolean };
|
||||
};
|
||||
|
||||
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
|
||||
|
||||
/** Public page a parent/guardian opens from their consent email or WhatsApp. */
|
||||
export default function ConsentPage() {
|
||||
const params = useParams<{ token: string }>();
|
||||
const token = params?.token;
|
||||
const [info, setInfo] = useState<ConsentInfo | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [done, setDone] = useState<"given" | "declined" | null>(null);
|
||||
|
||||
const [signedName, setSignedName] = useState("");
|
||||
const [isGuardian, setIsGuardian] = useState(false);
|
||||
const [medical, setMedical] = useState({ allergies: "", medication: "", conditions: "", medicalAid: "" });
|
||||
const [emergency, setEmergency] = useState({ name: "", phone: "", relationship: "" });
|
||||
const [photoConsent, setPhotoConsent] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
apiFetch<ConsentInfo>(`/api/consent/${encodeURIComponent(token)}`)
|
||||
.then(res => { setInfo(res); setSignedName(res.parentName || ""); })
|
||||
.catch(e => setLoadError(e instanceof ApiError ? e.message : "Couldn't load this consent request."));
|
||||
}, [token]);
|
||||
|
||||
const submit = async (decision: "give" | "decline") => {
|
||||
if (!token || !info) return;
|
||||
setError(null);
|
||||
if (decision === "give" && info.collect.photo && photoConsent === null) { setError("Please answer the photo consent question."); return; }
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiFetch(`/api/consent/${encodeURIComponent(token)}`, {
|
||||
method: "POST",
|
||||
body: {
|
||||
decision, signedName, isGuardian,
|
||||
...(decision === "give" && info.collect.medical ? { medical } : {}),
|
||||
...(decision === "give" && info.collect.emergency ? { emergency } : {}),
|
||||
...(decision === "give" && info.collect.photo ? { photoConsent } : {}),
|
||||
},
|
||||
});
|
||||
setDone(decision === "give" ? "given" : "declined");
|
||||
} catch (e) {
|
||||
setError(e instanceof ApiError ? e.message : "Couldn't save your answer. Please try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const open = info && info.status === "pending" && !info.superseded && !info.expired && !done;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
<main className="flex-1 px-4 py-10 max-w-2xl mx-auto w-full">
|
||||
<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>
|
||||
<h1 className="text-2xl font-semibold text-gray-900">Parental consent</h1>
|
||||
</div>
|
||||
|
||||
{loadError && <div className="border rounded-xl p-4 bg-red-50 text-red-800 text-sm">{loadError}</div>}
|
||||
{!info && !loadError && <div className="text-sm text-gray-600">Loading…</div>}
|
||||
|
||||
{info && (
|
||||
<div className="border rounded-xl p-5 bg-white shadow-sm space-y-4">
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">Event</div>
|
||||
<div className="font-semibold text-gray-900">{info.event.title}</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
{formatDate(new Date(info.event.startDate))}{info.event.endDate ? ` – ${formatDate(new Date(info.event.endDate))}` : ""}
|
||||
{info.event.location ? ` · ${info.event.location}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">Attendee</div>
|
||||
<div className="font-semibold text-gray-900">{info.attendeeName}</div>
|
||||
</div>
|
||||
|
||||
{(done || info.status !== "pending") && (
|
||||
<div className={`flex items-start gap-2 rounded-lg p-3 text-sm ${(done || info.status) === "given" ? "bg-green-50 text-green-800" : "bg-amber-50 text-amber-900"}`}>
|
||||
{(done || info.status) === "given" ? <CheckCircle2 className="w-5 h-5 shrink-0" /> : <XCircle className="w-5 h-5 shrink-0" />}
|
||||
<span>
|
||||
{(done || info.status) === "given" ? "Consent has been given. Thank you!" : "Consent has been declined. The organisers have been told."}
|
||||
{!done && info.respondedAt && ` (${formatDate(new Date(info.respondedAt))})`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{!done && info.status === "pending" && info.superseded && (
|
||||
<div className="rounded-lg p-3 text-sm bg-amber-50 text-amber-900">A newer consent request has replaced this one. Please use the link in your latest message.</div>
|
||||
)}
|
||||
{!done && info.status === "pending" && info.expired && (
|
||||
<div className="rounded-lg p-3 text-sm bg-gray-100 text-gray-700">This consent link has expired because the event has ended.</div>
|
||||
)}
|
||||
|
||||
{open && (
|
||||
<>
|
||||
<div>
|
||||
<div className="text-sm font-medium text-gray-800 mb-1">Please read</div>
|
||||
<div className="text-sm text-gray-700 whitespace-pre-line border rounded-lg p-3 bg-gray-50 max-h-72 overflow-y-auto">{info.consentText || "The organisers haven't added any consent text."}</div>
|
||||
</div>
|
||||
|
||||
{info.collect.medical && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium text-gray-800">Medical information <span className="font-normal text-gray-500">(kept confidential and deleted after the event)</span></legend>
|
||||
<textarea className={inputCls} rows={2} placeholder="Allergies" value={medical.allergies} onChange={e => setMedical({ ...medical, allergies: e.target.value })} aria-label="Allergies" />
|
||||
<textarea className={inputCls} rows={2} placeholder="Medication" value={medical.medication} onChange={e => setMedical({ ...medical, medication: e.target.value })} aria-label="Medication" />
|
||||
<textarea className={inputCls} rows={2} placeholder="Medical conditions" value={medical.conditions} onChange={e => setMedical({ ...medical, conditions: e.target.value })} aria-label="Medical conditions" />
|
||||
<input className={inputCls} placeholder="Medical aid (scheme and number)" value={medical.medicalAid} onChange={e => setMedical({ ...medical, medicalAid: e.target.value })} aria-label="Medical aid" />
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
{info.collect.emergency && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium text-gray-800">Emergency contact</legend>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
<input className={inputCls} placeholder="Name" value={emergency.name} onChange={e => setEmergency({ ...emergency, name: e.target.value })} aria-label="Emergency contact name" />
|
||||
<input type="tel" className={inputCls} placeholder="Phone" value={emergency.phone} onChange={e => setEmergency({ ...emergency, phone: e.target.value })} aria-label="Emergency contact phone" />
|
||||
<input className={inputCls} placeholder="Relationship" value={emergency.relationship} onChange={e => setEmergency({ ...emergency, relationship: e.target.value })} aria-label="Relationship" />
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
{info.collect.photo && (
|
||||
<fieldset>
|
||||
<legend className="text-sm font-medium text-gray-800 mb-1">May {info.attendeeName} appear in event photos and videos?</legend>
|
||||
<label className="inline-flex items-center gap-2 text-sm mr-4"><input type="radio" name="photo" checked={photoConsent === true} onChange={() => setPhotoConsent(true)} /> Yes</label>
|
||||
<label className="inline-flex items-center gap-2 text-sm"><input type="radio" name="photo" checked={photoConsent === false} onChange={() => setPhotoConsent(false)} /> No</label>
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
<div className="space-y-2 border-t pt-4">
|
||||
<label className="block text-sm font-medium text-gray-800">Type your full name to sign</label>
|
||||
<input className={inputCls} value={signedName} onChange={e => setSignedName(e.target.value)} aria-label="Your full name" />
|
||||
<label className="flex items-start gap-2 text-sm text-gray-700">
|
||||
<input type="checkbox" className="mt-0.5" checked={isGuardian} onChange={e => setIsGuardian(e.target.checked)} />
|
||||
<span>I am the parent or legal guardian of {info.attendeeName}.</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{error && <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||||
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button onClick={() => submit("give")} disabled={busy || !isGuardian || signedName.trim().length < 2} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{busy ? "Saving…" : "Give consent"}
|
||||
</button>
|
||||
<button onClick={() => submit("decline")} disabled={busy || !isGuardian || signedName.trim().length < 2} className="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 text-sm font-medium hover:bg-gray-50 disabled:opacity-50">
|
||||
Decline
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">We record your typed name, the time, and the device you used, together with the text above.</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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'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 => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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 & 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 & 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'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 & 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 "Re-request consent" 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 },
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
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";
|
||||
|
||||
// Tiered low-stock threshold — mirrors events/[id]/page.tsx
|
||||
function lowStockThreshold(stockLimit: number): number {
|
||||
@@ -42,6 +42,7 @@ type Event = {
|
||||
form?: { isRequired: boolean; fields?: any[] } | null;
|
||||
requiresAuth?: boolean;
|
||||
allowNamedAttendees?: boolean;
|
||||
requiresParentalConsent?: boolean;
|
||||
};
|
||||
|
||||
// Key format: "optionId" for no-variant options, "optionId:variantId" for variant options
|
||||
@@ -254,7 +255,8 @@ export default function RegisterForm({ event }: { event: Event }) {
|
||||
const [attendeeEntries, setAttendeeEntries] = useState<AttendeeEntries>({});
|
||||
const [delivery, setDelivery] = useState<TicketDelivery>("payer");
|
||||
const qtyFor = (optionId: string, variantId: string | null) => quantities[variantId ? `${optionId}:${variantId}` : optionId] || 0;
|
||||
const namedAttendees = () => (event.allowNamedAttendees && namingOthers
|
||||
const isYouthEvent = !!event.requiresParentalConsent;
|
||||
const namedAttendees = () => ((event.allowNamedAttendees && namingOthers) || isYouthEvent
|
||||
? attendeesPayload(event.eventOptions || [], qtyFor, attendeeEntries)
|
||||
: []);
|
||||
|
||||
@@ -327,6 +329,10 @@ export default function RegisterForm({ event }: { event: Event }) {
|
||||
setError("Select at least one ticket.");
|
||||
return;
|
||||
}
|
||||
if (isYouthEvent) {
|
||||
const missing = consentDetailsMissing(event.eventOptions || [], qtyFor, attendeeEntries, event.startDate);
|
||||
if (missing) { setError(missing); return; }
|
||||
}
|
||||
|
||||
if (isLoggedIn) {
|
||||
if (!token) {
|
||||
@@ -505,7 +511,7 @@ export default function RegisterForm({ event }: { event: Event }) {
|
||||
);
|
||||
})()}
|
||||
|
||||
{event.allowNamedAttendees && !eventSoldOut && (isLoggedIn || showGuestForm) && (
|
||||
{(event.allowNamedAttendees || isYouthEvent) && !eventSoldOut && (isLoggedIn || showGuestForm) && (
|
||||
<div className="mt-6">
|
||||
<AttendeeNamesEditor
|
||||
options={event.eventOptions || []}
|
||||
@@ -516,6 +522,7 @@ export default function RegisterForm({ event }: { event: Event }) {
|
||||
onEntriesChange={setAttendeeEntries}
|
||||
delivery={delivery}
|
||||
onDeliveryChange={setDelivery}
|
||||
consentEventStart={isYouthEvent ? event.startDate : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { TwoFactorChallenge, isTwoFactorChallenge } from "@/lib/auth";
|
||||
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";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||||
type EarlyBirdTier = { deadline: string; price: number; order?: number; variantId?: string | null };
|
||||
@@ -41,6 +41,7 @@ type KioskEvent = {
|
||||
eventOptions?: EventOption[];
|
||||
form?: EventForm | null;
|
||||
allowNamedAttendees?: boolean;
|
||||
requiresParentalConsent?: boolean;
|
||||
};
|
||||
|
||||
type Screen = "setup" | "form" | "eventform" | "confirmation";
|
||||
@@ -388,6 +389,10 @@ export default function SelfServicePage() {
|
||||
setFormError("The email and phone number entered belong to two different existing accounts. Please check and correct one of them before continuing.");
|
||||
return;
|
||||
}
|
||||
if (selectedEvent?.requiresParentalConsent) {
|
||||
const missing = consentDetailsMissing(selectedEvent.eventOptions || [], (o, v) => quantities[v ? `${o}::${v}` : o] || 0, attendeeEntries, selectedEvent.startDate);
|
||||
if (missing) { setFormError(missing); return; }
|
||||
}
|
||||
if (pendingChanges.length > 0) {
|
||||
setShowUpdateConfirm(true);
|
||||
return;
|
||||
@@ -417,7 +422,7 @@ export default function SelfServicePage() {
|
||||
notificationPreference: notificationPref,
|
||||
...(kioskCoupon ? { couponCode: kioskCoupon.code } : {}),
|
||||
};
|
||||
const kioskNames = selectedEvent?.allowNamedAttendees && namingOthers
|
||||
const kioskNames = (selectedEvent?.allowNamedAttendees && namingOthers) || selectedEvent?.requiresParentalConsent
|
||||
? attendeesPayload(selectedEvent.eventOptions || [], (o, v) => quantities[v ? `${o}::${v}` : o] || 0, attendeeEntries)
|
||||
: [];
|
||||
if (kioskNames.length > 0) {
|
||||
@@ -1008,7 +1013,7 @@ export default function SelfServicePage() {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{selectedEvent?.allowNamedAttendees && (
|
||||
{(selectedEvent?.allowNamedAttendees || selectedEvent?.requiresParentalConsent) && (
|
||||
<div className="mt-4">
|
||||
<AttendeeNamesEditor
|
||||
options={selectedEvent.eventOptions || []}
|
||||
@@ -1019,6 +1024,7 @@ export default function SelfServicePage() {
|
||||
onEntriesChange={setAttendeeEntries}
|
||||
delivery={delivery}
|
||||
onDeliveryChange={setDelivery}
|
||||
consentEventStart={selectedEvent.requiresParentalConsent ? selectedEvent.startDate : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
BarChart3,
|
||||
ClipboardList,
|
||||
TicketPercent,
|
||||
ShieldCheck,
|
||||
HeartPulse,
|
||||
} from "lucide-react";
|
||||
|
||||
export type ReportCategory = "Financial" | "Registration" | "Ticketing" | "Donations" | "Cashup" | "Other";
|
||||
@@ -34,6 +36,8 @@ export const REPORTS = [
|
||||
{ key: "financeReport", label: "Finance report (revenue & costs)", description: "Revenue & costs overview", category: "Financial", icon: FileBarChart, fields: 6 },
|
||||
{ key: "profitReport", label: "Profit report", description: "View profit report", category: "Financial", icon: BarChart3, fields: 5 },
|
||||
{ key: "cashupAudit", label: "Cashup audit trail", description: "Audit trail of cashup actions", category: "Cashup", icon: ClipboardList, fields: 6 },
|
||||
{ key: "consentStatus", label: "Parental consent status", description: "Youth events: consent per attendee", category: "Registration", icon: ShieldCheck, fields: 5 },
|
||||
{ key: "medicalList", label: "Medical & emergency list", description: "Youth events: confidential list for leaders (audited)", category: "Registration", icon: HeartPulse, fields: 5 },
|
||||
{ key: "discounts", label: "Discounts (coupon codes)", description: "Uses and value given away per code and event", category: "Financial", icon: TicketPercent, fields: 4 },
|
||||
] as const satisfies ReadonlyArray<{
|
||||
key: string;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch, API_BASE } from "@/lib/api";
|
||||
import { downloadReportExcel, emailReportPdf, whatsappReportPdf, viewReportPdf, type ReportPdfPayload } from "@/lib/export";
|
||||
import { Printer, Mail, FileSpreadsheet, MessageCircle, ShoppingCart, CreditCard, Gift, Clock, HandHeart, Search, TrendingUp, TicketPercent } from "lucide-react";
|
||||
import { Printer, Mail, FileSpreadsheet, MessageCircle, ShoppingCart, CreditCard, Gift, Clock, HandHeart, Search, TrendingUp, TicketPercent, ShieldCheck } from "lucide-react";
|
||||
import { REPORTS, type ReportKey } from "./ReportCatalog";
|
||||
import ReportsShell from "./ReportsShell";
|
||||
import ReportViewerModal, { ReportActionButton } from "./ReportViewerModal";
|
||||
@@ -174,6 +174,9 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
const [financialsByEvent, setFinancialsByEvent] = useState<Record<string, any>>({});
|
||||
const [auditRows, setAuditRows] = useState<any[]>([]);
|
||||
const [discountRows, setDiscountRows] = useState<any[]>([]);
|
||||
// Youth events (one row per attendee), each tagged with its event title.
|
||||
const [consentRows, setConsentRows] = useState<any[]>([]);
|
||||
const [medicalRows, setMedicalRows] = useState<any[]>([]);
|
||||
|
||||
// Deep-linking: dashboards link here with ?report=<key>&range=trailing_month to jump
|
||||
// straight into a specific report, pre-filtered to every currently-visible event and the
|
||||
@@ -296,6 +299,20 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
}
|
||||
};
|
||||
|
||||
const loadConsent = async (eventIds: string[], kind: "status" | "medical") => {
|
||||
if (!token) return [] as any[];
|
||||
const out: any[] = [];
|
||||
for (const id of eventIds) {
|
||||
const ev = filteredEvents.find((e: any) => e.id === id);
|
||||
if (!ev?.requiresParentalConsent) continue;
|
||||
try {
|
||||
const res = await apiFetch<any>(`/api/consent/events/${encodeURIComponent(id)}${kind === "medical" ? "/medical" : ""}`, { authToken: token });
|
||||
(res?.rows || []).forEach((r: any) => out.push({ ...r, eventTitle: ev.title }));
|
||||
} catch { /* not allowed or not found — skip */ }
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const loadCashupAudit = async (eventIds: string[]) => {
|
||||
if (!token) return [] as any[];
|
||||
const query = new URLSearchParams();
|
||||
@@ -390,6 +407,10 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
setAuditRows(rows);
|
||||
} else if (report === "discounts") {
|
||||
setDiscountRows(await loadDiscounts(selectedEventIds));
|
||||
} else if (report === "consentStatus") {
|
||||
setConsentRows(await loadConsent(selectedEventIds, "status"));
|
||||
} else if (report === "medicalList") {
|
||||
setMedicalRows(await loadConsent(selectedEventIds, "medical"));
|
||||
}
|
||||
setReady(true);
|
||||
} finally {
|
||||
@@ -963,6 +984,34 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
table: { columns: ["Event", "Donations (R)", "Used (R)", "Unused (R)", "Count"], rows }
|
||||
};
|
||||
}
|
||||
if (report === "consentStatus") {
|
||||
const minors = consentRows.filter(r => r.minor);
|
||||
const count = (s: string) => minors.filter(r => r.status === s).length;
|
||||
return {
|
||||
title: 'Parental consent status', subtitle, kind: 'table', orientation: 'landscape',
|
||||
stats: [
|
||||
{ label: 'Given', value: String(count('given')), tone: 'green' },
|
||||
{ label: 'Pending', value: String(count('pending')), tone: 'amber' },
|
||||
{ label: 'Declined / missing', value: String(count('declined') + count('missing')), tone: 'rose' },
|
||||
],
|
||||
note: 'Under-18 attendees on youth events. Pending, declined or missing consent blocks check-in.',
|
||||
table: {
|
||||
columns: ["Event", "Attendee", "Date of birth", "Parent / guardian", "Consent", "Answered"],
|
||||
rows: minors.map(r => [r.eventTitle, r.name, r.dateOfBirth ? new Date(r.dateOfBirth).toLocaleDateString() : '', [r.parentName, r.parentPhone].filter(Boolean).join(' · '), r.status + (r.request?.outdated ? ' (older text)' : ''), r.request?.respondedAt ? `${r.request.signedName || ''} ${new Date(r.request.respondedAt).toLocaleDateString()}`.trim() : '']),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (report === "medicalList") {
|
||||
const fmt = (m: any) => m ? [m.allergies && `Allergies: ${m.allergies}`, m.medication && `Medication: ${m.medication}`, m.conditions && `Conditions: ${m.conditions}`, m.medicalAid && `Medical aid: ${m.medicalAid}`].filter(Boolean).join('; ') : '';
|
||||
return {
|
||||
title: 'Medical & emergency list', subtitle, kind: 'table', orientation: 'landscape',
|
||||
note: 'CONFIDENTIAL — for event leaders only. Viewing this list is recorded in the audit log.',
|
||||
table: {
|
||||
columns: ["Event", "Attendee", "Medical", "Emergency contact", "Parent / guardian", "Photos"],
|
||||
rows: medicalRows.map(r => [r.eventTitle, r.name, r.purged ? 'Deleted after the event' : fmt(r.medical), r.emergency ? `${r.emergency.name} ${r.emergency.phone}${r.emergency.relationship ? ` (${r.emergency.relationship})` : ''}` : '', [r.parentName, r.parentPhone].filter(Boolean).join(' · '), r.photoConsent === null || r.photoConsent === undefined ? '' : r.photoConsent ? 'Yes' : 'No']),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (report === "discounts") {
|
||||
return {
|
||||
title: 'Discounts (coupon codes)', subtitle, kind: 'table', orientation: 'portrait',
|
||||
@@ -1168,6 +1217,8 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
profitReport: "Profit Report",
|
||||
cashupAudit: "Cashup Audit Trail",
|
||||
discounts: "Discounts Report",
|
||||
consentStatus: "Parental Consent Status",
|
||||
medicalList: "Medical & Emergency List",
|
||||
};
|
||||
|
||||
const doPrintPdf = async () => {
|
||||
@@ -1618,6 +1669,41 @@ export default function ReportsV2({ onBack }: { onBack?: () => void } = {}) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{(report === "consentStatus" || report === "medicalList") && (() => {
|
||||
const payload: any = buildReportPayload();
|
||||
const rows: any[] = payload?.table?.rows || [];
|
||||
const cols: string[] = payload?.table?.columns || [];
|
||||
return (
|
||||
<div>
|
||||
{report === "medicalList" && <div className="mb-3 text-sm text-red-700 font-medium">Confidential — for event leaders only. Viewing this list is recorded in the audit log.</div>}
|
||||
{payload?.stats && (
|
||||
<StatTileRow>
|
||||
{payload.stats.map((s: any) => <StatTile key={s.label} icon={ShieldCheck} label={s.label} value={s.value} tone={s.tone} />)}
|
||||
</StatTileRow>
|
||||
)}
|
||||
{rows.length === 0 ? (
|
||||
<div className="text-sm text-gray-500 mt-3">Nothing to show — pick youth events (ones that need parental consent) in the filters.</div>
|
||||
) : (
|
||||
<div className="mt-4 overflow-auto border border-gray-100 rounded-xl">
|
||||
<table className="min-w-[760px] w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-gray-500 text-xs uppercase tracking-wide bg-gray-50">
|
||||
{cols.map(c => <th key={c} className="py-2 px-3">{c}</th>)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={i} className="border-t border-gray-100 align-top">
|
||||
{r.map((cell: any, j: number) => <td key={j} className="py-2 px-3">{String(cell ?? '')}</td>)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
{report === "discounts" && (
|
||||
<div>
|
||||
{discountSummary.rows.length === 0 ? (
|
||||
|
||||
@@ -10,11 +10,28 @@ export type AttendeeOption = {
|
||||
variants?: { id: string; name: string }[] | null;
|
||||
};
|
||||
|
||||
export type AttendeeEntry = { name: string; email: string; phone: string };
|
||||
export type AttendeeEntry = {
|
||||
name: string; email: string; phone: string;
|
||||
dateOfBirth?: string; parentName?: string; parentEmail?: string; parentPhone?: string;
|
||||
};
|
||||
export type AttendeeEntries = Record<string, AttendeeEntry>;
|
||||
export type TicketDelivery = "payer" | "each";
|
||||
|
||||
export type AttendeePayload = { eventOptionId: string; variantId?: string | null; name: string; email?: string; phone?: string };
|
||||
export type AttendeePayload = {
|
||||
eventOptionId: string; variantId?: string | null; name: string; email?: string; phone?: string;
|
||||
dateOfBirth?: string; parentName?: string; parentEmail?: string; parentPhone?: string;
|
||||
};
|
||||
|
||||
/** Under 18 on the event's start date (mirrors backend utils/consent.js isMinor). */
|
||||
export function isMinorOn(dateOfBirth: string | undefined, eventStart: string | undefined): boolean {
|
||||
if (!dateOfBirth || !eventStart) return false;
|
||||
const dob = new Date(dateOfBirth);
|
||||
const on = new Date(eventStart);
|
||||
if (isNaN(dob.getTime()) || isNaN(on.getTime())) return false;
|
||||
let age = on.getUTCFullYear() - dob.getUTCFullYear();
|
||||
if (on.getUTCMonth() < dob.getUTCMonth() || (on.getUTCMonth() === dob.getUTCMonth() && on.getUTCDate() < dob.getUTCDate())) age -= 1;
|
||||
return age < 18;
|
||||
}
|
||||
|
||||
type Slot = { key: string; eventOptionId: string; variantId: string | null; label: string };
|
||||
|
||||
@@ -49,9 +66,29 @@ export function attendeesPayload(options: AttendeeOption[], qtyFor: (optionId: s
|
||||
name: e.name.trim(),
|
||||
...(e.email.trim() ? { email: e.email.trim() } : {}),
|
||||
...(e.phone.trim() ? { phone: e.phone.trim() } : {}),
|
||||
...(e.dateOfBirth ? { dateOfBirth: e.dateOfBirth } : {}),
|
||||
...(e.parentName?.trim() ? { parentName: e.parentName.trim() } : {}),
|
||||
...(e.parentEmail?.trim() ? { parentEmail: e.parentEmail.trim() } : {}),
|
||||
...(e.parentPhone?.trim() ? { parentPhone: e.parentPhone.trim() } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Youth events: what's still missing before registering (every place named with a date of
|
||||
* birth; parent details for minors). Empty when everything's in.
|
||||
*/
|
||||
export function consentDetailsMissing(options: AttendeeOption[], qtyFor: (optionId: string, variantId: string | null) => number, entries: AttendeeEntries, eventStart: string): string | null {
|
||||
for (const s of slotsFor(options, qtyFor)) {
|
||||
const e = entries[s.key];
|
||||
if (!e?.name.trim()) return `Add a name for ${s.label}.`;
|
||||
if (!e.dateOfBirth) return `Add a date of birth for ${e.name.trim()}.`;
|
||||
if (isMinorOn(e.dateOfBirth, eventStart) && (!e.parentName?.trim() || !e.parentEmail?.trim() || !e.parentPhone?.trim())) {
|
||||
return `${e.name.trim()} is under 18 — add a parent or guardian's name, email and phone.`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Registering for other people?" — a name (and optional email/phone) for each main
|
||||
* ticket place, plus who gets the tickets. Named places get their own ticket; any left
|
||||
@@ -67,6 +104,7 @@ export function AttendeeNamesEditor({
|
||||
delivery,
|
||||
onDeliveryChange,
|
||||
payerLabel = "me",
|
||||
consentEventStart,
|
||||
}: {
|
||||
options: AttendeeOption[];
|
||||
qtyFor: (optionId: string, variantId: string | null) => number;
|
||||
@@ -77,28 +115,40 @@ export function AttendeeNamesEditor({
|
||||
delivery: TicketDelivery;
|
||||
onDeliveryChange: (v: TicketDelivery) => void;
|
||||
payerLabel?: string;
|
||||
/** Set for youth events: names are required, with a date of birth, and parent details for minors. */
|
||||
consentEventStart?: string;
|
||||
}) {
|
||||
const consent = !!consentEventStart;
|
||||
const slots = slotsFor(options, qtyFor);
|
||||
const set = (key: string, field: keyof AttendeeEntry, value: string) => {
|
||||
const prev = entries[key] || { name: "", email: "", phone: "" };
|
||||
const prev: AttendeeEntry = entries[key] || { name: "", email: "", phone: "" };
|
||||
onEntriesChange({ ...entries, [key]: { ...prev, [field]: value } });
|
||||
};
|
||||
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
|
||||
|
||||
return (
|
||||
<div className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<label className="flex items-center gap-2 text-sm font-medium text-gray-800 cursor-pointer">
|
||||
<input type="checkbox" checked={enabled} onChange={e => onEnabledChange(e.target.checked)} />
|
||||
<Users className="w-4 h-4 text-brand-600" />
|
||||
Registering for other people?
|
||||
</label>
|
||||
{enabled && (
|
||||
{consent ? (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-sm font-medium text-gray-800">
|
||||
<Users className="w-4 h-4 text-brand-600" /> Who's coming?
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">This is a youth event: add each person's name and date of birth. For anyone under 18, a parent or guardian will be asked to give consent by email and WhatsApp before they can be checked in.</p>
|
||||
</div>
|
||||
) : (
|
||||
<label className="flex items-center gap-2 text-sm font-medium text-gray-800 cursor-pointer">
|
||||
<input type="checkbox" checked={enabled} onChange={e => onEnabledChange(e.target.checked)} />
|
||||
<Users className="w-4 h-4 text-brand-600" />
|
||||
Registering for other people?
|
||||
</label>
|
||||
)}
|
||||
{(enabled || consent) && (
|
||||
<div className="mt-3 space-y-3">
|
||||
{slots.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">Choose how many tickets first, then add a name for each person.</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-xs text-gray-500">Each named person gets their own ticket and their own attendee form. Leave a name blank to keep that ticket with the others.</p>
|
||||
{!consent && <p className="text-xs text-gray-500">Each named person gets their own ticket and their own attendee form. Leave a name blank to keep that ticket with the others.</p>}
|
||||
{slots.map(s => {
|
||||
const e = entries[s.key] || { name: "", email: "", phone: "" };
|
||||
return (
|
||||
@@ -109,6 +159,22 @@ export function AttendeeNamesEditor({
|
||||
<input type="email" className={inputCls} placeholder="Email (optional)" value={e.email} onChange={ev => set(s.key, "email", ev.target.value)} aria-label={`${s.label} email`} />
|
||||
<input type="tel" className={inputCls} placeholder="Phone (optional)" value={e.phone} onChange={ev => set(s.key, "phone", ev.target.value)} aria-label={`${s.label} phone`} />
|
||||
</div>
|
||||
{consent && (
|
||||
<div className="mt-2">
|
||||
<label className="block text-xs text-gray-600 mb-1">Date of birth</label>
|
||||
<input type="date" className={`${inputCls} sm:w-48`} value={e.dateOfBirth || ""} max={new Date().toISOString().slice(0, 10)} onChange={ev => set(s.key, "dateOfBirth", ev.target.value)} aria-label={`${s.label} date of birth`} />
|
||||
{isMinorOn(e.dateOfBirth, consentEventStart) && (
|
||||
<div className="mt-2 rounded-lg bg-amber-50 border border-amber-200 p-2">
|
||||
<div className="text-xs font-medium text-amber-900 mb-1">Parent or guardian (they'll be asked for consent)</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
<input className={inputCls} placeholder="Parent/guardian name" value={e.parentName || ""} onChange={ev => set(s.key, "parentName", ev.target.value)} aria-label={`${s.label} parent name`} />
|
||||
<input type="email" className={inputCls} placeholder="Parent email" value={e.parentEmail || ""} onChange={ev => set(s.key, "parentEmail", ev.target.value)} aria-label={`${s.label} parent email`} />
|
||||
<input type="tel" className={inputCls} placeholder="Parent phone" value={e.parentPhone || ""} onChange={ev => set(s.key, "parentPhone", ev.target.value)} aria-label={`${s.label} parent phone`} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -3,9 +3,24 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { Users, Send } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { isMinorOn } from "@/components/shared/AttendeeNamesEditor";
|
||||
|
||||
type Attendee = { id: string; eventOptionId: string; variantId: string | null; name: string; email: string | null; phone: string | null; ticket?: { id: string; isUsed: boolean } | null };
|
||||
type Row = { id?: string; eventOptionId: string; variantId: string | null; label: string; name: string; email: string; phone: string; locked: boolean };
|
||||
const CONSENT_LABEL: Record<string, { text: string; cls: string }> = {
|
||||
pending: { text: "consent pending", cls: "text-amber-700" },
|
||||
given: { text: "consent given", cls: "text-green-700" },
|
||||
declined: { text: "consent declined", cls: "text-red-700" },
|
||||
};
|
||||
|
||||
type Attendee = {
|
||||
id: string; eventOptionId: string; variantId: string | null; name: string; email: string | null; phone: string | null;
|
||||
dateOfBirth?: string | null; parentName?: string | null; parentEmail?: string | null; parentPhone?: string | null;
|
||||
ticket?: { id: string; isUsed: boolean } | null;
|
||||
consentRequests?: { id: string; status: "pending" | "given" | "declined" }[];
|
||||
};
|
||||
type Row = {
|
||||
id?: string; eventOptionId: string; variantId: string | null; label: string; name: string; email: string; phone: string; locked: boolean;
|
||||
dateOfBirth: string; parentName: string; parentEmail: string; parentPhone: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Named attendees on a registration (group tickets): shows who each main-ticket place
|
||||
@@ -21,6 +36,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
onMessage: (msg: string) => void;
|
||||
}) {
|
||||
const attendees: Attendee[] = registration.attendees || [];
|
||||
const youth = !!registration.event?.requiresParentalConsent;
|
||||
const eventStart: string | undefined = registration.event?.startDate;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [delivery, setDelivery] = useState<"payer" | "each">(registration.ticketDelivery || "payer");
|
||||
@@ -39,6 +56,8 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
out.push({
|
||||
id: a?.id, eventOptionId: ro.eventOptionId, variantId: ro.variantId || null, label: `${label} ${i + 1}`,
|
||||
name: a?.name || "", email: a?.email || "", phone: a?.phone || "",
|
||||
dateOfBirth: a?.dateOfBirth ? String(a.dateOfBirth).slice(0, 10) : "",
|
||||
parentName: a?.parentName || "", parentEmail: a?.parentEmail || "", parentPhone: a?.parentPhone || "",
|
||||
locked: !!a?.ticket?.isUsed,
|
||||
});
|
||||
}
|
||||
@@ -46,10 +65,11 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
return out;
|
||||
}, [registration, attendees]);
|
||||
|
||||
if (!registration.event?.allowNamedAttendees && attendees.length === 0) return null;
|
||||
if (!registration.event?.allowNamedAttendees && !youth && attendees.length === 0) return null;
|
||||
|
||||
const startEdit = () => { setRows(buildRows()); setDelivery(registration.ticketDelivery || "payer"); setError(null); setEditing(true); };
|
||||
const update = (i: number, field: "name" | "email" | "phone", value: string) => setRows(prev => prev.map((r, j) => (j === i ? { ...r, [field]: value } : r)));
|
||||
const update = (i: number, field: "name" | "email" | "phone" | "dateOfBirth" | "parentName" | "parentEmail" | "parentPhone", value: string) =>
|
||||
setRows(prev => prev.map((r, j) => (j === i ? { ...r, [field]: value } : r)));
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
@@ -67,6 +87,10 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
name: r.name.trim(),
|
||||
email: r.email.trim() || undefined,
|
||||
phone: r.phone.trim() || undefined,
|
||||
...(r.dateOfBirth ? { dateOfBirth: r.dateOfBirth } : {}),
|
||||
...(r.parentName.trim() ? { parentName: r.parentName.trim() } : {}),
|
||||
...(r.parentEmail.trim() ? { parentEmail: r.parentEmail.trim() } : {}),
|
||||
...(r.parentPhone.trim() ? { parentPhone: r.parentPhone.trim() } : {}),
|
||||
})),
|
||||
},
|
||||
});
|
||||
@@ -91,6 +115,15 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
|
||||
const answered = new Set((registration.formResponses || []).map((r: any) => r.attendeeId).filter(Boolean));
|
||||
|
||||
const resendConsent = async (requestId: string) => {
|
||||
try {
|
||||
const res = await apiFetch<{ message: string }>(`/api/consent/requests/${encodeURIComponent(requestId)}/resend`, { method: "POST", authToken: token });
|
||||
onMessage(res.message);
|
||||
} catch (e: any) {
|
||||
setError(e?.message || "Couldn't re-send the consent request");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="font-medium mb-1 flex items-center justify-between">
|
||||
@@ -112,7 +145,13 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
{a.name}
|
||||
{(a.email || a.phone) && <span className="text-xs text-gray-500"> · {[a.email, a.phone].filter(Boolean).join(" · ")}</span>}
|
||||
{hasForm && <span className={`ml-2 text-xs ${answered.has(a.id) ? "text-green-700" : "text-amber-700"}`}>{answered.has(a.id) ? "form done" : "form to do"}</span>}
|
||||
{youth && a.consentRequests?.[0] && (
|
||||
<span className={`ml-2 text-xs ${CONSENT_LABEL[a.consentRequests[0].status]?.cls}`}>{CONSENT_LABEL[a.consentRequests[0].status]?.text}</span>
|
||||
)}
|
||||
</span>
|
||||
{canEdit && youth && a.consentRequests?.[0]?.status === "pending" && (
|
||||
<button onClick={() => resendConsent(a.consentRequests![0].id)} className="text-xs text-brand-700 hover:underline shrink-0 inline-flex items-center gap-1"><Send className="w-3 h-3" /> Resend consent</button>
|
||||
)}
|
||||
{canEdit && hasForm && !answered.has(a.id) && (a.email || a.phone) && (
|
||||
<button onClick={() => sendLink(a)} className="text-xs text-brand-700 hover:underline shrink-0 inline-flex items-center gap-1"><Send className="w-3 h-3" /> Send form link</button>
|
||||
)}
|
||||
@@ -132,6 +171,18 @@ export function AttendeesPanel({ registration, token, canEdit, hasForm, onSaved,
|
||||
<input className="border rounded px-2 py-1 text-sm" placeholder="Email (optional)" value={r.email} disabled={r.locked} onChange={e => update(i, "email", e.target.value)} aria-label={`${r.label} email`} />
|
||||
<input className="border rounded px-2 py-1 text-sm" placeholder="Phone (optional)" value={r.phone} disabled={r.locked} onChange={e => update(i, "phone", e.target.value)} aria-label={`${r.label} phone`} />
|
||||
</div>
|
||||
{youth && (
|
||||
<div className="mt-1 space-y-1">
|
||||
<input type="date" className="border rounded px-2 py-1 text-sm" value={r.dateOfBirth} disabled={r.locked} onChange={e => update(i, "dateOfBirth", e.target.value)} aria-label={`${r.label} date of birth`} />
|
||||
{isMinorOn(r.dateOfBirth, eventStart) && (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||
<input className="border rounded px-2 py-1 text-sm" placeholder="Parent/guardian name" value={r.parentName} disabled={r.locked} onChange={e => update(i, "parentName", e.target.value)} aria-label={`${r.label} parent name`} />
|
||||
<input className="border rounded px-2 py-1 text-sm" placeholder="Parent email" value={r.parentEmail} disabled={r.locked} onChange={e => update(i, "parentEmail", e.target.value)} aria-label={`${r.label} parent email`} />
|
||||
<input className="border rounded px-2 py-1 text-sm" placeholder="Parent phone" value={r.parentPhone} disabled={r.locked} onChange={e => update(i, "parentPhone", e.target.value)} aria-label={`${r.label} parent phone`} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<div className="text-sm pt-1">
|
||||
|
||||
@@ -26,7 +26,7 @@ export const eventDetailHelpContent: HelpContent = {
|
||||
"N remaining" appears once stock runs low, and "Sold out" once an option is fully booked.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Users} title="Registering for other people?" tone="violet">
|
||||
Some events let you name each person you're booking for. Each named person gets their own ticket and their own attendee form, and you can choose to have every ticket sent to you or each person their own.
|
||||
Some events let you name each person you're booking for. Each named person gets their own ticket and their own attendee form, and you can choose to have every ticket sent to you or each person their own. On youth events, you'll give each person's date of birth; for anyone under 18, their parent or guardian is asked to give consent by email and WhatsApp before they can be checked in.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -22,6 +22,7 @@ import { supervisorAtTheDoorHelpContent } from "./supervisor-at-the-door";
|
||||
import { supervisorPaymentsHelpContent } from "./supervisor-payments";
|
||||
import { supervisorFormsHelpContent } from "./supervisor-forms";
|
||||
import { supervisorCouponsHelpContent } from "./supervisor-coupons";
|
||||
import { supervisorConsentHelpContent } from "./supervisor-consent";
|
||||
import { supervisorEmailAttendeesHelpContent } from "./supervisor-email-attendees";
|
||||
import { supervisorWhatsappAttendeesHelpContent } from "./supervisor-whatsapp-attendees";
|
||||
import { staffEventTicketsHelpContent } from "./staff-event-tickets";
|
||||
@@ -148,6 +149,11 @@ const REGISTRY: HelpRegistryEntry[] = [
|
||||
matches: pathname => pathname === "/dashboard/supervisor/payments",
|
||||
content: supervisorPaymentsHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "supervisor-consent",
|
||||
matches: pathname => pathname === "/dashboard/supervisor/consent",
|
||||
content: supervisorConsentHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "supervisor-coupons",
|
||||
matches: pathname => pathname === "/dashboard/supervisor/coupons",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from "react";
|
||||
import { QrCode, Filter, CheckCircle2 } from "lucide-react";
|
||||
import { QrCode, Filter, CheckCircle2, ShieldAlert } from "lucide-react";
|
||||
import { GuideItem } from "@/components/shared/GuideItem";
|
||||
import type { HelpContent } from "./types";
|
||||
|
||||
@@ -19,6 +19,9 @@ export const staffTicketScanningHelpContent: HelpContent = {
|
||||
<GuideItem icon={CheckCircle2} title="Outcomes" tone="green">
|
||||
You'll see Success (with redeemed/remaining counts), Already Used, or an Error if something's wrong with the ticket.
|
||||
</GuideItem>
|
||||
<GuideItem icon={ShieldAlert} title="Parental consent" tone="rose">
|
||||
On youth events, the confirm screen warns when a parent hasn't given consent yet (or declined). That person can't be checked in; a supervisor can override, and the override is recorded in the audit log.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import React from "react";
|
||||
import { ShieldCheck, Send, RefreshCw, HeartPulse, Ban, Clock, QrCode } from "lucide-react";
|
||||
import { GuideItem } from "@/components/shared/GuideItem";
|
||||
import type { HelpContent } from "./types";
|
||||
|
||||
/** Help content for /dashboard/supervisor/consent. */
|
||||
export const supervisorConsentHelpContent: HelpContent = {
|
||||
title: "Parental consent",
|
||||
subtitle: "Youth events: who still needs a parent's consent before check-in.",
|
||||
tabs: [
|
||||
{
|
||||
key: "how",
|
||||
label: "How it works",
|
||||
icon: ShieldCheck,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={ShieldCheck} title="Turning it on" tone="brand">
|
||||
In the event wizard's Visibility step, tick "Requires parental consent", write the consent text, and choose whether to ask for medical info, an emergency contact and photo consent.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Send} title="Requests" tone="green">
|
||||
Everyone registering gives a date of birth for each attendee. For anyone under 18 on the event's start date, the parent or guardian is sent a consent link by email and WhatsApp. They read the text, fill in any medical details, type their name to sign, and give or decline consent.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Clock} title="Reminders" tone="amber">
|
||||
Unanswered requests are reminded automatically 2 days later, then every 3 days until the event. Links stop working when the event ends.
|
||||
</GuideItem>
|
||||
<GuideItem icon={QrCode} title="At check-in" tone="rose">
|
||||
Tickets are sent as normal, but the scanner won't check someone in until consent is given. Supervisors can override, which is recorded in the audit log.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Ban} title="Declined" tone="gray">
|
||||
The registrant and the event's notification recipients are told. The registration stays, but can't be checked in — handle any refund from Payments.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "tools",
|
||||
label: "This page",
|
||||
icon: RefreshCw,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Send} title="Resend" tone="brand">
|
||||
Resend one request, or every pending one at once. Each resend issues a new link; old links stop working.
|
||||
</GuideItem>
|
||||
<GuideItem icon={RefreshCw} title="Re-request consent" tone="violet">
|
||||
If you change the consent text, parents who already agreed keep their record of the old version. "Re-request consent" asks them again on the new text, and also sends requests to under-18s who never got one (for example, names added later).
|
||||
</GuideItem>
|
||||
<GuideItem icon={HeartPulse} title="Medical & emergency list" tone="rose">
|
||||
A printable, confidential list for camp leaders, for attendees whose consent has been given. Every time it's opened is recorded in the audit log. Medical details are deleted a set number of days after the event (Site Settings → Legal).
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -44,7 +44,7 @@ export const supervisorEventsHelpContent: HelpContent = {
|
||||
Build a custom registration form — text, number, date, yes/no, statement, and heading fields, reorderable, optionally required before tickets are generated.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Eye} title="Visibility" tone="gray">
|
||||
Hide the event, allow guest (no-account) registration, turn on named attendees (group tickets — each named person gets their own ticket and form), or toggle it active.
|
||||
Hide the event, allow guest (no-account) registration, turn on named attendees (group tickets — each named person gets their own ticket and form), make it a youth event that needs parental consent for under-18s, or toggle it active.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Bell} title="Notifications" tone="blue">
|
||||
Choose which staff get registration, payment, and daily-summary emails for this event.
|
||||
|
||||
Reference in New Issue
Block a user