POPIA toolkit part 3: retention, breach register, readiness

- Retention policies (Admin -> Privacy -> Retention) applied by a nightly
  `retention` job: inactive accounts anonymised after 5 years with a
  30-day warning (on by default; never staff roles or people with an
  upcoming registration), form answers, login history, payer details in
  payment notifications, audit/access logs
- User.lastLoginAt (set on login, backfilled) and inactivityWarnedAt
- Breach register (SecurityBreach) with drafts for the people affected
  and the Information Regulator
- Readiness checklist with a score
- Children's/medical flag in the access log; {retention} placeholder in
  the privacy notice
- Unit tests (retention.test.js), e2e (privacy-retention.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 20:25:58 +02:00
co-authored by Claude Opus 5.5
parent 6eee10b610
commit a1ecbb9617
32 changed files with 1441 additions and 35 deletions
@@ -0,0 +1,144 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
type Policy = { enabled: boolean; months: number };
type Definition = { label: string; description: string; minMonths: number; defaults: Policy };
type State = {
policies: Record<string, Policy>;
definitions: Record<string, Definition>;
reviewedAt: string | null;
reviewedBy: string | null;
preview: Record<string, Record<string, number>>;
lastRun: { at: string; result: Record<string, Record<string, number | string>> } | null;
related: { medicalDays: number; backupCount: number; analyticsDays: number };
};
type Msg = { type: "ok" | "err"; text: string } | null;
const fmt = (d: string) => new Date(d).toLocaleString(undefined, { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
function previewText(key: string, p: Record<string, number> | undefined) {
if (!p) return "";
if (key === "inactive_accounts") {
if (!p.toWarn && !p.toAnonymise) return "Nobody is affected right now.";
return `Next run: ${p.toWarn} to warn, ${p.toAnonymise} to anonymise (warned 30+ days ago).`;
}
return p.count ? `Next run affects ${p.count} record${p.count === 1 ? "" : "s"}.` : "Nothing is due right now.";
}
/** Admin → Privacy → Retention: how long personal information is kept. */
export function RetentionPanel({ token }: { token: string }) {
const [state, setState] = useState<State | null>(null);
const [policies, setPolicies] = useState<Record<string, Policy>>({});
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<Msg>(null);
const apply = (s: State) => { setState(s); setPolicies(s.policies); };
const load = useCallback(async () => {
try {
apply(await apiFetch<State>("/api/privacy/retention", { authToken: token }));
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load retention settings." });
}
}, [token]);
useEffect(() => { load(); }, [load]);
const save = async () => {
const inactive = policies.inactive_accounts;
if (state && inactive?.enabled && !state.policies.inactive_accounts.enabled && !confirm("Switch on deleting inactive accounts? People are warned 30 days before; after that it can't be undone.")) return;
setBusy(true);
setMsg(null);
try {
apply(await apiFetch<State>("/api/privacy/retention", { method: "PUT", authToken: token, body: { policies } }));
setMsg({ type: "ok", text: "Saved. The privacy notice's retention section is updated to match." });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not save." });
} finally {
setBusy(false);
}
};
const runNow = async () => {
if (!confirm("Run the retention job now? It deletes and anonymises everything past its retention period, just like the nightly run.")) return;
setBusy(true);
setMsg(null);
try {
const res = await apiFetch<{ state: State }>("/api/privacy/retention/run", { method: "POST", authToken: token });
apply(res.state);
setMsg({ type: "ok", text: "Done — see \"Last run\" below." });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "The run failed." });
} finally {
setBusy(false);
}
};
if (!state) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-400">Loading…</p>;
const dirty = JSON.stringify(policies) !== JSON.stringify(state.policies);
return (
<div className="space-y-5">
<p className="text-sm text-gray-600">
POPIA says personal information mustn&apos;t be kept longer than needed. Every night at 03:30 the retention job deletes or anonymises
what&apos;s past these periods. The defaults are a sensible start — check them with your Information Officer and save, even if you change nothing.
{state.reviewedAt ? ` Last saved ${fmt(state.reviewedAt)}${state.reviewedBy ? ` by ${state.reviewedBy}` : ""}.` : " Not reviewed yet."}
</p>
<ul className="space-y-3">
{Object.entries(state.definitions).map(([key, def]) => {
const p = policies[key];
return (
<li key={key} className="border rounded-xl p-4 bg-white">
<div className="flex flex-wrap items-center gap-3">
<label className="flex items-center gap-2 font-medium text-gray-900">
<input type="checkbox" className="h-4 w-4 accent-brand-600" checked={p.enabled} onChange={e => setPolicies({ ...policies, [key]: { ...p, enabled: e.target.checked } })} />
{def.label}
</label>
<label className="ml-auto flex items-center gap-2 text-sm text-gray-700">
after
<input type="number" min={def.minMonths} max={240} className="w-20 border rounded-lg px-2 py-1 text-sm" value={p.months} disabled={!p.enabled}
onChange={e => setPolicies({ ...policies, [key]: { ...p, months: parseInt(e.target.value, 10) || def.minMonths } })} aria-label={`${def.label} months`} />
months
</label>
</div>
<p className="mt-1 text-sm text-gray-600">{def.description}</p>
<p className="mt-1 text-xs text-gray-500">
{p.enabled ? previewText(key, state.preview[key]) : "Off — kept until someone asks for it to be deleted."}
{(p.months !== def.defaults.months || p.enabled !== def.defaults.enabled) && ` (Default: ${def.defaults.enabled ? `${def.defaults.months} months` : "off"}.)`}
</p>
</li>
);
})}
</ul>
<div className="border rounded-xl p-4 bg-gray-50 text-sm text-gray-600 space-y-1">
<div className="font-medium text-gray-800">Set elsewhere</div>
<div>Medical details from parental consent: deleted {state.related.medicalDays} days after the event — <Link href="/dashboard/admin/settings?tab=legal" className="text-brand-600 hover:underline">Site settings → Legal</Link>.</div>
<div>Database backups: the last {state.related.backupCount} are kept — <Link href="/dashboard/admin/settings?tab=backups" className="text-brand-600 hover:underline">Site settings → Backups</Link>.</div>
<div>Visit statistics: rolled up into anonymous daily totals after {state.related.analyticsDays} days.</div>
<div>Consent records and privacy notice acceptances are kept as proof (without the IP address once an account is deleted).</div>
</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>}
<div className="flex flex-wrap gap-2">
<button onClick={save} disabled={busy} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
{busy ? "Saving…" : dirty ? "Save changes" : "Save (confirm reviewed)"}
</button>
<button onClick={runNow} disabled={busy || dirty} className="px-4 py-2 rounded-lg border bg-white text-sm hover:bg-gray-50 disabled:opacity-50" title={dirty ? "Save first" : undefined}>
Run now
</button>
</div>
{state.lastRun && (
<div className="text-xs text-gray-500">
<span className="font-medium text-gray-700">Last run</span> {fmt(state.lastRun.at)}:{" "}
{Object.entries(state.lastRun.result).length === 0 ? "nothing switched on." : Object.entries(state.lastRun.result).map(([k, r]) => `${state.definitions[k]?.label || k} — ${Object.entries(r).map(([a, b]) => `${a}: ${b}`).join(", ")}`).join("; ")}
</div>
)}
</div>
);
}