POPIA toolkit part 2: privacy notice editor, operators, consent and access logs

- Admin -> Privacy (POPIA): edit the privacy notice (built-in text as the
  start, placeholders for org/IO/operators), drafts, preview, numbered
  versions; earlier versions readable on /legal/privacy?version=N
- "Significant change" versions are accepted once after login
  (NoticePrompt); sign-up records the version accepted
- Operator register (seeded with the services the app uses), listed in
  the notice via {operators}
- Consent log (news opt-ins, notice acceptances, parental consent) and
  access log (report exports, registers, certificates, group lists, form
  answers, consent/medical lists, backups, impersonation)
- Information Officer on the contact page
- Unit tests (privacyNotice.test.js), e2e (privacy-notice.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 19:11:20 +02:00
co-authored by Claude Opus 5.5
parent 04be99b930
commit 34f9e96e4e
40 changed files with 2328 additions and 324 deletions
@@ -0,0 +1,181 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
const fmt = (d: string | null) => (d ? new Date(d).toLocaleString(undefined, { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
const selectCls = "border rounded-lg px-3 py-2 text-sm bg-white";
function Pager({ page, total, pageSize, onPage }: { page: number; total: number; pageSize: number; onPage: (p: number) => void }) {
const pages = Math.max(1, Math.ceil(total / pageSize));
if (pages <= 1) return <p className="text-xs text-gray-500">{total} record{total === 1 ? "" : "s"}</p>;
return (
<div className="flex items-center gap-2 text-sm">
<button onClick={() => onPage(page - 1)} disabled={page <= 1} className="px-2 py-1 rounded border bg-white disabled:opacity-40">Previous</button>
<span className="text-gray-600">Page {page} of {pages} · {total} records</span>
<button onClick={() => onPage(page + 1)} disabled={page >= pages} className="px-2 py-1 rounded border bg-white disabled:opacity-40">Next</button>
</div>
);
}
// ─── Consent log ──────────────────────────────────────────────────────────────
type ConsentType = "news" | "notice" | "parental";
type NewsRow = { id: string; at: string; name: string | null; email: string | null; channel: string; granted: boolean; source: string; ip: string | null };
type NoticeRow = { id: string; at: string; name: string | null; email: string | null; version: number; source: string; ip: string | null };
type ParentalRow = { id: string; at: string | null; child: string; event: string; status: string; signedName: string | null; parentName: string | null; textVersion: number; photoConsent: boolean | null; ip: string | null; medicalDeleted: boolean };
type LogResponse<T> = { rows: T[]; total: number; pageSize: number };
const SOURCE: Record<string, string> = {
signup: "Sign-up", privacy_centre: "Privacy page", prompt: "Asked after login", unsubscribe_link: "Unsubscribe link",
whatsapp_stop: "Replied STOP", existing_account: "Existing account (1.38.0)", admin: "Administrator",
};
/** Admin → Privacy → Consent log: proof of who agreed to what, when and how. */
export function ConsentLogPanel({ token }: { token: string }) {
const [type, setType] = useState<ConsentType>("news");
const [q, setQ] = useState("");
const [query, setQuery] = useState("");
const [page, setPage] = useState(1);
const [data, setData] = useState<LogResponse<NewsRow | NoticeRow | ParentalRow> | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setData(null);
try {
setData(await apiFetch(`/api/privacy/consent-log?type=${type}&page=${page}${query ? `&q=${encodeURIComponent(query)}` : ""}`, { authToken: token }));
setError(null);
} catch (e) {
setError(errorMessage(e) || "Could not load the consent log.");
}
}, [token, type, page, query]);
useEffect(() => { load(); }, [load]);
return (
<div className="space-y-3">
<p className="text-sm text-gray-600">Who agreed to what, when and how. Entries are never changed or removed (after an account is deleted they stay, without the IP address).</p>
<form onSubmit={e => { e.preventDefault(); setPage(1); setQuery(q.trim()); }} className="flex flex-wrap gap-2">
<select className={selectCls} value={type} onChange={e => { setType(e.target.value as ConsentType); setPage(1); }} aria-label="Kind of consent">
<option value="news">News &amp; announcements opt-in</option>
<option value="notice">Privacy notice accepted</option>
<option value="parental">Parental consent</option>
</select>
<input className="border rounded-lg px-3 py-2 text-sm flex-1 min-w-[12rem]" value={q} onChange={e => setQ(e.target.value)} placeholder="Name or email" aria-label="Search" />
<button className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm">Search</button>
</form>
{error && <p className="text-sm text-red-700">{error}</p>}
{!data ? <p className="text-sm text-gray-400">Loading…</p> : data.rows.length === 0 ? <p className="text-sm text-gray-500">Nothing recorded yet.</p> : (
<div className="overflow-x-auto border rounded-xl bg-white">
<table className="w-full text-sm">
{type === "news" && (
<>
<thead className="bg-gray-50 text-left text-xs text-gray-500"><tr><th className="p-2">When</th><th className="p-2">Person</th><th className="p-2">Channel</th><th className="p-2">Choice</th><th className="p-2">How</th></tr></thead>
<tbody>{(data.rows as NewsRow[]).map(r => (
<tr key={r.id} className="border-t">
<td className="p-2 whitespace-nowrap">{fmt(r.at)}</td>
<td className="p-2">{r.name || <span className="text-gray-400">No account</span>}<div className="text-xs text-gray-500 break-all">{r.email}</div></td>
<td className="p-2">{r.channel === "whatsapp" ? "WhatsApp" : "Email"}</td>
<td className="p-2">{r.granted ? <span className="text-green-700">Opted in</span> : <span className="text-gray-700">Opted out</span>}</td>
<td className="p-2 text-gray-600">{SOURCE[r.source] || r.source}{r.ip ? <div className="text-xs text-gray-400">{r.ip}</div> : null}</td>
</tr>
))}</tbody>
</>
)}
{type === "notice" && (
<>
<thead className="bg-gray-50 text-left text-xs text-gray-500"><tr><th className="p-2">When</th><th className="p-2">Person</th><th className="p-2">Version</th><th className="p-2">How</th></tr></thead>
<tbody>{(data.rows as NoticeRow[]).map(r => (
<tr key={r.id} className="border-t">
<td className="p-2 whitespace-nowrap">{fmt(r.at)}</td>
<td className="p-2">{r.name}<div className="text-xs text-gray-500 break-all">{r.email}</div></td>
<td className="p-2">{r.version === 0 ? "Built-in" : r.version}</td>
<td className="p-2 text-gray-600">{SOURCE[r.source] || r.source}{r.ip ? <div className="text-xs text-gray-400">{r.ip}</div> : null}</td>
</tr>
))}</tbody>
</>
)}
{type === "parental" && (
<>
<thead className="bg-gray-50 text-left text-xs text-gray-500"><tr><th className="p-2">When</th><th className="p-2">Child · event</th><th className="p-2">Answer</th><th className="p-2">Signed by</th><th className="p-2">Wording</th></tr></thead>
<tbody>{(data.rows as ParentalRow[]).map(r => (
<tr key={r.id} className="border-t">
<td className="p-2 whitespace-nowrap">{fmt(r.at)}</td>
<td className="p-2">{r.child}<div className="text-xs text-gray-500">{r.event}</div></td>
<td className="p-2">{r.status === "given" ? <span className="text-green-700">Given</span> : <span className="text-red-700">Declined</span>}{r.photoConsent != null && <div className="text-xs text-gray-500">Photos: {r.photoConsent ? "yes" : "no"}</div>}</td>
<td className="p-2">{r.signedName || "—"}{r.ip ? <div className="text-xs text-gray-400">{r.ip}</div> : null}</td>
<td className="p-2 text-gray-600">v{r.textVersion}{r.medicalDeleted && <div className="text-xs text-gray-400">medical details deleted</div>}</td>
</tr>
))}</tbody>
</>
)}
</table>
</div>
)}
{data && <Pager page={page} total={data.total} pageSize={data.pageSize} onPage={setPage} />}
</div>
);
}
// ─── Access log ───────────────────────────────────────────────────────────────
type AccessRow = { id: string; at: string; actor: string; actorRole: string; action: string; what: string; records: number | null; ip: string | null };
type AccessResponse = LogResponse<AccessRow> & { actions: Record<string, string>; actors: { id: string; name: string }[] };
/** Admin → Privacy → Access log: who took personal information out of the system in bulk. */
export function AccessLogPanel({ token }: { token: string }) {
const [action, setAction] = useState("");
const [actorId, setActorId] = useState("");
const [page, setPage] = useState(1);
const [data, setData] = useState<AccessResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const params = new URLSearchParams({ page: String(page) });
if (action) params.set("action", action);
if (actorId) params.set("actorId", actorId);
setData(await apiFetch<AccessResponse>(`/api/privacy/access-log?${params}`, { authToken: token }));
setError(null);
} catch (e) {
setError(errorMessage(e) || "Could not load the access log.");
}
}, [token, action, actorId, page]);
useEffect(() => { load(); }, [load]);
return (
<div className="space-y-3">
<p className="text-sm text-gray-600">
Every time someone downloads, emails or opens personal information in bulk — reports, attendance registers, certificates, group lists,
form answers, the consent and medical lists, backups — and every time an admin views the site as someone else.
</p>
<div className="flex flex-wrap gap-2">
<select className={selectCls} value={action} onChange={e => { setAction(e.target.value); setPage(1); }} aria-label="What">
<option value="">Everything</option>
{Object.entries(data?.actions || {}).map(([k, label]) => <option key={k} value={k}>{label}</option>)}
</select>
<select className={selectCls} value={actorId} onChange={e => { setActorId(e.target.value); setPage(1); }} aria-label="Who">
<option value="">Everyone</option>
{(data?.actors || []).map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select>
</div>
{error && <p className="text-sm text-red-700">{error}</p>}
{!data ? <p className="text-sm text-gray-400">Loading…</p> : data.rows.length === 0 ? <p className="text-sm text-gray-500">Nothing recorded yet.</p> : (
<div className="overflow-x-auto border rounded-xl bg-white">
<table className="w-full text-sm">
<thead className="bg-gray-50 text-left text-xs text-gray-500"><tr><th className="p-2">When</th><th className="p-2">Who</th><th className="p-2">What</th><th className="p-2 text-right">Records</th></tr></thead>
<tbody>{data.rows.map(r => (
<tr key={r.id} className="border-t align-top">
<td className="p-2 whitespace-nowrap">{fmt(r.at)}</td>
<td className="p-2">{r.actor}<div className="text-xs text-gray-500">{r.actorRole}{r.ip ? ` · ${r.ip}` : ""}</div></td>
<td className="p-2">{data.actions[r.action] || r.action}<div className="text-xs text-gray-500">{r.what}</div></td>
<td className="p-2 text-right">{r.records ?? "—"}</td>
</tr>
))}</tbody>
</table>
</div>
)}
{data && <Pager page={page} total={data.total} pageSize={data.pageSize} onPage={setPage} />}
</div>
);
}
@@ -0,0 +1,230 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { ArrowUp, ArrowDown, Trash2, Plus, RotateCcw, Eye, PencilLine } from "lucide-react";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { PrivacyNoticeSection, type NoticeSection } from "@/components/shared/PrivacyNoticeSection";
type Version = { version: number; publishedAt: string; changeSummary: string | null; requiresAcceptance: boolean; publishedBy: string | null; acceptances: number };
type Draft = { sections: NoticeSection[]; rendered: NoticeSection[]; isDraft: boolean; savedAt: string | null; versions: Version[]; builtIn: NoticeSection[] };
type Msg = { type: "ok" | "err"; text: string } | null;
const PLACEHOLDER_HELP: [string, string][] = [
["{org}", "organisation name"],
["{orgEmail}", "organisation email"],
["{website}", "website (Site settings → Legal)"],
["{ioName}", "Information Officer"],
["{ioEmail}", "Information Officer's email"],
["{medicalRetentionDays}", "days before medical details are deleted"],
["{operators}", "on its own line: one bullet per active operator"],
];
const fmt = (d: string) => new Date(d).toLocaleString(undefined, { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
/** Admin → Privacy → Privacy notice: edit the sections, preview, publish versions. */
export function NoticeEditor({ token }: { token: string }) {
const [draft, setDraft] = useState<Draft | null>(null);
const [sections, setSections] = useState<NoticeSection[]>([]);
const [dirty, setDirty] = useState(false);
const [preview, setPreview] = useState(false);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<Msg>(null);
const [publishing, setPublishing] = useState(false);
const [changeSummary, setChangeSummary] = useState("");
const [requiresAcceptance, setRequiresAcceptance] = useState(false);
const load = useCallback(async () => {
try {
const d = await apiFetch<Draft>("/api/privacy/notice/draft", { authToken: token });
setDraft(d);
setSections(d.sections);
setDirty(false);
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the notice." });
}
}, [token]);
useEffect(() => { load(); }, [load]);
const change = (next: NoticeSection[]) => { setSections(next); setDirty(true); };
const update = (i: number, patch: Partial<NoticeSection>) => change(sections.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const move = (i: number, by: number) => {
const next = [...sections];
const [s] = next.splice(i, 1);
next.splice(i + by, 0, s);
change(next);
};
const save = async () => {
setBusy(true);
setMsg(null);
try {
const res = await apiFetch<{ sections: NoticeSection[]; rendered: NoticeSection[]; savedAt: string }>("/api/privacy/notice/draft", { method: "PUT", authToken: token, body: { sections } });
setDraft(d => (d ? { ...d, sections: res.sections, rendered: res.rendered, isDraft: true, savedAt: res.savedAt } : d));
setSections(res.sections);
setDirty(false);
setMsg({ type: "ok", text: "Draft saved. It isn't public until you publish it." });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not save." });
} finally {
setBusy(false);
}
};
const discard = async () => {
if (!confirm("Throw away the draft and go back to the published text?")) return;
setBusy(true);
try {
await apiFetch("/api/privacy/notice/draft", { method: "DELETE", authToken: token });
await load();
setMsg({ type: "ok", text: "Draft discarded." });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not discard." });
} finally {
setBusy(false);
}
};
const publish = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const res = await apiFetch<{ version: number }>("/api/privacy/notice/publish", { method: "POST", authToken: token, body: { sections, changeSummary, requiresAcceptance } });
setPublishing(false);
setChangeSummary("");
setRequiresAcceptance(false);
await load();
setMsg({ type: "ok", text: `Version ${res.version} is published.${requiresAcceptance ? " Everyone will be asked to accept it after they next log in." : ""}` });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not publish." });
} finally {
setBusy(false);
}
};
if (!draft) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
const builtInById = new Map(draft.builtIn.map(s => [s.id, s]));
const current = draft.versions[0];
return (
<div className="space-y-5">
<div className="text-sm text-gray-600">
{current ? (
<>Published: <strong>version {current.version}</strong> ({fmt(current.publishedAt)}). </>
) : (
<>Nothing published yet — the site shows the built-in notice. </>
)}
{draft.isDraft && <span className="text-amber-700">You have an unpublished draft{draft.savedAt ? ` (saved ${fmt(draft.savedAt)})` : ""}. </span>}
<Link href="/legal/privacy" target="_blank" className="text-brand-600 hover:underline">View the public page</Link>
</div>
<details className="text-xs text-gray-500 border rounded-lg p-3 bg-gray-50">
<summary className="cursor-pointer font-medium text-gray-700">How to write it</summary>
<p className="mt-2">One paragraph per line; start a line with &quot;• &quot; for a bullet. These are filled in when the notice is shown, so they stay up to date:</p>
<ul className="mt-1 grid sm:grid-cols-2 gap-x-4">
{PLACEHOLDER_HELP.map(([p, d]) => <li key={p}><code>{p}</code> — {d}</li>)}
</ul>
<p className="mt-2">This is tooling to help you comply, not legal advice — your Information Officer should check the wording.</p>
</details>
<div className="flex flex-wrap gap-2">
<button onClick={() => setPreview(p => !p)} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-white text-sm hover:bg-gray-50">
{preview ? <><PencilLine className="w-4 h-4" /> Edit</> : <><Eye className="w-4 h-4" /> Preview</>}
</button>
<button onClick={save} disabled={busy || !dirty} className="px-3 py-1.5 rounded-lg bg-white border border-brand-600 text-brand-700 text-sm font-medium hover:bg-brand-50 disabled:opacity-50">
Save draft
</button>
<button onClick={() => setPublishing(true)} disabled={busy} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
Publish…
</button>
{draft.isDraft && (
<button onClick={discard} disabled={busy} className="px-3 py-1.5 rounded-lg text-sm text-gray-600 hover:bg-gray-100">Discard draft</button>
)}
{dirty && <span className="self-center text-xs text-amber-700">Unsaved changes</span>}
</div>
{msg && <div className={`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>}
{publishing && (
<form onSubmit={publish} className="border rounded-xl p-4 bg-brand-50/40 space-y-3">
<div className="font-medium text-gray-900">Publish version {(current?.version ?? 0) + 1}</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">What changed</label>
<textarea className={inputCls} rows={2} maxLength={2000} value={changeSummary} onChange={e => setChangeSummary(e.target.value)} placeholder="e.g. We now use PayFast for online payments." />
</div>
<label className="flex items-start gap-2 text-sm text-gray-700">
<input type="checkbox" className="mt-0.5 h-4 w-4 accent-brand-600" checked={requiresAcceptance} onChange={e => setRequiresAcceptance(e.target.checked)} />
<span>
<strong>Significant change</strong> — ask everyone to accept this version the next time they log in.
<span className="block text-xs text-gray-500">Leave unticked for small fixes (wording, typos, contact details).</span>
</span>
</label>
<div className="flex gap-2">
<button type="button" onClick={() => setPublishing(false)} className="px-3 py-1.5 rounded-lg bg-gray-100 text-sm hover:bg-gray-200">Cancel</button>
<button type="submit" disabled={busy || (requiresAcceptance && !changeSummary.trim())} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{busy ? "Publishing…" : "Publish"}
</button>
</div>
</form>
)}
{preview ? (
<div className="border rounded-xl p-6 bg-white text-gray-700 leading-relaxed">
{dirty && <p className="mb-4 text-xs text-amber-700">Showing the last saved draft — save to preview your latest edits.</p>}
{draft.rendered.map((s, i) => <PrivacyNoticeSection key={s.id} section={s} first={i === 0} />)}
</div>
) : (
<div className="space-y-3">
{sections.map((s, i) => {
const original = builtInById.get(s.id);
return (
<div key={`${s.id}-${i}`} className="border rounded-xl p-3 bg-white">
<div className="flex items-center gap-2 mb-2">
<input className={`${inputCls} font-medium`} value={s.title} onChange={e => update(i, { title: e.target.value })} aria-label="Section title" />
<button onClick={() => move(i, -1)} disabled={i === 0} className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30" aria-label="Move up"><ArrowUp className="w-4 h-4" /></button>
<button onClick={() => move(i, 1)} disabled={i === sections.length - 1} className="p-1.5 rounded hover:bg-gray-100 disabled:opacity-30" aria-label="Move down"><ArrowDown className="w-4 h-4" /></button>
{original && (original.body !== s.body || original.title !== s.title) && (
<button onClick={() => update(i, { title: original.title, body: original.body })} className="p-1.5 rounded hover:bg-gray-100" title="Restore the built-in text" aria-label="Restore the built-in text"><RotateCcw className="w-4 h-4" /></button>
)}
<button onClick={() => confirm(`Remove "${s.title}"?`) && change(sections.filter((_, j) => j !== i))} className="p-1.5 rounded hover:bg-red-50 text-red-600" aria-label="Remove section"><Trash2 className="w-4 h-4" /></button>
</div>
<textarea className={`${inputCls} font-mono text-xs`} rows={Math.min(18, Math.max(3, s.body.split("\n").length + 1))} value={s.body} onChange={e => update(i, { body: e.target.value })} aria-label={`${s.title} text`} />
</div>
);
})}
<button onClick={() => change([...sections, { id: `section-${sections.length + 1}`, title: "New section", body: "" }])} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-white text-sm hover:bg-gray-50">
<Plus className="w-4 h-4" /> Add section
</button>
</div>
)}
{draft.versions.length > 0 && (
<div>
<h3 className="text-sm font-semibold text-gray-900 mb-2">Published versions</h3>
<div className="overflow-x-auto border rounded-xl bg-white">
<table className="w-full text-sm">
<thead className="bg-gray-50 text-left text-xs text-gray-500">
<tr><th className="p-2">Version</th><th className="p-2">Published</th><th className="p-2">What changed</th><th className="p-2">Re-accept</th><th className="p-2 text-right">Accepted by</th></tr>
</thead>
<tbody>
{draft.versions.map(v => (
<tr key={v.version} className="border-t">
<td className="p-2"><Link href={`/legal/privacy?version=${v.version}`} target="_blank" className="text-brand-600 hover:underline">{v.version}</Link></td>
<td className="p-2 whitespace-nowrap">{fmt(v.publishedAt)}{v.publishedBy ? ` · ${v.publishedBy}` : ""}</td>
<td className="p-2 text-gray-600">{v.changeSummary || "—"}</td>
<td className="p-2">{v.requiresAcceptance ? "Yes" : "No"}</td>
<td className="p-2 text-right">{v.acceptances}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,120 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
type Operator = { id: string; name: string; purpose: string; dataShared: string; location: string | null; website: string | null; active: boolean; order: number };
type Form = { name: string; purpose: string; dataShared: string; location: string; website: string; active: boolean };
const EMPTY: Form = { name: "", purpose: "", dataShared: "", location: "", website: "", active: true };
const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
function OperatorForm({ initial, onSave, onCancel, busy }: { initial: Form; onSave: (f: Form) => void; onCancel: () => void; busy: boolean }) {
const [f, setF] = useState(initial);
const set = (k: keyof Form) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: k === "active" ? e.target.checked : e.target.value });
return (
<form onSubmit={e => { e.preventDefault(); onSave(f); }} className="grid sm:grid-cols-2 gap-3 border rounded-xl p-4 bg-gray-50">
<label className="text-sm">Name<input className={inputCls} value={f.name} onChange={set("name")} required maxLength={200} /></label>
<label className="text-sm">What they do for you<input className={inputCls} value={f.purpose} onChange={set("purpose")} required placeholder="e.g. Online payments" /></label>
<label className="text-sm sm:col-span-2">Personal information they receive<input className={inputCls} value={f.dataShared} onChange={set("dataShared")} placeholder="e.g. Name, email address, payment amount" /></label>
<label className="text-sm">Where it&apos;s processed<input className={inputCls} value={f.location} onChange={set("location")} placeholder="e.g. South Africa" /></label>
<label className="text-sm">Website / privacy policy<input className={inputCls} value={f.website} onChange={set("website")} placeholder="https://…" /></label>
<label className="flex items-center gap-2 text-sm sm:col-span-2">
<input type="checkbox" className="h-4 w-4 accent-brand-600" checked={f.active} onChange={set("active")} /> In use (listed in the privacy notice)
</label>
<div className="flex gap-2 sm:col-span-2">
<button type="button" onClick={onCancel} className="px-3 py-1.5 rounded-lg bg-white border text-sm hover:bg-gray-100">Cancel</button>
<button type="submit" disabled={busy} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">{busy ? "Saving…" : "Save"}</button>
</div>
</form>
);
}
/** Admin → Privacy → Operators: the third parties that process personal information. */
export function OperatorsPanel({ token }: { token: string }) {
const [ops, setOps] = useState<Operator[] | null>(null);
const [editing, setEditing] = useState<string | "new" | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
setOps(await apiFetch<Operator[]>("/api/privacy/operators", { authToken: token }));
} catch (e) {
setError(errorMessage(e) || "Could not load operators.");
}
}, [token]);
useEffect(() => { load(); }, [load]);
const save = async (f: Form) => {
setBusy(true);
setError(null);
try {
const body = { ...f, location: f.location || null, website: f.website || null };
if (editing === "new") await apiFetch("/api/privacy/operators", { method: "POST", authToken: token, body });
else await apiFetch(`/api/privacy/operators/${editing}`, { method: "PUT", authToken: token, body });
setEditing(null);
await load();
} catch (e) {
setError(errorMessage(e) || "Could not save.");
} finally {
setBusy(false);
}
};
const remove = async (op: Operator) => {
if (!confirm(`Remove ${op.name} from the register? (Untick "In use" instead if you might use them again.)`)) return;
try {
await apiFetch(`/api/privacy/operators/${op.id}`, { method: "DELETE", authToken: token });
await load();
} catch (e) {
setError(errorMessage(e) || "Could not remove.");
}
};
return (
<div className="space-y-4">
<p className="text-sm text-gray-600">
Services outside your organisation that process personal information for you (POPIA calls them &quot;operators&quot;). The ones in
use are listed in the privacy notice wherever it says <code>{"{operators}"}</code>. Check each one&apos;s details — especially
your email and hosting provider — and that you have an agreement with it.
</p>
{error && <p className="text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg p-3">{error}</p>}
{ops === null ? <p className="text-sm text-gray-400">Loading…</p> : (
<ul className="space-y-2">
{ops.map(op => (
<li key={op.id}>
{editing === op.id ? (
<OperatorForm busy={busy} onCancel={() => setEditing(null)} onSave={save}
initial={{ name: op.name, purpose: op.purpose, dataShared: op.dataShared, location: op.location || "", website: op.website || "", active: op.active }} />
) : (
<div className={`flex items-start gap-3 border rounded-xl p-3 bg-white ${op.active ? "" : "opacity-60"}`}>
<div className="min-w-0 flex-1 text-sm">
<div className="font-medium text-gray-900">
{op.name}{op.location ? <span className="font-normal text-gray-500"> · {op.location}</span> : null}
{!op.active && <span className="ml-2 text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600">not in use</span>}
</div>
<div className="text-gray-600">{op.purpose}</div>
{op.dataShared && <div className="text-xs text-gray-500">Receives: {op.dataShared}</div>}
{op.website && <a href={op.website} target="_blank" rel="noopener noreferrer" className="text-xs text-brand-600 hover:underline break-all">{op.website}</a>}
</div>
<button onClick={() => setEditing(op.id)} className="p-1.5 rounded hover:bg-gray-100" aria-label={`Edit ${op.name}`}><Pencil className="w-4 h-4" /></button>
<button onClick={() => remove(op)} className="p-1.5 rounded hover:bg-red-50 text-red-600" aria-label={`Remove ${op.name}`}><Trash2 className="w-4 h-4" /></button>
</div>
)}
</li>
))}
</ul>
)}
{editing === "new" ? (
<OperatorForm busy={busy} initial={EMPTY} onCancel={() => setEditing(null)} onSave={save} />
) : (
<button onClick={() => setEditing("new")} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border bg-white text-sm hover:bg-gray-50">
<Plus className="w-4 h-4" /> Add operator
</button>
)}
</div>
);
}