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,51 @@
const prisma = require('../config/db');
const { getClientIp } = require('./requestUtils');
// What each DataAccessLog action means, for the admin page.
const ACCESS_ACTIONS = {
report_pdf: 'Report downloaded (PDF)',
report_excel: 'Report downloaded (Excel)',
report_email: 'Report emailed',
report_whatsapp: 'Report sent by WhatsApp',
attendance_export: 'Attendance register exported',
certificates_download: 'Certificates downloaded',
group_lists: 'Room/group lists opened',
form_responses: 'Attendee form answers viewed',
consent_list: 'Parental consent list viewed',
medical_list: 'Medical list viewed',
backup_download: 'Database backup downloaded',
impersonation: 'Viewed the site as another user',
};
/**
* POPIA access log: someone exported or viewed personal information in bulk. Fire-and-
* forget like logAdminAction — a logging failure never blocks the export itself.
*/
async function logDataAccess(req, { action, what, eventId = null, records = null }) {
try {
await prisma.dataAccessLog.create({
data: {
actorId: req.user?.id || null,
actorRole: req.user?.role || 'unknown',
action,
what: String(what || ACCESS_ACTIONS[action] || action).slice(0, 500),
eventId: eventId || null,
records: Number.isFinite(records) ? records : null,
ip: getClientIp(req),
},
});
} catch (e) {
console.error('Failed to log data access:', e?.message);
}
}
/** Rows in a report payload (main table or layered sections, plus extra tables). */
function reportRowCount(payload) {
const p = payload || {};
let n = Array.isArray(p.table?.rows) ? p.table.rows.length : 0;
if (Array.isArray(p.layered?.sections)) n += p.layered.sections.reduce((s, sec) => s + (Array.isArray(sec.items) ? sec.items.length : 0), 0);
if (Array.isArray(p.extraTables)) n += p.extraTables.reduce((s, t) => s + (Array.isArray(t.rows) ? t.rows.length : 0), 0);
return n;
}
module.exports = { ACCESS_ACTIONS, logDataAccess, reportRowCount };
+7 -1
View File
@@ -446,6 +446,10 @@ async function anonymiseUser(userId, db = prisma) {
const checkouts = await tx.providerCheckout.findMany({ where: { metadata: { path: ['userId'], equals: userId } }, select: { id: true, request: true } });
for (const c of checkouts) await tx.providerCheckout.update({ where: { id: c.id }, data: { request: scrubPersonal(c.request) } });
// Consent and notice records stay as proof, without the IP address they came from.
await tx.communicationConsent.updateMany({ where: { userId }, data: { ip: null } });
await tx.noticeAcceptance.updateMany({ where: { userId }, data: { ip: null } });
await tx.securityEvent.deleteMany({ where: { userId } });
await tx.passwordReset.deleteMany({ where: { userId } });
await tx.twoFactorChallenge.deleteMany({ where: { userId } });
@@ -472,7 +476,7 @@ async function exportUserData(userId, db = prisma) {
});
if (!user) return null;
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests] = await Promise.all([
const [registrations, payments, tickets, waitlist, certificates, feedback, consents, security, requests, notices] = await Promise.all([
db.registration.findMany({
where: { userId },
orderBy: { createdAt: 'asc' },
@@ -495,6 +499,7 @@ async function exportUserData(userId, db = prisma) {
consentHistory(userId, db),
db.securityEvent.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, take: 100, select: { type: true, ip: true, device: true, createdAt: true } }),
db.dataRequest.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, select: { type: true, status: true, details: true, response: true, createdAt: true, closedAt: true } }),
db.noticeAcceptance.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, select: { version: true, source: true, createdAt: true } }),
]);
return {
@@ -505,6 +510,7 @@ async function exportUserData(userId, db = prisma) {
news: { email: user.newsEmail, whatsapp: user.newsWhatsApp, answeredAt: user.newsAskedAt },
history: consents.map(c => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })),
},
privacyNoticeAccepted: notices.map(n => ({ version: n.version, how: n.source, at: n.createdAt })),
registrations: registrations.map(r => ({
id: r.id,
event: r.event?.title,
@@ -0,0 +1,434 @@
/**
* The privacy notice: the built-in text (version 0), published versions (PrivacyNotice),
* the admin's draft, and who has accepted which version.
*
* A notice is a list of sections { id, title, body }. A body is plain text, one paragraph
* per line; a line starting with "• " is a bullet. Placeholders are filled in when the
* notice is shown, so it follows Site settings and the operator register:
* {org} {orgEmail} {website} {ioName} {ioEmail} {medicalRetentionDays}
* {operators} — on a line of its own: one bullet per active operator.
*/
const prisma = require('../config/db');
const PLACEHOLDERS = ['org', 'orgEmail', 'website', 'ioName', 'ioEmail', 'medicalRetentionDays', 'operators'];
const MAX_SECTIONS = 40;
const MAX_TITLE = 200;
const MAX_BODY = 20000;
const DRAFT_KEY = 'privacy_notice_draft';
const DEFAULT_SECTIONS = [
{
id: 'summary',
title: 'Plain English Summary',
body: [
"We respect your privacy — here's what you need to know:",
'• We only collect info needed to run events: registrations, payments, tickets and check-in.',
'• We store your info safely on South African servers.',
"• We don't sell your data, and only share it with the services listed in section 9, which process payments and deliver messages for us.",
'• If you register other people or pass a ticket on, we only use the email or phone number you type to contact them. We never show you whether someone has an account with us.',
'• For youth events, a parent or guardian gives consent. Medical details are encrypted, seen only by the event leaders who need them, and deleted shortly after the event.',
'• Online payments go through Yoco or PayFast; we never see your card details.',
'• We send tickets, updates and security alerts by email and/or WhatsApp. News and announcements are sent only if you ask for them, and you can unsubscribe at any time.',
'• Visit statistics are only collected if you click "Allow" on the cookie notice — no third-party analytics.',
'• On the Privacy page in your account you can download your data, ask for corrections, and delete your account.',
].join('\n'),
},
{
id: 'introduction',
title: '1. Introduction',
body: [
"{org} ('we', 'us', 'our') values your privacy and is committed to protecting your personal information in accordance with the Protection of Personal Information Act (POPIA).",
'This notice explains what data we collect, how we use it, and your rights.',
].join('\n'),
},
{
id: 'information',
title: '2. Information We Collect',
body: [
'We collect the following information when you interact with our platform:',
'• Account information: name, email address, phone number, notification preference and password (stored only as an encrypted hash). If you use two-factor authentication, we keep which method you use; codes are short-lived and never stored in readable form.',
'• Security records: sign-ins, password changes and similar account events, with the time, IP address and device type, so we can alert you and investigate misuse.',
'• Event information: events you register for, ticket selections, discount codes used, attendee form answers, waitlist requests, ticket check-ins (when your ticket was scanned), and room or group allocations.',
'• Details about other people you register (see section 3), and parental consent details for youth events (see section 8).',
'• Payment information: processed by our payment provider (Yoco or PayFast); we receive only payment status, amount and reference numbers. If you sponsor a spot, we record the amount and, unless you give anonymously, the name and message you choose to add.',
"• Feedback: answers you give to post-event feedback forms. If an event's feedback is anonymous, your answers are not linked to your name.",
'• Your choices: whether you want news and announcements, which version of this notice you accepted, and when you made each choice.',
'• Communication data: emails or messages exchanged with our team.',
'• Visit statistics: only if you allow them on the cookie notice (see section 11).',
'We do not collect or store credit card numbers or bank details.',
'Accounts may be created by an administrator, or when someone registers you or transfers a ticket to you, with a mobile number or email address only. You can activate such an account at any time.',
].join('\n'),
},
{
id: 'others',
title: '3. People You Register or Transfer Tickets To',
body: [
'You can register other people (for example family members) and give each one their own ticket, or pass your ticket on to someone else.',
'• You type their name and, optionally, their email address or phone number. There is no search or list of existing users to choose from, and we never tell you whether the details you enter belong to an account.',
'• We use those details only to send that person their ticket, their attendee form, a parental consent request (youth events), or — for a transfer — a link to accept the ticket. A transfer only happens once they accept it; they can also decline.',
"• If the email or phone number matches an existing account, the ticket also appears in that person's own account. Otherwise an account may be created for them, which they can activate if they wish.",
"• Some events ask for each person's date of birth or gender (for example, to allocate rooms at a camp).",
'By entering someone else\'s details, you confirm that you are allowed to share them with us for this purpose (for a child, that you are their parent or guardian or have their permission).',
].join('\n'),
},
{
id: 'use',
title: '4. How We Use Your Information',
body: [
'We use your information to:',
'• Process event registrations, payments, discounts and refunds.',
'• Send updates about events you registered for — confirmations, reminders and changes — by email and/or WhatsApp (based on your preference).',
'• Send news and announcements about upcoming events, only if you asked for them. Every such email has an unsubscribe link, and you can reply STOP on WhatsApp.',
'• Send security notifications for new logins, password changes, and account actions on your account.',
'• Deliver your event tickets via email attachment and/or WhatsApp PDF (based on your preference).',
'• Check tickets in at the door, including with scanners that keep working without an internet connection.',
'• Offer places from a waitlist, arrange rooms and groups, and ask for parental consent on youth events.',
'• Send you an optional feedback form after an event, with one reminder.',
'• Manage user accounts and event attendance records, and give support when you ask for help.',
'• Improve our events and website (using anonymous statistics, and only with your permission).',
'• Comply with legal obligations.',
].join('\n'),
},
{
id: 'whatsapp',
title: '5. WhatsApp Communications',
body: [
"If you choose 'WhatsApp' or 'Both' as your notification preference, we will use your South African mobile number to send you messages via WhatsApp. These messages may include:",
'• Event registration confirmations and updates.',
'• Payment receipts.',
'• Your event tickets (as a PDF document).',
'• Security alerts such as new login notifications, password changes, and account closure confirmations.',
'• News and announcements, only if you asked for them on WhatsApp. Reply STOP to any of these to stop them.',
'WhatsApp communications are delivered through WAWP (wawp.net), a third-party WhatsApp Business API provider. Your mobile number is transmitted to WAWP solely for the purpose of delivering your messages.',
'Security-critical messages (login alerts, password resets, account closures) are always sent via email regardless of your preference, and additionally sent via WhatsApp if your preference includes it.',
"You may change your notification preference at any time from the Profile & Security page in your account. Selecting 'Email only' will stop WhatsApp messages from being sent to you.",
'For accounts registered without a valid email address (e.g. walk-in or at-the-door registrations), WhatsApp will be used as the primary delivery channel for payment confirmations and ticket delivery, regardless of notification preference, since email is unavailable.',
'If your account requires activation and no email address is on file, the activation link will be sent to your WhatsApp number instead.',
"WhatsApp is a product of Meta Platforms, Inc. By receiving WhatsApp messages from us, you are subject to WhatsApp's own Terms of Service and Privacy Policy.",
].join('\n'),
},
{
id: 'storage',
title: '6. Where We Store Your Data',
body: [
'All data is securely stored on cloud servers hosted in South Africa.',
'We use appropriate technical and organisational measures to protect your information from unauthorised access, alteration, or disclosure.',
].join('\n'),
},
{
id: 'retention',
title: '7. Data Retention',
body: [
'We retain your personal data for up to 5 years after your last event registration, or until you ask us to delete your account — whichever comes first.',
'Medical and emergency-contact details from parental consent forms are deleted {medicalRetentionDays} days after the event ends. The record of who gave consent, when, and to which wording is kept.',
'Detailed visit statistics are combined into anonymous daily totals after 90 days.',
"Ticket lists downloaded to a staff member's scanner for offline check-in are deleted from that device when offline mode is ended.",
'Records of support access to accounts (see section 9), of who exported personal information, and other audit records are kept for accountability.',
'You can ask for your account to be deleted from the Privacy page in your account. Your account is closed straight away, and your personal information — your name and contact details, the people you registered, your form answers — is deleted within 30 days (after any upcoming event you registered for). Payment and registration records are kept without your name, because the law requires us to keep financial records.',
'Backups of our database still contain deleted information until they are replaced, which happens automatically within a few weeks.',
].join('\n'),
},
{
id: 'children',
title: '8. Children, Parental Consent and Health Information',
body: [
'Users under 18 may only create an account or register for events with the consent and supervision of a parent or guardian.',
'We do not knowingly collect or process personal information of minors without such consent.',
"For youth events, each attendee's date of birth is required. For anyone under 18, the parent or guardian named at registration is sent a consent request by email and WhatsApp, where they review the event details and give or decline consent. Their typed name, the time, the wording agreed to, and the IP address and device type used are recorded as proof of consent. A young person can't be checked in until consent is given.",
"The consent form may ask for medical information (such as allergies, medication and conditions) and an emergency contact. This is special personal information under POPIA. We collect it only with the parent's or guardian's consent, for the young person's safety at the event. It is stored encrypted and shown only to supervisors who need it, and each time the medical list is viewed this is recorded. It is deleted after the event as described in section 7.",
'A parent or guardian may also say whether photos of the young person may be used.',
].join('\n'),
},
{
id: 'sharing',
title: '9. Who Can See Your Information',
body: [
'We do not sell or rent your personal information. Outside our organisation, it is shared only with these service providers ("operators"), each only for its purpose:',
'{operators}',
'• Anyone we are required to share it with under South African law.',
'Within our organisation, people see only what they need:',
"• Door staff see a ticket's holder name, ticket type and check-in status when scanning.",
'• Group, room or bus leaders see the names, ages and contact numbers of the people in their group. Medical details are shown to supervisors only.',
'• Supervisors and administrators manage registrations, payments and communication for events. Every export of personal information (reports, attendance registers, lists) is recorded.',
'• Support access: to help with a problem (for example, a ticket not showing), an administrator may view the site as you see it for up to 30 minutes. This is strictly read-only — nothing can be changed, paid, registered or sent on your behalf. A reason must be given, and the session and every page viewed are recorded. The organisation may choose to email you whenever this happens.',
'• Sponsors never see who was helped by a sponsorship; the public only sees how many spots were sponsored.',
'• Nobody else can see whether you have an account.',
].join('\n'),
},
{
id: 'rights',
title: '10. Your Rights (under POPIA)',
body: [
'Under POPIA, you have the right to:',
'• Access your personal information.',
'• Request correction or deletion of your data.',
'• Withdraw consent for processing, including for news and announcements.',
'• Object to direct marketing.',
'• Lodge a complaint with the Information Regulator of South Africa.',
'The Privacy page in your account lets you download your data, ask for a correction, delete your account and choose which messages you receive. We answer requests within 30 days.',
'To contact the Information Regulator:',
'• Website: www.inforeg.org.za',
'• Email: enquiries@inforeg.org.za',
'To exercise your rights directly with us, contact our Information Officer using the details in section 14 below.',
].join('\n'),
},
{
id: 'cookies',
title: '11. Cookie Policy (Cookies and Browser Storage)',
body: [
"Our own site does not set tracking cookies. It keeps a few small items in your browser's storage (localStorage, and on staff scanners IndexedDB and an offline page cache). These work much like cookies, so this policy covers them. We do not use third-party analytics, advertising or tracking pixels.",
"Strictly necessary — always used, because the site can't work without them:",
'• hope_events_token — keeps you signed in.',
'• hope_events_user_cache — your last loaded profile, so pages keep working if your connection drops.',
'• hope_events_device — only if you tick "Trust this device" when entering a two-factor code, so you aren\'t asked for a code every time.',
'• hope_events_cookie_consent — remembers your choice on the cookie notice.',
'• banner_dismissed_… — remembers notices you have closed.',
'Staff and administrators only:',
'• hope_events_scan_device, hope_events_offline_lock and the "hope-events-offline-scan" database — on a staff member\'s scanner in offline mode: the device\'s id, the ticket list for the section being scanned, and scans waiting to upload. They are deleted when offline mode is ended. A copy of the scanner page is also cached so it opens without a connection.',
'• hope_events_admin_token, hope_events_admin_user_cache and hope_events_impersonation — only while an administrator is using read-only support access (section 9), and removed when it ends.',
'Optional — only if you click "Allow" on the cookie notice:',
'• hope_events_analytics_sid — a random, anonymous visit id. With it we count, in our own statistics, how many visitors view an event, start registering, and complete a registration. We record only that step, where the visit came from (for example a short link or campaign link) and the type of device — never your name, IP address or browsing history. Detailed records become anonymous daily totals after 90 days. If you choose "No thanks", nothing is counted and no visit id is created.',
'Third parties:',
"• Event pages with a location show an embedded Google Maps map. Google may set its own cookies when the map loads (see Google's privacy policy).",
"• Payments open the payment provider's secure checkout page (Yoco or PayFast), which uses its own cookies on the provider's site.",
'You can change your cookie choice at any time with "Cookie settings" at the bottom of every page, or with the button above. You can also clear your browser\'s storage in your browser settings; this signs you out.',
].join('\n'),
},
{
id: 'security',
title: '12. Security',
body: [
'Your personal data is encrypted during transmission and stored using industry-standard security protocols. Medical and emergency details are additionally encrypted in our database.',
'Passwords are encrypted and cannot be viewed by anyone, including administrators.',
'Two-factor authentication is available to everyone and is required for supervisors and administrators.',
'Links we send for consent, feedback, ticket transfers and unsubscribing are personal. Only a secure fingerprint of most links is stored, not the link itself.',
'In the event of a data breach that poses a risk to your rights, we will notify you and the Information Regulator of South Africa as required under POPIA section 22, without unreasonable delay.',
].join('\n'),
},
{
id: 'changes',
title: '13. Changes to This Notice',
body: [
'We may update this notice from time to time. Each update is published as a new version with its date, and earlier versions stay available on this page.',
'If a change is significant, we ask you to accept the new version the next time you log in.',
].join('\n'),
},
{
id: 'officer',
title: '14. Information Officer',
body: [
'The Information Officer responsible for overseeing compliance with POPIA on behalf of {org} is:',
'• Name: {ioName}',
'• Email: {ioEmail}',
'You may contact the Information Officer for any POPIA-related requests, including access to your personal data, requests for correction or deletion, and formal complaints.',
].join('\n'),
},
{
id: 'contact',
title: '15. Contact',
body: [
'For general privacy-related questions or requests, you can also contact us at:',
'📧 {orgEmail}',
].join('\n'),
},
];
function defaultSections() {
return DEFAULT_SECTIONS.map(s => ({ ...s }));
}
function slugify(text) {
return String(text || '').toLowerCase().replace(/^\d+\.\s*/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'section';
}
/** Checks and tidies sections from the editor. Throws a message fit for the admin. */
function cleanSections(input) {
if (!Array.isArray(input) || input.length === 0) throw new Error('The notice needs at least one section.');
if (input.length > MAX_SECTIONS) throw new Error(`At most ${MAX_SECTIONS} sections.`);
const seen = new Set();
return input.map((s, i) => {
const title = String(s?.title || '').trim();
const body = String(s?.body || '').replace(/\r\n/g, '\n').trim();
if (!title) throw new Error(`Section ${i + 1} needs a title.`);
if (title.length > MAX_TITLE) throw new Error(`The title of "${title.slice(0, 40)}…" is too long.`);
if (body.length > MAX_BODY) throw new Error(`"${title}" is too long.`);
let id = slugify(s?.id || title);
while (seen.has(id)) id = `${id}-${i + 1}`;
seen.add(id);
return { id, title, body };
});
}
/** Settings and operators the placeholders are filled from. */
async function noticeContext(db = prisma) {
const { getSetting } = require('./settingsCache');
const [org, orgEmail, website, ioName, ioEmail, medicalDays, operators] = await Promise.all([
getSetting('org_name', process.env.ORG_NAME || 'Cross Code'),
getSetting('org_email', ''),
getSetting('legal_website_url', ''),
getSetting('legal_io_name', ''),
getSetting('legal_io_email', ''),
getSetting('consent_medical_retention_days', ''),
db.operator.findMany({ where: { active: true }, orderBy: [{ order: 'asc' }, { name: 'asc' }] }),
]);
// Unset legal fields show an obviously-unfinished placeholder, never someone's real details.
return {
org,
orgEmail: orgEmail || 'privacy@example.com',
website: website || 'example.com',
ioName: ioName || '[not yet configured]',
ioEmail: ioEmail || 'io@example.com',
medicalRetentionDays: String(parseInt(medicalDays, 10) || 30),
operators,
};
}
function operatorLine(o) {
return `• ${o.name}${o.location ? ` (${o.location})` : ''} — ${o.purpose}. ${o.dataShared ? `Receives: ${o.dataShared}.` : ''}`.trim();
}
/** Sections with their placeholders filled in. */
function renderSections(sections, ctx) {
return sections.map(s => {
const body = String(s.body || '')
.split('\n')
.flatMap(line => (line.trim() === '{operators}' ? (ctx.operators.length ? ctx.operators.map(operatorLine) : ['• (No service providers listed.)']) : [line]))
.map(line => line.replace(/\{(\w+)\}/g, (m, key) => (key !== 'operators' && PLACEHOLDERS.includes(key) ? ctx[key] : m)))
.join('\n');
return { id: s.id, title: s.title, body };
});
}
async function latestNotice(db = prisma) {
return db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
}
/** The newest version people must have accepted, or null when none asks for it. */
async function requiredVersion(db = prisma) {
const row = await db.privacyNotice.findFirst({ where: { requiresAcceptance: true }, orderBy: { version: 'desc' }, select: { version: true } });
return row ? row.version : null;
}
/** Whether someone must (re-)accept the notice before carrying on. */
async function noticePromptPending(user, db = prisma) {
const required = await requiredVersion(db);
if (required == null) return false;
return (user.noticeVersionAccepted ?? -1) < required;
}
/**
* A notice for the public page: the given version (or the current one), rendered, with
* the list of versions. Version 0 is the built-in notice.
*/
async function publicNotice(version, db = prisma) {
const versions = await db.privacyNotice.findMany({
orderBy: { version: 'desc' },
select: { version: true, publishedAt: true, changeSummary: true, requiresAcceptance: true },
});
const ctx = await noticeContext(db);
const wanted = version == null ? versions[0]?.version ?? 0 : version;
if (wanted === 0) {
if (version != null && versions.length) return null; // the built-in text isn't a past version
const { getSetting } = require('./settingsCache');
return {
version: 0,
builtIn: true,
current: true,
publishedAt: null,
effectiveDate: (await getSetting('legal_effective_date', '')) || '[not yet set]',
changeSummary: null,
sections: renderSections(DEFAULT_SECTIONS, ctx),
versions,
};
}
const notice = await db.privacyNotice.findUnique({ where: { version: wanted } });
if (!notice) return null;
return {
version: notice.version,
builtIn: false,
current: notice.version === versions[0]?.version,
publishedAt: notice.publishedAt,
effectiveDate: notice.publishedAt.toLocaleDateString('en-ZA', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'Africa/Johannesburg' }),
changeSummary: notice.changeSummary,
sections: renderSections(notice.sections, ctx),
versions,
};
}
/** The version a new acceptance is for: the latest published, or 0 (built-in). */
async function currentVersion(db = prisma) {
return (await latestNotice(db))?.version ?? 0;
}
/** Record that someone accepted the current notice. */
async function acceptNotice(userId, { source, ip = null } = {}, db = prisma) {
const version = await currentVersion(db);
await db.user.update({ where: { id: userId }, data: { noticeVersionAccepted: version } });
await db.noticeAcceptance.create({ data: { userId, version, source, ip } });
return version;
}
// ─── Draft (admin) ────────────────────────────────────────────────────────────
/** The draft being edited, or — when there is none — the current notice's sections. */
async function getDraft(db = prisma) {
const row = await db.appSetting.findUnique({ where: { key: DRAFT_KEY } });
if (row?.value) {
try {
const draft = JSON.parse(row.value);
if (Array.isArray(draft.sections)) return { sections: draft.sections, savedAt: draft.savedAt || null, isDraft: true };
} catch { /* fall through to the current notice */ }
}
const latest = await latestNotice(db);
return { sections: latest ? latest.sections : defaultSections(), savedAt: null, isDraft: false };
}
async function saveDraft(sections, db = prisma) {
const clean = cleanSections(sections);
const value = JSON.stringify({ sections: clean, savedAt: new Date().toISOString() });
await db.appSetting.upsert({ where: { key: DRAFT_KEY }, update: { value }, create: { key: DRAFT_KEY, value } });
return clean;
}
async function discardDraft(db = prisma) {
await db.appSetting.deleteMany({ where: { key: DRAFT_KEY } });
}
/** Publish the given sections as the next version, and clear the draft. */
async function publish({ sections, changeSummary, requiresAcceptance, publishedById }, db = prisma) {
const clean = cleanSections(sections);
const notice = await db.$transaction(async tx => {
const latest = await tx.privacyNotice.findFirst({ orderBy: { version: 'desc' }, select: { version: true } });
return tx.privacyNotice.create({
data: {
version: (latest?.version ?? 0) + 1,
sections: clean,
changeSummary: changeSummary ? String(changeSummary).trim().slice(0, 2000) : null,
requiresAcceptance: !!requiresAcceptance,
publishedById: publishedById || null,
},
});
});
await discardDraft(db);
return notice;
}
module.exports = {
PLACEHOLDERS,
defaultSections,
cleanSections,
noticeContext,
renderSections,
operatorLine,
requiredVersion,
noticePromptPending,
publicNotice,
currentVersion,
acceptNotice,
getDraft,
saveDraft,
discardDraft,
publish,
};