This repository has been archived on 2026-11-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
hope-events/frontend/src/app/dashboard/user/privacy/page.tsx
T
joshuaandClaude Opus 5.5 e9d1b1fb24 Accessibility pass, WCAG 2.2 AA (1.50.0)
Public pages, auth, registration, payment, My Events and the kiosk: skip
link, focus ring, labels tied to fields, named quantity buttons, announced
errors, ModalOverlay popups (focus trap, Escape, focus return), contrast
and underlined in-text links, reduced motion. Branding warns about a primary
colour too light for white text and offers a darker shade. axe-core and
keyboard checks in e2e/accessibility.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:41:19 +02:00

344 lines
18 KiB
TypeScript

"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",
activation: "when you activated your account",
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-500">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-500 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 htmlFor="privacy-reason" className="block text-sm font-medium text-gray-700 mb-1">Reason (optional)</label>
<textarea id="privacy-reason" className={inputCls} rows={2} maxLength={1000} value={deleteReason} onChange={e => setDeleteReason(e.target.value)} />
</div>
<div>
<label htmlFor="privacy-confirm-with-your-password" className="block text-sm font-medium text-gray-700 mb-1">Confirm with your password</label>
<input id="privacy-confirm-with-your-password" 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>
);
}