POPIA toolkit part 1: privacy page, unsubscribe, WhatsApp STOP, data requests

- Privacy page: news opt-in per channel with history, download my data
  (JSON + PDF), correction and deletion requests
- Bulk messages are an Event update or News & announcements; news only
  reaches people who opted in, with unsubscribe links, one-click
  List-Unsubscribe headers and "Reply STOP" on WhatsApp
- WhatsApp STOP via WAWP's message webhook, checked against a secret in
  the webhook URL
- Sign-up opt-in box; existing accounts kept opted in and asked once
- Admin -> Data requests with 30-day due dates and a daily reminder job
- Deleting an account is a request; anonymising now covers attendees,
  form answers, consent details, payer details in provider payloads, etc.
- Unit tests (privacy.test.js) and e2e (privacy.spec.ts); docs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
This commit is contained in:
2026-10-23 18:13:47 +02:00
co-authored by Claude Opus 5.5
parent be5ad620da
commit 594cb35a85
47 changed files with 2871 additions and 143 deletions
@@ -40,6 +40,9 @@ const ACTIONS = [
"yoco_config_updated",
"yoco_webhook_registered",
"yoco_webhook_deleted",
"data_request_completed",
"data_request_rejected",
"user_anonymised",
] as const;
const ACTION_LABELS: Record<string, string> = {
@@ -72,6 +75,9 @@ const ACTION_LABELS: Record<string, string> = {
yoco_config_updated: "Yoco settings changed",
yoco_webhook_registered: "Yoco webhook registered",
yoco_webhook_deleted: "Yoco webhook deleted",
data_request_completed: "Privacy request completed",
data_request_rejected: "Privacy request rejected/cancelled",
user_anonymised: "User's personal data deleted",
};
interface AuditLogEntry {
@@ -0,0 +1,201 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Inbox, AlertTriangle } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
type RequestType = "access" | "correction" | "deletion";
type RequestStatus = "open" | "completed" | "rejected" | "cancelled";
type Blocker = { registrationId: string; status: string; eventId: string; eventTitle: string; endDate: string };
type DataRequest = {
id: string; type: RequestType; status: RequestStatus; name: string; email: string; details: string | null; response: string | null;
dueAt: string; closedAt: string | null; createdAt: string; userId: string | null; handledBy: string | null; overdue: boolean; blockers: Blocker[];
};
type Msg = { type: "ok" | "err"; text: string } | null;
const TYPE_LABEL: Record<RequestType, string> = { access: "Access", correction: "Correction", deletion: "Delete account" };
const STATUS_TONE: Record<RequestStatus, string> = {
open: "bg-amber-50 text-amber-700",
completed: "bg-green-50 text-green-700",
rejected: "bg-red-50 text-red-700",
cancelled: "bg-gray-100 text-gray-600",
};
const fmtDate = (d: string) => new Date(d).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });
/** One open request with its actions: complete (deletion: anonymise), reject or cancel. */
function OpenRequest({ request, token, onDone }: { request: DataRequest; token: string; onDone: (msg: Msg) => void }) {
const [mode, setMode] = useState<"idle" | "complete" | "reject">("idle");
const [response, setResponse] = useState("");
const [cancelled, setCancelled] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const isDeletion = request.type === "deletion";
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (mode === "complete" && isDeletion && !confirm(`Delete ${request.name}'s personal information? This can't be undone.`)) return;
setBusy(true);
setError(null);
try {
await apiFetch(`/api/privacy/requests/${request.id}/${mode}`, {
method: "POST",
authToken: token,
body: { response: response || undefined, cancelled: mode === "reject" ? cancelled : undefined },
});
onDone({ type: "ok", text: mode === "complete" ? (isDeletion ? `${request.name}'s personal information was deleted.` : "Request completed.") : "Request closed." });
} catch (e) {
setError(errorMessage(e) || "Something went wrong.");
} finally {
setBusy(false);
}
};
return (
<li className={`border rounded-xl p-4 bg-white shadow-sm ${request.overdue ? "border-red-300" : ""}`}>
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold text-gray-900">{TYPE_LABEL[request.type]}</span>
<span className="text-sm text-gray-700">— {request.name}</span>
<a href={`mailto:${request.email}`} className="text-sm text-brand-600 hover:underline">{request.email}</a>
<span className={`ml-auto text-xs px-2 py-0.5 rounded-full ${request.overdue ? "bg-red-50 text-red-700" : "bg-gray-100 text-gray-600"}`}>
{request.overdue ? "Overdue — was due " : "Due "}{fmtDate(request.dueAt)}
</span>
</div>
<p className="text-xs text-gray-400 mt-1">Received {fmtDate(request.createdAt)}</p>
{request.details && <p className="text-sm text-gray-700 mt-2 whitespace-pre-line">{request.details}</p>}
{isDeletion && (
request.blockers.length > 0 ? (
<div className="mt-3 p-3 rounded-lg bg-amber-50 border border-amber-200 text-sm text-amber-900">
<div className="flex items-center gap-2 font-medium"><AlertTriangle className="w-4 h-4" /> Waiting on registrations for upcoming events</div>
<ul className="mt-1 list-disc pl-5">
{request.blockers.map(b => (
<li key={b.registrationId}>{b.eventTitle} ({b.status}, ends {fmtDate(b.endDate)})</li>
))}
</ul>
<p className="mt-1 text-xs">
Cancel (and refund where needed) on <Link href="/dashboard/admin/registrations" className="text-brand-600 hover:underline">Registrations</Link> —
search for {request.email} — or wait until the event is over. The account is already closed.
</p>
</div>
) : (
<p className="mt-2 text-xs text-gray-500">The account is closed. Completing deletes their name, contact details, attendees, form answers and payer details; payments and registrations stay as &quot;Deleted User&quot;.</p>
)
)}
{mode === "idle" ? (
<div className="flex flex-wrap gap-2 mt-3">
<button onClick={() => setMode("complete")} disabled={isDeletion && request.blockers.length > 0} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{isDeletion ? "Delete personal data…" : "Mark as done…"}
</button>
<button onClick={() => setMode("reject")} className="px-3 py-1.5 rounded-lg border border-gray-300 text-gray-700 text-sm font-medium hover:bg-gray-50">
Reject or cancel…
</button>
</div>
) : (
<form onSubmit={submit} className="mt-3 space-y-3">
<label className="block text-sm font-medium text-gray-700">
{mode === "reject" ? "Reason (emailed to them)" : request.type === "correction" ? "What was corrected (emailed to them)" : "Message to them (optional)"}
</label>
<textarea
className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
rows={3}
maxLength={5000}
value={response}
onChange={e => setResponse(e.target.value)}
required={mode === "reject" || request.type === "correction"}
/>
{mode === "reject" && (
<label className="flex items-center gap-2 text-sm text-gray-700">
<input type="checkbox" className="h-4 w-4 accent-brand-600" checked={cancelled} onChange={e => setCancelled(e.target.checked)} />
They withdrew it (cancelled, not rejected)
</label>
)}
{mode === "reject" && isDeletion && <p className="text-xs text-gray-500">Their account is opened again so they can log in.</p>}
<div className="flex gap-2">
<button type="button" onClick={() => { setMode("idle"); setResponse(""); setError(null); }} className="px-3 py-1.5 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Back</button>
<button type="submit" disabled={busy} className={`px-3 py-1.5 rounded-lg text-white text-sm font-medium disabled:opacity-50 ${mode === "complete" && isDeletion ? "bg-red-600 hover:bg-red-700" : "bg-brand-600 hover:bg-brand-700"}`}>
{busy ? "Saving…" : mode === "complete" ? (isDeletion ? "Delete personal data" : "Complete") : cancelled ? "Cancel request" : "Reject request"}
</button>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
</form>
)}
</li>
);
}
export default function DataRequestsPage() {
const { token } = useAuth();
const [view, setView] = useState<"open" | "closed">("open");
const [requests, setRequests] = useState<DataRequest[] | null>(null);
const [openCount, setOpenCount] = useState(0);
const [msg, setMsg] = useDismissingState<Msg>(null);
const load = useCallback(async () => {
if (!token) return;
try {
const res = await apiFetch<{ requests: DataRequest[]; openCount: number }>(`/api/privacy/requests?status=${view}`, { authToken: token });
setRequests(res.requests);
setOpenCount(res.openCount);
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load requests." });
}
}, [token, view, setMsg]);
useEffect(() => { setRequests(null); load(); }, [load]);
return (
<div className="max-w-4xl mx-auto w-full">
<div className="mb-6">
<BackLink href="/dashboard/admin" />
<div className="flex items-center gap-2 mt-0.5">
<Inbox className="w-6 h-6 text-brand-600" />
<h1 className="text-2xl font-semibold text-gray-900">Data requests</h1>
</div>
<p className="text-sm text-gray-500 mt-1">
POPIA requests from people about their personal information. Answer within 30 days. Downloads people make
themselves from their Privacy page aren&apos;t listed here.
</p>
</div>
<div className="flex gap-2 mb-4">
{(["open", "closed"] as const).map(v => (
<button key={v} onClick={() => setView(v)} className={`px-3 py-1.5 rounded-lg text-sm font-medium ${view === v ? "bg-brand-600 text-white" : "bg-white border text-gray-700 hover:bg-gray-50"}`}>
{v === "open" ? `Open${openCount ? ` (${openCount})` : ""}` : "Closed"}
</button>
))}
</div>
{msg && <div className={`mb-4 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
{requests === null ? (
<p className="text-sm text-gray-400">Loading…</p>
) : requests.length === 0 ? (
<p className="text-sm text-gray-500">{view === "open" ? "No open requests." : "No closed requests yet."}</p>
) : view === "open" ? (
<ul className="space-y-3">
{requests.map(r => <OpenRequest key={r.id} request={r} token={token!} onDone={m => { setMsg(m); load(); }} />)}
</ul>
) : (
<ul className="space-y-2">
{requests.map(r => (
<li key={r.id} className="border rounded-xl p-3 bg-white text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium text-gray-900">{TYPE_LABEL[r.type]}</span>
<span className="text-gray-700">— {r.name}</span>
<span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_TONE[r.status]}`}>{r.status}</span>
<span className="ml-auto text-xs text-gray-400">{r.closedAt ? `Closed ${fmtDate(r.closedAt)}` : ""}{r.handledBy ? ` by ${r.handledBy}` : ""}</span>
</div>
{r.response && <p className="text-gray-600 mt-1 whitespace-pre-line">{r.response}</p>}
</li>
))}
</ul>
)}
</div>
);
}
+2 -1
View File
@@ -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, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck, Inbox,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -42,6 +42,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/whatsapp-attendees", label: "WhatsApp attendees", description: "Send a WhatsApp message to event attendees", icon: MessageCircle },
{ href: "/dashboard/admin/cashup", label: "Post-event Cashup", description: "Set costs, reconcile takings, and close out events", icon: Wallet },
{ href: "/dashboard/admin/audit-log", label: "Audit log", description: "Review refunds, manual registrations, event and settings changes", icon: History },
{ href: "/dashboard/admin/data-requests", label: "Data requests", description: "POPIA: people asking to correct or delete their information", icon: Inbox },
] as const;
type OverviewMetric = { thisMonth: number; lastMonth: number; pctChange: number | null };
@@ -746,6 +746,8 @@ interface ConfigResponse {
hasToken: boolean;
hasInstance: boolean;
configured: boolean;
// Where WAWP should send events; carries the secret incoming messages are checked against.
webhookUrl?: string;
}
interface StatusResponse {
@@ -1182,6 +1184,22 @@ function WhatsAppTab({ active }: { active: boolean }) {
</section>
)}
{cfg?.webhookUrl && (
<section className="border rounded-xl p-5 bg-gray-50 space-y-3">
<h3 className="text-base font-semibold">Webhook (STOP replies)</h3>
<p className="text-sm text-gray-600">
So people can reply <strong>STOP</strong> to stop news on WhatsApp: in the WAWP dashboard, click <em>Webhook</em> on
your instance, paste this URL and tick the <code>message</code> and <code>session.status</code> events. Keep it
private — the secret at the end is what proves a message came from WAWP.
</p>
<div className="flex gap-2">
<input readOnly value={cfg.webhookUrl} className="flex-1 min-w-0 border rounded-lg px-3 py-2 text-xs font-mono bg-white" onFocus={e => e.target.select()} />
<button type="button" className="px-3 py-2 rounded-lg border text-sm bg-white hover:bg-gray-50" onClick={() => navigator.clipboard?.writeText(cfg.webhookUrl || "")}>Copy</button>
</div>
<p className="text-xs text-gray-500">The URL must be reachable from the internet over HTTPS (set <code>BACKEND_URL</code> on the server).</p>
</section>
)}
<section className="border rounded-xl p-5 bg-gray-50 space-y-4">
<h3 className="text-base font-semibold">Session Controls</h3>
<div className="flex flex-wrap gap-3">
+4
View File
@@ -6,6 +6,7 @@ import { usePathname, useRouter } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { Sidebar, MobileSidebar } from "@/components/layout/Sidebar";
import { NewsPrompt } from "@/components/shared/NewsPrompt";
// The sidebar shows only on these exact routes — each role's dashboard root,
// plus Profile & Security and Site Settings (matching the redesign
@@ -17,6 +18,7 @@ const SIDEBAR_ROUTES = [
"/dashboard/staff",
"/dashboard/user",
"/dashboard/user/profile",
"/dashboard/user/privacy",
"/dashboard/admin/settings",
];
@@ -85,6 +87,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
return (
<div className="h-screen flex flex-col overflow-hidden">
<Navbar />
<NewsPrompt />
<MobileSidebar />
<div className="flex-1 flex min-h-0">
<Sidebar />
@@ -100,6 +103,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<NewsPrompt />
<main className="flex-1 p-6 bg-gray-50">{children}</main>
<Footer />
</div>
@@ -10,6 +10,7 @@ import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter
import { errorMessage } from "@/lib/utils";
import type { Event, MessageSendResult, Registration, User } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { MessageKindPicker, matchedText, type MessageKind } from "@/components/shared/MessageKindPicker";
type Attendee = { id: string; name: string; email: string; pref: string };
type TemplateKey = 'custom'|'payment_reminder'|'event_reminder'|'tickets';
@@ -243,6 +244,7 @@ function EmailAttendeesPageInner() {
}, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<TemplateKey>('custom');
const [messageKind, setMessageKind] = useState<MessageKind>('update');
const [showInfo, setShowInfo] = useState(false);
// Broadcasts state
@@ -256,7 +258,9 @@ function EmailAttendeesPageInner() {
const [broadcastPreviewCount, setBroadcastPreviewCount] = useState<number|null>(null);
const [broadcastPreviewSample, setBroadcastPreviewSample] = useState<{email:string;name?:string}[]|null>(null);
const [broadcastScheduledAtLocal, setBroadcastScheduledAtLocal] = useState<string>("");
const [broadcastKind, setBroadcastKind] = useState<MessageKind>('news');
const resetBroadcastForm = () => {
setBroadcastKind('news');
setSelectedUserIds([]);
setBroadcastEventId("");
setBroadcastSubject("");
@@ -423,11 +427,12 @@ function EmailAttendeesPageInner() {
if (!subject.trim()) { setError("Subject is required"); return; }
if (!body.trim()) { setError("Message is required"); return; }
}
const payload: { subject: string; filter: MessageFilter; dryRun: boolean; template: TemplateKey } & EmailContent = {
const payload: { subject: string; filter: MessageFilter; dryRun: boolean; template: TemplateKey; kind: MessageKind } & EmailContent = {
subject: subject || "(no subject)",
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
dryRun: true,
template: templateKey,
kind: messageKind,
};
if (templateKey !== 'tickets') {
if (body.trim().startsWith('<')) payload.html = body; else payload.text = body;
@@ -435,7 +440,7 @@ function EmailAttendeesPageInner() {
const res = await apiFetch<EmailSendResult>(`/api/events/${encodeURIComponent(eventId)}/email-attendees`, { method: 'POST', authToken: token, body: payload });
setPreviewCount(res?.matched ?? 0);
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
setInfo(matchedText(res));
} catch (e) {
setError(errorMessage(e) || 'Failed to preview recipients');
}
@@ -443,6 +448,7 @@ function EmailAttendeesPageInner() {
const resetAttendeesForm = () => {
setTemplateKey('custom');
setMessageKind('update');
setSubject(''); setBody('');
setSubjectDirty(false); setBodyDirty(false);
setStatus('any');
@@ -463,10 +469,11 @@ function EmailAttendeesPageInner() {
if (!body.trim()) { setError("Message is required"); return; }
}
setSending(true);
const payload: { subject: string; filter: MessageFilter; template: TemplateKey } & EmailContent = {
const payload: { subject: string; filter: MessageFilter; template: TemplateKey; kind: MessageKind } & EmailContent = {
subject,
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
kind: messageKind,
};
if (templateKey !== 'tickets') {
if (body.trim().startsWith('<')) payload.html = body; else payload.text = body.replace(/\n/g, '\n');
@@ -571,6 +578,10 @@ function EmailAttendeesPageInner() {
</div>
</div>
{templateKey !== 'tickets' && (
<MessageKindPicker name="attendeesKind" value={messageKind} onChange={setMessageKind} />
)}
{showInfo && (
<div className="fixed inset-0 z-20">
<div className="absolute inset-0 bg-black/30" onClick={() => setShowInfo(false)} />
@@ -663,10 +674,11 @@ function EmailAttendeesPageInner() {
if (!body.trim()) { setError('Message is required'); return; }
}
const whenIso = new Date(scheduledAtLocal).toISOString();
const payload: { subject: string; filter: MessageFilter; template: TemplateKey; scheduledAt: string } & EmailContent = {
const payload: { subject: string; filter: MessageFilter; template: TemplateKey; kind: MessageKind; scheduledAt: string } & EmailContent = {
subject,
filter: { status: status !== 'any' ? status : undefined, attendeeIds: selectedAttendeeIds && selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
kind: messageKind,
scheduledAt: whenIso,
};
if (templateKey !== 'tickets') {
@@ -739,6 +751,8 @@ function EmailAttendeesPageInner() {
<PrefWarning attendees={users} selectedIds={selectedUserIds} channel="email" />
)}
<MessageKindPicker name="broadcastKind" value={broadcastKind} onChange={setBroadcastKind} />
<div>
<div className="flex items-center justify-between">
<label className="block text-xs text-gray-600 mb-1">Subject</label>
@@ -782,11 +796,11 @@ Jane Doe <jane@example.com>
if (!token) { setError('Not authenticated'); return; }
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const body = { userIds: selectedUserIds, emails: broadcastEmails, eventId: broadcastEventId || undefined };
const body = { userIds: selectedUserIds, emails: broadcastEmails, eventId: broadcastEventId || undefined, kind: broadcastKind };
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/preview`, { method: 'POST', authToken: token, body });
setBroadcastPreviewCount(res?.matched ?? 0);
setBroadcastPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
setInfo(matchedText(res));
} catch (e) {
setError(errorMessage(e) || 'Failed to preview recipients');
}
@@ -798,10 +812,10 @@ Jane Doe <jane@example.com>
if (!token) { setError('Not authenticated'); return; }
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const payload: { subject: string; eventId?: string; userIds: string[]; emails: string } & EmailContent = { subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
const payload: { subject: string; eventId?: string; userIds: string[]; emails: string; kind: MessageKind } & EmailContent = { subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails, kind: broadcastKind };
if (broadcastBody.trim().startsWith('<')) payload.html = broadcastBody; else payload.text = broadcastBody;
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/send`, { method: 'POST', authToken: token, body: payload });
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).`);
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).${res?.skipped ? ` ${res.skipped} skipped — not opted in to news or unsubscribed.` : ''}`);
// Reset broadcast form
resetBroadcastForm();
} catch (e) {
@@ -816,7 +830,7 @@ Jane Doe <jane@example.com>
if (!broadcastSubject.trim()) { setError('Subject is required'); return; }
if (!broadcastBody.trim()) { setError('Message is required'); return; }
const whenIso = new Date(broadcastScheduledAtLocal).toISOString();
const payload: { scheduledAt: string; subject: string; eventId?: string; userIds: string[]; emails: string } & EmailContent = { scheduledAt: whenIso, subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails };
const payload: { scheduledAt: string; subject: string; eventId?: string; userIds: string[]; emails: string; kind: MessageKind } & EmailContent = { scheduledAt: whenIso, subject: broadcastSubject, eventId: broadcastEventId || undefined, userIds: selectedUserIds, emails: broadcastEmails, kind: broadcastKind };
if (broadcastBody.trim().startsWith('<')) payload.html = broadcastBody; else payload.text = broadcastBody;
const res = await apiFetch<EmailSendResult>(`/api/broadcasts/schedule`, { method: 'POST', authToken: token, body: payload });
if (res?.job?.id) setInfo('Broadcast scheduled. It will be sent around the specified time.'); else setInfo('Scheduled.');
@@ -10,6 +10,7 @@ import { AllocationGroupFilter } from "@/components/shared/AllocationGroupFilter
import { errorMessage } from "@/lib/utils";
import type { Event, MessageSendResult, Registration, User } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { MessageKindPicker, matchedText, type MessageKind } from "@/components/shared/MessageKindPicker";
// Attendee with preference info
type Attendee = { id: string; name: string; phone: string; pref: string };
@@ -404,6 +405,7 @@ function WhatsAppAttendeesPageInner() {
const [eventId, setEventId] = useState<string>(preselectEventId);
useEffect(() => { if (preselectEventId) setEventId(preselectEventId); }, [preselectEventId]);
const [templateKey, setTemplateKey] = useState<TemplateKey>("custom");
const [messageKind, setMessageKind] = useState<MessageKind>("update");
const [message, setMessage] = useState("");
// Set once the supervisor edits the message, so picking a template doesn't overwrite it.
// A ref, not state: it only gates the template effect below and is never rendered.
@@ -456,9 +458,10 @@ function WhatsAppAttendeesPageInner() {
}, [eventId, token]);
const buildPayload = (dryRun?: boolean) => {
const payload: { filter: MessageFilter; template: TemplateKey; dryRun?: boolean; message?: string } = {
const payload: { filter: MessageFilter; template: TemplateKey; kind: MessageKind; dryRun?: boolean; message?: string } = {
filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey,
kind: messageKind,
dryRun: dryRun || undefined,
};
if (templateKey !== "tickets") payload.message = message;
@@ -474,12 +477,12 @@ function WhatsAppAttendeesPageInner() {
const res = await apiFetch<MessageSendResult>(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees`, { method: "POST", authToken: token, body: buildPayload(true) });
setPreviewCount(res?.matched ?? 0);
setPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s) with a phone number.`);
setInfo(matchedText(res));
} catch (e) { setError(errorMessage(e) || "Failed to preview"); }
};
const resetAttendeesForm = () => {
setTemplateKey("custom"); setMessage(""); messageDirtyRef.current = false;
setTemplateKey("custom"); setMessageKind("update"); setMessage(""); messageDirtyRef.current = false;
setStatus("any"); setScheduledAtLocal(""); setPreviewCount(null); setPreviewSample(null);
setSelectedAttendeeIds(attendees.map((a) => a.id));
};
@@ -505,10 +508,10 @@ function WhatsAppAttendeesPageInner() {
if (templateKey !== "tickets" && !message.trim()) { setError("Message is required"); return; }
if (!scheduledAtLocal) { setError("Scheduled time is required"); return; }
const whenIso = new Date(scheduledAtLocal).toISOString();
const payload: { message?: string; filter: MessageFilter; template: TemplateKey; scheduledAt: string } = {
const payload: { message?: string; filter: MessageFilter; template: TemplateKey; kind: MessageKind; scheduledAt: string } = {
message: message || undefined,
filter: { status: status !== "any" ? status : undefined, attendeeIds: selectedAttendeeIds.length ? selectedAttendeeIds : undefined, allocationGroupId: groupId || undefined },
template: templateKey, scheduledAt: whenIso,
template: templateKey, kind: messageKind, scheduledAt: whenIso,
};
const res = await apiFetch<MessageSendResult>(`/api/events/${encodeURIComponent(eventId)}/whatsapp-attendees/schedule`, { method: "POST", authToken: token, body: payload });
setInfo(res?.job?.id ? "WhatsApp scheduled. It will be sent around the specified time." : "Scheduled.");
@@ -526,6 +529,7 @@ function WhatsAppAttendeesPageInner() {
const [broadcastPreviewCount, setBroadcastPreviewCount] = useState<number | null>(null);
const [broadcastPreviewSample, setBroadcastPreviewSample] = useState<{ phone: string; name?: string }[] | null>(null);
const [broadcastScheduledAtLocal, setBroadcastScheduledAtLocal] = useState<string>("");
const [broadcastKind, setBroadcastKind] = useState<MessageKind>("news");
useEffect(() => {
const run = async () => {
@@ -546,7 +550,7 @@ function WhatsAppAttendeesPageInner() {
const resetBroadcastForm = () => {
setSelectedUserIds([]); setBroadcastEventId(""); setBroadcastMessage("");
setBroadcastPhones(""); setBroadcastPreviewCount(null); setBroadcastPreviewSample(null);
setBroadcastScheduledAtLocal("");
setBroadcastScheduledAtLocal(""); setBroadcastKind("news");
};
// ── Scheduled tab ──────────────────────────────────────────────────────────
@@ -683,6 +687,10 @@ function WhatsAppAttendeesPageInner() {
</div>
</div>
{templateKey !== "tickets" && (
<MessageKindPicker name="waAttendeesKind" value={messageKind} onChange={setMessageKind} />
)}
{showInfo && (
<div className="fixed inset-0 z-20">
<div className="absolute inset-0 bg-black/30" onClick={() => setShowInfo(false)} />
@@ -817,6 +825,8 @@ function WhatsAppAttendeesPageInner() {
<PrefWarning attendees={users} selectedIds={selectedUserIds} channel="whatsapp" />
)}
<MessageKindPicker name="waBroadcastKind" value={broadcastKind} onChange={setBroadcastKind} />
<div>
<label className="block text-xs text-gray-600 mb-1">Message</label>
<textarea className="w-full border rounded px-3 py-2 text-sm" rows={8} value={broadcastMessage}
@@ -843,10 +853,10 @@ function WhatsAppAttendeesPageInner() {
try {
setError(null); setInfo(null); setBroadcastPreviewCount(null); setBroadcastPreviewSample(null);
if (!token) { setError("Not authenticated"); return; }
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/preview`, { method: "POST", authToken: token, body: { userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/preview`, { method: "POST", authToken: token, body: { userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined, kind: broadcastKind } });
setBroadcastPreviewCount(res?.matched ?? 0);
setBroadcastPreviewSample(Array.isArray(res?.recipients) ? res.recipients : null);
setInfo(`Matched ${res?.matched ?? 0} recipient(s).`);
setInfo(matchedText(res));
} catch (e) { setError(errorMessage(e) || "Failed to preview"); }
}}>Preview recipients</button>
@@ -855,8 +865,8 @@ function WhatsAppAttendeesPageInner() {
setError(null); setInfo(null);
if (!token) { setError("Not authenticated"); return; }
if (!broadcastMessage.trim()) { setError("Message is required"); return; }
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/send`, { method: "POST", authToken: token, body: { message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).`);
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/send`, { method: "POST", authToken: token, body: { message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined, kind: broadcastKind } });
setInfo(`Sent ${res?.sent ?? 0} out of ${res?.matched ?? 0} recipient(s).${res?.skipped ? ` ${res.skipped} skipped — not opted in to news or unsubscribed.` : ""}`);
resetBroadcastForm();
} catch (e) { setError(errorMessage(e) || "Failed to send"); }
}}>Send now</button>
@@ -867,7 +877,7 @@ function WhatsAppAttendeesPageInner() {
if (!token) { setError("Not authenticated"); return; }
if (!broadcastMessage.trim()) { setError("Message is required"); return; }
const whenIso = new Date(broadcastScheduledAtLocal).toISOString();
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/schedule`, { method: "POST", authToken: token, body: { scheduledAt: whenIso, message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined } });
const res = await apiFetch<MessageSendResult>(`/api/whatsapp-broadcasts/schedule`, { method: "POST", authToken: token, body: { scheduledAt: whenIso, message: broadcastMessage, userIds: selectedUserIds, phones: broadcastPhones, eventId: broadcastEventId || undefined, kind: broadcastKind } });
if (res?.job?.id) setInfo("WhatsApp broadcast scheduled."); else setInfo("Scheduled.");
resetBroadcastForm();
} catch (e) { setError(errorMessage(e) || "Failed to schedule broadcast"); }
@@ -0,0 +1,342 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, API_BASE } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Megaphone, Download, PencilLine, Trash2, ListChecks, type LucideIcon } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
type RequestType = "access" | "correction" | "deletion";
type RequestStatus = "open" | "completed" | "rejected" | "cancelled";
type DataRequest = { id: string; type: RequestType; status: RequestStatus; details: string | null; response: string | null; createdAt: string; closedAt: string | null };
type ConsentEntry = { id: string; channel: "email" | "whatsapp"; granted: boolean; source: string; createdAt: string };
type PrivacyInfo = {
news: { email: boolean; whatsapp: boolean };
canWhatsApp: boolean;
notificationPreference: "email" | "whatsapp" | "both";
history: ConsentEntry[];
requests: DataRequest[];
};
type Msg = { type: "ok" | "err"; text: string } | null;
const SOURCE_LABEL: Record<string, string> = {
signup: "when you signed up",
privacy_centre: "in your privacy settings",
prompt: "when we asked after logging in",
unsubscribe_link: "with an unsubscribe link",
whatsapp_stop: "by replying STOP on WhatsApp",
existing_account: "your account existed before we asked",
admin: "by an administrator",
};
const TYPE_LABEL: Record<RequestType, string> = { access: "Access", correction: "Correction", deletion: "Account deletion" };
const STATUS_TONE: Record<RequestStatus, string> = {
open: "bg-amber-50 text-amber-700",
completed: "bg-green-50 text-green-700",
rejected: "bg-red-50 text-red-700",
cancelled: "bg-gray-100 text-gray-600",
};
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
function Alert({ msg }: { msg: NonNullable<Msg> }) {
return (
<div className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>
{msg.text}
</div>
);
}
function SectionHeader({ icon: Icon, title, tone = "brand" }: { icon: LucideIcon; title: string; tone?: "brand" | "red" }) {
return (
<div className="flex items-center gap-2 mb-4">
<div className={`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${tone === "red" ? "bg-red-50 text-red-600" : "bg-brand-50 text-brand-600"}`}>
<Icon className="w-5 h-5" />
</div>
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
</div>
);
}
function Toggle({ label, hint, checked, disabled, onChange }: { label: string; hint?: string; checked: boolean; disabled?: boolean; onChange: (v: boolean) => void }) {
return (
<label className={`flex items-start gap-3 ${disabled ? "opacity-60" : "cursor-pointer"}`}>
<input type="checkbox" className="mt-0.5 h-4 w-4 accent-brand-600" checked={checked} disabled={disabled} onChange={e => onChange(e.target.checked)} />
<span className="text-sm text-gray-700">
{label}
{hint && <span className="block text-xs text-gray-500">{hint}</span>}
</span>
</label>
);
}
export default function PrivacyCentrePage() {
const { token, logout } = useAuth();
const [info, setInfo] = useState<PrivacyInfo | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const load = useCallback(async () => {
if (!token) return;
try {
setInfo(await apiFetch<PrivacyInfo>("/api/privacy/me", { authToken: token }));
setLoadError(null);
} catch (e) {
setLoadError(errorMessage(e) || "Could not load your privacy settings.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
// ── News & announcements ──────────────────────────────────────────────────
const [newsMsg, setNewsMsg] = useDismissingState<Msg>(null);
const [savingNews, setSavingNews] = useState(false);
const setNews = async (channel: "email" | "whatsapp", value: boolean) => {
if (!token || !info) return;
setSavingNews(true);
setNewsMsg(null);
// Show the new state straight away; load() puts back the saved one if it fails.
setInfo({ ...info, news: { ...info.news, [channel]: value } });
try {
await apiFetch("/api/privacy/me/news", { method: "PUT", authToken: token, body: { [channel]: value } });
await load();
setNewsMsg({ type: "ok", text: value ? "You're subscribed." : "You're unsubscribed." });
} catch (e) {
await load();
setNewsMsg({ type: "err", text: errorMessage(e) || "Could not save." });
} finally {
setSavingNews(false);
}
};
// ── Download my data ──────────────────────────────────────────────────────
const [downloadMsg, setDownloadMsg] = useDismissingState<Msg>(null);
const [downloading, setDownloading] = useState<"json" | "pdf" | null>(null);
const download = async (format: "json" | "pdf") => {
if (!token) return;
setDownloading(format);
setDownloadMsg(null);
try {
const res = await fetch(`${API_BASE}/api/privacy/me/export${format === "pdf" ? "?format=pdf" : ""}`, { headers: { Authorization: `Bearer ${token}` } });
if (!res.ok) {
const body = await res.json().catch(() => null);
throw new Error(body?.message || `Download failed (${res.status})`);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `my-data-${new Date().toISOString().slice(0, 10)}.${format}`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 2000);
} catch (e) {
setDownloadMsg({ type: "err", text: errorMessage(e) || "Download failed." });
} finally {
setDownloading(null);
}
};
// ── Correction request ────────────────────────────────────────────────────
const [correction, setCorrection] = useState("");
const [correctionMsg, setCorrectionMsg] = useDismissingState<Msg>(null);
const [sendingCorrection, setSendingCorrection] = useState(false);
const requestCorrection = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setSendingCorrection(true);
setCorrectionMsg(null);
try {
const res = await apiFetch<{ message?: string }>("/api/privacy/me/requests", { method: "POST", authToken: token, body: { type: "correction", details: correction } });
setCorrection("");
setCorrectionMsg({ type: "ok", text: res?.message || "Request sent." });
load();
} catch (e) {
setCorrectionMsg({ type: "err", text: errorMessage(e) || "Could not send the request." });
} finally {
setSendingCorrection(false);
}
};
// ── Delete my account ─────────────────────────────────────────────────────
const [deleteStep, setDeleteStep] = useState<"idle" | "confirm">("idle");
const [deletePassword, setDeletePassword] = useState("");
const [deleteReason, setDeleteReason] = useState("");
const [deleteMsg, setDeleteMsg] = useDismissingState<Msg>(null);
const [deleting, setDeleting] = useState(false);
const requestDeletion = async (e: React.FormEvent) => {
e.preventDefault();
if (!token) return;
setDeleting(true);
setDeleteMsg(null);
try {
const res = await apiFetch<{ message?: string }>("/api/privacy/me/requests", {
method: "POST",
authToken: token,
body: { type: "deletion", password: deletePassword, details: deleteReason || undefined },
});
setDeleteMsg({ type: "ok", text: res?.message || "Your account is closed." });
setTimeout(() => logout(), 3000);
} catch (e) {
setDeleteMsg({ type: "err", text: errorMessage(e) || "Could not send the request." });
} finally {
setDeleting(false);
}
};
const openCorrection = info?.requests.some(r => r.type === "correction" && r.status === "open");
return (
<div className="max-w-4xl mx-auto w-full">
<div className="mb-6">
<BackLink href="/dashboard" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Privacy</h1>
<p className="text-sm text-gray-500 mt-1">
What we send you, a copy of the information we hold about you, and your rights under POPIA.
Read the <Link href="/legal/privacy" className="text-brand-600 hover:underline">Privacy Policy</Link>.
</p>
</div>
{loadError && <Alert msg={{ type: "err", text: loadError }} />}
<div className="grid lg:grid-cols-2 gap-6 items-start">
<div className="space-y-6">
{/* ── News & announcements ───────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Megaphone} title="News & announcements" />
<p className="text-sm text-gray-500 mb-4">
Occasional messages about upcoming events. Messages about events you&apos;ve registered for — tickets,
reminders, changes — are always sent{info ? ` (by ${info.notificationPreference === "both" ? "email and WhatsApp" : info.notificationPreference === "whatsapp" ? "WhatsApp" : "email"}; change this in ` : " (change how in "}
<Link href="/dashboard/user/profile" className="text-brand-600 hover:underline">Profile &amp; Security</Link>).
</p>
{info ? (
<div className="space-y-3">
<Toggle label="By email" checked={info.news.email} disabled={savingNews} onChange={v => setNews("email", v)} />
<Toggle
label="By WhatsApp"
hint={info.canWhatsApp ? undefined : "Add a valid phone number to your profile first."}
checked={info.news.whatsapp}
disabled={savingNews || (!info.canWhatsApp && !info.news.whatsapp)}
onChange={v => setNews("whatsapp", v)}
/>
</div>
) : !loadError && <p className="text-sm text-gray-400">Loading…</p>}
{newsMsg && <Alert msg={newsMsg} />}
{info && info.history.length > 0 && (
<details className="mt-4">
<summary className="text-xs text-gray-500 cursor-pointer">History of your choices</summary>
<ul className="mt-2 space-y-1">
{info.history.slice(0, 20).map(h => (
<li key={h.id} className="text-xs text-gray-500">
{new Date(h.createdAt).toLocaleString()} — {h.channel === "email" ? "email" : "WhatsApp"} {h.granted ? "on" : "off"}, {SOURCE_LABEL[h.source] || h.source}
</li>
))}
</ul>
</details>
)}
</section>
{/* ── Download my data ───────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Download} title="Download my data" />
<p className="text-sm text-gray-500 mb-4">
A copy of everything we hold about you: your account, registrations, the people you registered,
form answers, payments, tickets and check-ins, certificates, feedback and your communication choices.
</p>
<div className="flex flex-wrap gap-3">
<button onClick={() => download("pdf")} disabled={!!downloading} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{downloading === "pdf" ? "Preparing…" : "Readable PDF"}
</button>
<button onClick={() => download("json")} disabled={!!downloading} 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">
{downloading === "json" ? "Preparing…" : "Complete copy (JSON)"}
</button>
</div>
{downloadMsg && <Alert msg={downloadMsg} />}
</section>
{/* ── My requests ────────────────────────────────────────────────── */}
{info && info.requests.length > 0 && (
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={ListChecks} title="My requests" />
<ul className="space-y-3">
{info.requests.map(r => (
<li key={r.id} className="text-sm">
<div className="flex items-center gap-2">
<span className="font-medium text-gray-800">{TYPE_LABEL[r.type]}</span>
<span className={`text-xs px-2 py-0.5 rounded-full ${STATUS_TONE[r.status]}`}>{r.status}</span>
<span className="text-xs text-gray-400 ml-auto">{new Date(r.createdAt).toLocaleDateString()}</span>
</div>
{r.details && <p className="text-gray-600 mt-1 whitespace-pre-line">{r.details}</p>}
{r.response && <p className="text-gray-500 mt-1 text-xs whitespace-pre-line">Our answer: {r.response}</p>}
</li>
))}
</ul>
</section>
)}
</div>
<div className="space-y-6">
{/* ── Correct my data ────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={PencilLine} title="Correct my data" />
<p className="text-sm text-gray-500 mb-4">
Change your name, email or phone number yourself in{" "}
<Link href="/dashboard/user/profile" className="text-brand-600 hover:underline">Profile &amp; Security</Link>.
For anything you can&apos;t change there — such as details on a past registration, an attendee&apos;s
date of birth or a form answer — tell us what is wrong and we&apos;ll correct it.
</p>
{openCorrection ? (
<p className="text-sm text-gray-600">You have a correction request open — we&apos;ll email you when it&apos;s done.</p>
) : (
<form onSubmit={requestCorrection} className="space-y-3">
<textarea className={inputCls} rows={4} maxLength={5000} value={correction} onChange={e => setCorrection(e.target.value)} placeholder="What needs correcting, and what should it be?" required />
<button type="submit" disabled={sendingCorrection || !correction.trim()} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{sendingCorrection ? "Sending…" : "Send correction request"}
</button>
</form>
)}
{correctionMsg && <Alert msg={correctionMsg} />}
</section>
{/* ── Delete my account ──────────────────────────────────────────── */}
<section className="border border-red-200 rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Trash2} title="Delete my account" tone="red" />
<p className="text-sm text-gray-500 mb-4">
Your account is closed straight away, and your personal information — name, contact details, the people
you registered, form answers — is deleted once we&apos;ve processed the request (within 30 days). If you
have a registration for an upcoming event, that is sorted out first. Payment amounts and dates are kept,
without your name, because the law requires us to keep financial records.
</p>
{deleteStep === "idle" ? (
<button onClick={() => setDeleteStep("confirm")} className="px-4 py-2 rounded-lg border border-red-600 text-red-600 text-sm font-medium hover:bg-red-50">
Delete my account…
</button>
) : (
<form onSubmit={requestDeletion} className="space-y-4">
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-800">
<strong>You won&apos;t be able to log in again.</strong> Download your data first if you want a copy.
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Reason (optional)</label>
<textarea className={inputCls} rows={2} maxLength={1000} value={deleteReason} onChange={e => setDeleteReason(e.target.value)} />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Confirm with your password</label>
<input type="password" className={inputCls} value={deletePassword} onChange={e => setDeletePassword(e.target.value)} required autoComplete="current-password" />
</div>
<div className="flex gap-3">
<button type="button" onClick={() => { setDeleteStep("idle"); setDeletePassword(""); setDeleteReason(""); setDeleteMsg(null); }} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">
Cancel
</button>
<button type="submit" disabled={deleting || !deletePassword} className="px-4 py-2 rounded-lg bg-red-600 text-white text-sm font-medium hover:bg-red-700 disabled:opacity-50">
{deleting ? "Sending…" : "Close account and delete my data"}
</button>
</div>
</form>
)}
{deleteMsg && <Alert msg={deleteMsg} />}
</section>
</div>
</div>
</div>
);
}
@@ -3,6 +3,7 @@
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { apiFetch } from "@/lib/api";
import { isValidZAPhone } from "@/lib/phone";
import { useDismissingState } from "@/hooks/useDismissingState";
@@ -534,9 +535,10 @@ export default function UserProfilePage() {
<section className="border border-red-200 rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Trash2} title="Close account" tone="red" />
<p className="text-sm text-gray-500 mb-4">
Closing your account will deactivate it immediately. You can also request that your personal
information (name, email, phone number) be permanently deleted. Tickets and payment records
will remain for accounting purposes but will show as &quot;Deleted User&quot;.
Closing your account will deactivate it immediately. You can also ask for your personal
information to be deleted — we do that once the request is processed (see{" "}
<Link href="/dashboard/user/privacy" className="text-brand-600 hover:underline">Privacy</Link>). Tickets and
payment records remain for accounting purposes but show as &quot;Deleted User&quot;.
</p>
{closeStep === "idle" && (
@@ -562,8 +564,9 @@ export default function UserProfilePage() {
onChange={e => setDeleteData(e.target.checked)}
/>
<span className="text-sm text-gray-700">
<span className="font-medium">Also delete my personal data</span> — your name, email address,
and phone number will be permanently removed and cannot be recovered.
<span className="font-medium">Also delete my personal data</span> — your name, contact details,
the people you registered and your form answers are permanently removed once your request
is processed (within 30 days).
</span>
</label>
@@ -595,7 +598,7 @@ export default function UserProfilePage() {
disabled={closing || !closePassword}
className="px-4 py-2 rounded-lg bg-red-600 text-white text-sm font-medium hover:bg-red-700 disabled:opacity-50"
>
{closing ? "Processing…" : deleteData ? "Delete my data & close account" : "Close my account"}
{closing ? "Processing…" : deleteData ? "Close account & request deletion" : "Close my account"}
</button>
</div>
{closeMsg && <Alert msg={closeMsg} />}