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 f03b766b6e
commit 18f35ceeb3
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>
);
}
@@ -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">
@@ -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} />}
+1 -1
View File
@@ -8,7 +8,7 @@ export default function robots(): MetadataRoute.Robots {
rules: {
userAgent: "*",
allow: "/",
disallow: ["/dashboard", "/self-service", "/set-banner", "/lockdown-rules"],
disallow: ["/dashboard", "/self-service", "/set-banner", "/lockdown-rules", "/unsubscribe"],
},
sitemap: `${base}/sitemap.xml`,
};
@@ -0,0 +1,103 @@
"use client";
import React, { Suspense, useEffect, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { apiFetch, ApiError } from "@/lib/api";
import { MailX } from "lucide-react";
type Info =
| { kind: "account"; email: string; hasPhone: boolean; news: { email: boolean; whatsapp: boolean } }
| { kind: "address"; channel: "email" | "whatsapp"; address: string; optedOut: boolean };
/** Landing page for the unsubscribe link in News & announcements emails and WhatsApps. */
function Unsubscribe() {
const token = useSearchParams().get("t") || "";
const [info, setInfo] = useState<Info | null>(null);
const [error, setError] = useState<string | null>(token ? null : "This unsubscribe link is incomplete.");
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
useEffect(() => {
if (!token) return;
apiFetch<Info>(`/api/privacy/unsubscribe/${encodeURIComponent(token)}`)
.then(setInfo)
.catch(e => setError(e instanceof ApiError ? e.message : "Couldn't load this link."));
}, [token]);
const unsubscribe = async (channels?: ("email" | "whatsapp")[]) => {
setBusy(true);
try {
await apiFetch(`/api/privacy/unsubscribe/${encodeURIComponent(token)}`, { method: "POST", body: channels ? { channels } : {} });
setDone(true);
} catch (e) {
setError(e instanceof ApiError ? e.message : "Couldn't unsubscribe. Please try again.");
} finally {
setBusy(false);
}
};
const alreadyOff = info && (info.kind === "account" ? !info.news.email && !info.news.whatsapp : info.optedOut);
const btn = "px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50";
return (
<>
{error && <div className="border rounded-xl p-4 bg-red-50 text-red-800 text-sm">{error}</div>}
{!info && !error && <div className="text-sm text-gray-600">Loading…</div>}
{info && (
<div className="border rounded-xl p-5 bg-white shadow-sm space-y-4">
{done || alreadyOff ? (
<p className="text-sm text-gray-700">
You&apos;re unsubscribed from news and announcements{info.kind === "address" ? ` for ${info.address}` : ""}.
You&apos;ll still get messages about events you register for.
</p>
) : (
<>
<p className="text-sm text-gray-700">
Stop news and announcements to <strong>{info.kind === "account" ? info.email : info.address}</strong>?
Messages about events you register for — tickets, reminders, changes — still come through.
</p>
<div className="flex flex-wrap gap-3">
{info.kind === "account" && info.news.email && info.news.whatsapp ? (
<>
<button onClick={() => unsubscribe()} disabled={busy} className={`${btn} bg-brand-600 text-white hover:bg-brand-700`}>Unsubscribe from all news</button>
<button onClick={() => unsubscribe(["email"])} disabled={busy} className={`${btn} border border-gray-300 text-gray-700 hover:bg-gray-50`}>Email only</button>
<button onClick={() => unsubscribe(["whatsapp"])} disabled={busy} className={`${btn} border border-gray-300 text-gray-700 hover:bg-gray-50`}>WhatsApp only</button>
</>
) : (
<button onClick={() => unsubscribe()} disabled={busy} className={`${btn} bg-brand-600 text-white hover:bg-brand-700`}>{busy ? "Unsubscribing…" : "Unsubscribe"}</button>
)}
</div>
</>
)}
{info.kind === "account" && (
<p className="text-xs text-gray-500">
<Link href="/dashboard/user/privacy" className="text-brand-600 hover:underline">Log in to manage all your preferences</Link>
</p>
)}
</div>
)}
</>
);
}
export default function UnsubscribePage() {
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-1 px-4 py-10 max-w-xl 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">
<MailX className="w-5 h-5 text-brand-600" />
</div>
<h1 className="text-2xl font-semibold text-gray-900">Unsubscribe</h1>
</div>
<Suspense fallback={<div className="text-sm text-gray-600">Loading…</div>}>
<Unsubscribe />
</Suspense>
</main>
<Footer />
</div>
);
}
@@ -19,6 +19,8 @@ export function RegisterForm() {
const [phoneNumber, setPhoneNumber] = useState("");
const [notificationPreference, setNotificationPreference] = useState<"email" | "whatsapp" | "both">("email");
const [accepted, setAccepted] = useState(false);
// POPIA: marketing needs an opt-in, so this starts unticked.
const [newsOptIn, setNewsOptIn] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -53,6 +55,7 @@ export function RegisterForm() {
password,
phoneNumber: phoneNumber || undefined,
notificationPreference: hasValidPhone ? notificationPreference : "email",
newsOptIn,
});
window.location.href = redirectTo;
} catch (err) {
@@ -150,6 +153,19 @@ export function RegisterForm() {
</label>
</div>
<div className="flex items-start gap-2">
<input
id="news"
type="checkbox"
checked={newsOptIn}
onChange={(e) => setNewsOptIn(e.target.checked)}
className="mt-1 h-4 w-4 border-gray-300 rounded accent-brand-600"
/>
<label htmlFor="news" className="text-sm text-gray-700 leading-snug">
Send me news and announcements about upcoming events (optional — you can unsubscribe at any time).
</label>
</div>
<div className="mt-1">
<a
href={loginHref}
@@ -2,7 +2,7 @@
import React, { useState } from "react";
import Link from "next/link";
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, type LucideIcon } from "lucide-react";
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, Lock, type LucideIcon } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { RoleBadge, type Role } from "@/components/shared/RoleBadge";
import { UserAvatar } from "@/components/shared/UserAvatar";
@@ -12,6 +12,7 @@ import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
const navLinks: { href: string; label: string; icon: LucideIcon; roles?: string[] }[] = [
{ href: "/dashboard/user", label: "My Events", icon: Calendar, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/profile", label: "Profile & Security", icon: User, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/privacy", label: "Privacy", icon: Lock, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/staff", label: "Staff", icon: LayoutDashboard, roles: ["staff"] },
{ href: "/dashboard/supervisor", label: "Supervisor", icon: LayoutDashboard, roles: ["supervisor"] },
{ href: "/dashboard/admin", label: "Admin", icon: ShieldCheck, roles: ["admin"] },
@@ -0,0 +1,44 @@
"use client";
import React from "react";
export type MessageKind = "update" | "news";
const OPTIONS: { value: MessageKind; label: string; description: string }[] = [
{
value: "update",
label: "Event update",
description: "About an event the recipients registered for — a reminder, venue or time change, what to bring. Goes to everyone selected.",
},
{
value: "news",
label: "News & announcements",
description: "Promoting events or sharing news. Only goes to people who opted in, and includes an unsubscribe link.",
},
];
/** POPIA: what kind of bulk message this is — decides who it may go to (see utils/privacy.js). */
export function MessageKindPicker({ value, onChange, name }: { value: MessageKind; onChange: (kind: MessageKind) => void; name: string }) {
return (
<fieldset>
<legend className="block text-xs text-gray-600 mb-1">Message type</legend>
<div className="grid sm:grid-cols-2 gap-2">
{OPTIONS.map(o => (
<label key={o.value} className={`flex items-start gap-2 border rounded-lg p-2.5 cursor-pointer ${value === o.value ? "border-brand-500 bg-brand-50" : "border-gray-200 bg-white hover:bg-gray-50"}`}>
<input type="radio" name={name} className="mt-0.5 accent-brand-600" checked={value === o.value} onChange={() => onChange(o.value)} />
<span>
<span className="block text-sm font-medium text-gray-800">{o.label}</span>
<span className="block text-[11px] text-gray-500">{o.description}</span>
</span>
</label>
))}
</div>
</fieldset>
);
}
/** "Matched 12 recipient(s)." plus how many news skipped. */
export function matchedText(res: { matched?: number; skipped?: number } | null | undefined) {
const skipped = res?.skipped ?? 0;
return `Matched ${res?.matched ?? 0} recipient(s).${skipped ? ` ${skipped} skipped — not opted in to news or unsubscribed.` : ""}`;
}
@@ -0,0 +1,87 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { Megaphone } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
type News = { email: boolean; whatsapp: boolean };
/**
* POPIA: asks once, after login, whether the person wants News & announcements — for
* accounts that never answered (existing accounts, ones made at the door). Their current
* setting is pre-filled; saving records the answer so it isn't asked again.
*/
export function NewsPrompt() {
const { user, token } = useAuth();
const [news, setNews] = useState<News | null>(null);
const [canWhatsApp, setCanWhatsApp] = useState(false);
const [done, setDone] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const pending = !!user?.newsPromptPending && !done;
useEffect(() => {
if (!pending || !token || news) return;
apiFetch<{ news: News; canWhatsApp: boolean }>("/api/privacy/me", { authToken: token })
.then(res => { setNews(res.news); setCanWhatsApp(res.canWhatsApp); })
.catch(() => setDone(true)); // never block the dashboard over this
}, [pending, token, news]);
if (!pending || !news) return null;
const save = async (choice: News) => {
if (!token) return;
setSaving(true);
setError(null);
try {
await apiFetch("/api/privacy/me/news", { method: "PUT", authToken: token, body: { ...choice, source: "prompt" } });
setDone(true);
} catch (e) {
setError(errorMessage(e) || "Could not save your choice.");
} finally {
setSaving(false);
}
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-labelledby="news-prompt-title">
<div className="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
<div className="flex items-center gap-2 mb-3">
<div className="w-9 h-9 rounded-lg flex items-center justify-center bg-brand-50 text-brand-600 shrink-0">
<Megaphone className="w-5 h-5" />
</div>
<h2 id="news-prompt-title" className="text-lg font-semibold text-gray-900">Hear about upcoming events?</h2>
</div>
<p className="text-sm text-gray-600 mb-4">
We&apos;d like to send you occasional news and announcements. Messages about events you register for are
sent either way. You can change this any time under <Link href="/dashboard/user/privacy" className="text-brand-600 hover:underline">Privacy</Link>.
</p>
<div className="space-y-3 mb-5">
<label className="flex items-center gap-3 text-sm text-gray-700 cursor-pointer">
<input type="checkbox" className="h-4 w-4 accent-brand-600" checked={news.email} onChange={e => setNews({ ...news, email: e.target.checked })} />
By email
</label>
{canWhatsApp && (
<label className="flex items-center gap-3 text-sm text-gray-700 cursor-pointer">
<input type="checkbox" className="h-4 w-4 accent-brand-600" checked={news.whatsapp} onChange={e => setNews({ ...news, whatsapp: e.target.checked })} />
By WhatsApp
</label>
)}
</div>
{error && <p className="text-sm text-red-600 mb-3">{error}</p>}
<div className="flex flex-wrap justify-end gap-3">
<button onClick={() => save({ email: false, whatsapp: false })} disabled={saving} className="px-4 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200 disabled:opacity-50">
No thanks
</button>
<button onClick={() => save({ email: news.email, whatsapp: canWhatsApp && news.whatsapp })} disabled={saving} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{saving ? "Saving…" : "Save my choice"}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,92 @@
import React from "react";
import { Megaphone, Download, PencilLine, Trash2, MailX, Inbox, Clock, ShieldCheck, MessageCircle } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
/** Help content for /dashboard/user/privacy (the person's own privacy centre). */
export const userPrivacyHelpContent: HelpContent = {
title: "Privacy",
subtitle: "What we send you, your data, and your rights under POPIA.",
tabs: [
{
key: "messages",
label: "Messages",
icon: Megaphone,
content: (
<div className="space-y-4">
<GuideItem icon={Megaphone} title="News & announcements" tone="brand">
Occasional messages about upcoming events. You only get them if you said yes — by email, WhatsApp or both. Untick a box to stop them.
</GuideItem>
<GuideItem icon={ShieldCheck} title="Messages about your events" tone="green">
Tickets, receipts, reminders and changes to events you registered for are always sent, by the channel you chose in Profile &amp; Security.
</GuideItem>
<GuideItem icon={MailX} title="Unsubscribe" tone="amber">
Every news email has an unsubscribe link, and you can reply STOP to a news message on WhatsApp. The history under the boxes shows every choice you made and when.
</GuideItem>
</div>
),
},
{
key: "data",
label: "Your data",
icon: Download,
content: (
<div className="space-y-4">
<GuideItem icon={Download} title="Download my data" tone="brand">
The PDF is easy to read; the JSON file is the complete copy. Both include your registrations, the people you registered, form answers, payments, tickets and check-ins.
</GuideItem>
<GuideItem icon={PencilLine} title="Correct my data" tone="green">
Change your name, email and phone in Profile &amp; Security. For anything else, send a correction request — we answer by email within 30 days.
</GuideItem>
<GuideItem icon={Trash2} title="Delete my account" tone="rose">
Your account is closed straight away. Your personal information is deleted once the request is processed (within 30 days) — after any upcoming event you registered for. Payment amounts and dates are kept without your name, because the law requires it.
</GuideItem>
</div>
),
},
],
};
/** Help content for /dashboard/admin/data-requests. */
export const adminDataRequestsHelpContent: HelpContent = {
title: "Data requests",
subtitle: "POPIA requests from people about their personal information.",
tabs: [
{
key: "how",
label: "How it works",
icon: Inbox,
content: (
<div className="space-y-4">
<GuideItem icon={Inbox} title="Where requests come from" tone="brand">
People send correction and deletion requests from their Privacy page (or by ticking &quot;also delete my data&quot; when closing their account). The Information Officer (Site settings → Legal) and all admins are emailed for each one.
</GuideItem>
<GuideItem icon={Clock} title="30 days" tone="amber">
POPIA asks for an answer within 30 days. Requests due within a week or overdue are emailed to admins every morning, and overdue ones are outlined in red.
</GuideItem>
<GuideItem icon={Download} title="Access requests" tone="green">
People download their own data from their Privacy page, so those aren&apos;t listed here. If someone asks by email or phone, point them to that page. (Downloading is blocked while viewing as someone else, so an admin can&apos;t take a person&apos;s full record that way.)
</GuideItem>
</div>
),
},
{
key: "handle",
label: "Handling a request",
icon: Trash2,
content: (
<div className="space-y-4">
<GuideItem icon={PencilLine} title="Corrections" tone="brand">
Make the change (e.g. on the registration or attendee), then click Mark as done and say what you changed — it&apos;s emailed to them.
</GuideItem>
<GuideItem icon={Trash2} title="Deletions" tone="rose">
The account is already closed. If they have a registration for an upcoming event, cancel it (refund if needed) or wait until the event is over. Then Delete personal data: their name, contact details, attendees, form answers and the payer details kept by Yoco/PayFast notifications are removed. Payments, registrations and check-ins stay as &quot;Deleted User&quot; for the books and reports. It can&apos;t be undone and is logged in the audit log.
</GuideItem>
<GuideItem icon={MessageCircle} title="Reject or cancel" tone="amber">
Give a reason; it&apos;s emailed to them. Tick &quot;They withdrew it&quot; if they changed their mind. Rejecting or cancelling a deletion opens their account again.
</GuideItem>
</div>
),
},
],
};
@@ -26,6 +26,7 @@ import { supervisorBundlesHelpContent } from "./supervisor-bundles";
import { supervisorConsentHelpContent } from "./supervisor-consent";
import { supervisorWaitlistHelpContent } from "./supervisor-waitlist";
import { supervisorAttendanceHelpContent } from "./supervisor-attendance";
import { userPrivacyHelpContent, adminDataRequestsHelpContent } from "./privacy";
import { supervisorOfflineScansHelpContent } from "./supervisor-offline-scans";
import { supervisorAllocationsHelpContent, staffMyGroupsHelpContent } from "./supervisor-allocations";
import { supervisorEmailAttendeesHelpContent } from "./supervisor-email-attendees";
@@ -179,6 +180,16 @@ const REGISTRY: HelpRegistryEntry[] = [
matches: pathname => pathname === "/dashboard/supervisor/attendance",
content: supervisorAttendanceHelpContent,
},
{
slug: "user-privacy",
matches: pathname => pathname === "/dashboard/user/privacy",
content: userPrivacyHelpContent,
},
{
slug: "admin-data-requests",
matches: pathname => pathname === "/dashboard/admin/data-requests",
content: adminDataRequestsHelpContent,
},
{
slug: "supervisor-consent",
matches: pathname => pathname === "/dashboard/supervisor/consent",
@@ -1,5 +1,5 @@
import React from "react";
import { Mail, Users, Zap, Send, Clock } from "lucide-react";
import { Mail, Users, Zap, Send, Clock, ShieldCheck } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
@@ -22,6 +22,9 @@ export const supervisorEmailAttendeesHelpContent: HelpContent = {
<GuideItem icon={Send} title="Preview, send, or schedule" tone="green">
Preview the recipient list before sending, send immediately, or pick a future date and time.
</GuideItem>
<GuideItem icon={ShieldCheck} title="Message type (POPIA)" tone="violet">
An <strong>Event update</strong> is about the event they registered for and goes to everyone selected. <strong>News &amp; announcements</strong> (promoting events) only goes to people who opted in, and gets an unsubscribe link — the preview says how many were skipped. The next-event promo automation is always news.
</GuideItem>
</div>
</div>
),
@@ -37,7 +40,7 @@ export const supervisorEmailAttendeesHelpContent: HelpContent = {
Four canned lifecycle emails per event — a pre-event reminder, a final reminder, a thank-you, and a next-event promo — with send times auto-computed from the event&apos;s dates.
</GuideItem>
<GuideItem icon={Mail} title="Broadcasts" tone="violet">
Send to any selected users or pasted external addresses, independent of a specific event&apos;s attendee list.
Send to any selected users or pasted external addresses, independent of a specific event&apos;s attendee list. Broadcasts are News &amp; announcements unless you choose Event update.
</GuideItem>
<GuideItem icon={Clock} title="Scheduled" tone="gray">
Review, edit, or cancel any email that&apos;s scheduled but not yet sent.
@@ -1,5 +1,5 @@
import React from "react";
import { MessageCircle, Users, Zap, Clock } from "lucide-react";
import { MessageCircle, Users, Zap, Clock, ShieldCheck } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
@@ -19,6 +19,9 @@ export const supervisorWhatsappAttendeesHelpContent: HelpContent = {
<GuideItem icon={MessageCircle} title="Who's eligible" tone="brand">
Only recipients with a phone number can be messaged; the list is pre-filtered and colour-coded by notification preference (WhatsApp / Both), though you can still select a mismatch with a warning.
</GuideItem>
<GuideItem icon={ShieldCheck} title="Message type (POPIA)" tone="violet">
<strong>Event updates</strong> go to everyone selected. <strong>News &amp; announcements</strong> only go to people who opted in to WhatsApp news, and end with &quot;Reply STOP&quot; and an unsubscribe link. Broadcasts are news unless you choose Event update.
</GuideItem>
</div>
</div>
),
@@ -11,7 +11,7 @@ export type AuthContextValue = {
login: (email: string, password: string) => Promise<AuthUser | TwoFactorChallenge>;
verifyTwoFactor: (challengeId: string, code: string, rememberDevice: boolean) => Promise<AuthUser>;
resendTwoFactor: (challengeId: string) => Promise<TwoFactorChallenge>;
register: (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both" }) => Promise<void>;
register: (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both"; newsOptIn?: boolean }) => Promise<void>;
logout: () => void;
updateToken: (token: string) => void;
};
@@ -116,7 +116,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
});
}, []);
const register = useCallback(async (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both" }) => {
const register = useCallback(async (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both"; newsOptIn?: boolean }) => {
const res = await apiFetch<AuthResponse>("/api/users", {
method: "POST",
body: data,
+2
View File
@@ -9,6 +9,8 @@ export type AuthUser = {
twoFactorMethod?: TwoFactorMethod | null;
// True for roles that must use 2FA (admin, supervisor) — it can't be turned off.
twoFactorRequired?: boolean;
// POPIA: hasn't answered the "news and announcements" opt-in question yet (asked once).
newsPromptPending?: boolean;
};
export type AuthResponse = AuthUser & {
+2
View File
@@ -618,6 +618,8 @@ export type DashboardStats = {
// What the email/WhatsApp send, preview and schedule endpoints return.
export type MessageSendResult<Recipient = { phone: string; name?: string }> = {
matched?: number;
// News & announcements: selected people left out (not opted in, or unsubscribed).
skipped?: number;
queued?: number;
sent?: number;
recipients?: Recipient[];