Describe your event (new event), Improve/Shorter/Fix mistakes (event description, banner, email and WhatsApp boxes), Draft with AI (email and WhatsApp attendees), Summarise this report (people-free reports) and Summarise feedback (per event). Built-in privacy notice text for AI (2.0.0 entry in BUILT_IN_UPDATES). npm run ai:eval runs the trial cases through the Hub with fact checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMeckMWrKPfc1MMyMJF
538 lines
37 KiB
JavaScript
538 lines
37 KiB
JavaScript
/**
|
||
* 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.
|
||
* {retention} — on a line of its own: one bullet per retention period (utils/retention.js).
|
||
*/
|
||
|
||
const prisma = require('../config/db');
|
||
|
||
const PLACEHOLDERS = ['org', 'orgEmail', 'website', 'ioName', 'ioEmail', 'medicalRetentionDays', 'operators', 'retention'];
|
||
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, check-in, volunteer rosters and, for children\'s ministry, kids check-in.',
|
||
"• Your information is kept in this site's own database, run by the hosting provider listed in section 9. It isn't shared with other organisations that use the same software.",
|
||
"• We don't sell your data, and only share it with the services listed in section 9 — they process payments and deliver messages for us, and any other system we connect (such as church-management software) gets only the updates we chose.",
|
||
'• 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.',
|
||
"• For kids check-in, parents add their children's details once. Allergies, medical and custody notes are encrypted, shown only to kids-ministry staff, and deleted when a child hasn't been checked in for a while (section 7). Children are collected with a pickup code.",
|
||
'• 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 (including the sessions you chose on multi-session events), discount codes used, attendee form answers, waitlist requests, ticket check-ins (when your ticket was scanned, per session), room or group allocations, and completion certificates issued to you.',
|
||
'• Your home campus, if the organisation has more than one campus and you choose one.',
|
||
'• Serving (if you volunteer): the roles and shifts you sign up for or are given, requests to pass a shift on and who took it, when you checked in, and the hours you served.',
|
||
'• Event series you follow, and season passes you buy (a season pass registers you for each event on it, so each shows in your registrations).',
|
||
"• Kids check-in (if you use it): your family's name, your children's names, dates of birth, gender, allergies, medical notes and custody notes, the adults you allow to collect them (name, phone number, relationship), and each check-in — when, which room, the pickup code, who checked them in and out, and who collected them (see section 8).",
|
||
'• Details about other people you register (see section 3), parental consent details for youth events, and children at kids check-in (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, and keep attendance per session on multi-session events.',
|
||
'• Send optional reminders before sessions, and issue completion certificates (each has a code anyone can use to check it is genuine: the check shows the name on the certificate and the event).',
|
||
'• Check children in and out at kids check-in, send you their pickup code, and ask you to come to the room if a leader needs you.',
|
||
'• Show you the events of your home campus first, if the organisation has more than one campus.',
|
||
'• Run volunteer rosters: remind you the day before you serve, pass your shift on to someone who accepts it when you can\'t make it, and check you in when you arrive.',
|
||
'• Tell you when a new event in a series you follow comes out. This counts as news, so it\'s only sent if you get news and announcements.',
|
||
'• 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.',
|
||
'• If we use the AI helpers: our staff can ask an AI service to help draft event details and messages, improve text, and summarise reports and event feedback. A person checks every suggestion before anything is saved or sent. Only what a task needs is sent — never your name, contact details, or medical or children\'s information — and feedback comments are sent without who wrote them (see section 9).',
|
||
'• 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, and sign-in codes if you chose WhatsApp for two-factor authentication.',
|
||
'• Session reminders, if the event sends them, and volunteer reminders the day before you serve.',
|
||
'• Kids check-in: your children\'s pickup code, and a request to come to the room if a leader needs you. These never include medical or custody details. If you ask the desk to, the pickup code is also sent to one of your authorised adults.',
|
||
'• 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: [
|
||
"Your information is stored in this site's own database, on the servers of the hosting provider listed in section 9 (where they are is shown there). Each organisation using this software has its own separate site and database.",
|
||
'The software (Cross Events) is licensed from Cross Code. Every 15 minutes the site sends Cross Code\'s licence server technical health information (software version, uptime, disk space, errors) and totals — such as the number of accounts, events, registrations, tickets and check-ins, and income as a broad range (for example "R5 001–R20 000"). It never sends names, contact details, children\'s details or any other personal information.',
|
||
'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 keep personal information only as long as we need it:',
|
||
'{retention}',
|
||
"• Ticket lists downloaded to a staff member's scanner for offline check-in are deleted from that device when offline mode is ended.",
|
||
'• Copies of the updates sent to connected systems (webhooks, section 9) are kept for 30 days so problems can be checked, then deleted — and straight away when your account is deleted.',
|
||
"• Family lists downloaded to a kids check-in desk for offline use stay on that device until the desk is synced and the list is refreshed or removed. Only kids-ministry staff can download them, and each download is recorded.",
|
||
'You can ask for your account to be deleted at any time 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.',
|
||
].join('\n'),
|
||
},
|
||
{
|
||
id: 'children',
|
||
title: '8. Children, Parental Consent, Kids Check-in 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.',
|
||
'Kids check-in:',
|
||
"• A parent adds their children under My account → Kids, or the kids desk adds them with the parent present. A parent who is added at the desk with only a phone number or email address gets an account they can activate.",
|
||
"• Allergies, medical notes and custody notes (for example, someone who may not collect a child) are special personal information. We keep them only to keep your child safe, with your consent as their parent or guardian. They are stored encrypted, shown only to kids-ministry staff at the desk and in the rooms, and never put in a message. Opening the desk or room screens is recorded. Only parents, supervisors and administrators can change custody notes, and every change is recorded.",
|
||
'• Each check-in gives you a pickup code. Anyone who has the code can collect your children, so share it only with people you trust. The adults you list as allowed to collect are shown to the room leader so they can check.',
|
||
'• Each child is added to the event\'s attendance records (name, date of birth and gender) like any other attendee, so the organisation knows who attended.',
|
||
"• A child's details are deleted when they haven't been checked in for the period in section 7. You can remove them yourself at any time.",
|
||
].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.',
|
||
'If we use the AI helpers, requests go through our software provider\'s service to Anthropic (the Claude AI service) in the United States, which is listed above. Our software provider does not keep what was sent. Anthropic handles it under its commercial terms, which do not allow it to be used to train AI; it may be kept for a short time for safety checks. Because this is outside South Africa, it is only done under the protections POPIA requires for such transfers.',
|
||
'If we connect another system — for example our church-management software — through a webhook, it is listed above with what it receives. It gets only the updates we chose (such as new registrations, payments and check-ins), and never children\'s details from kids check-in.',
|
||
'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 from parental consent forms are shown to supervisors only.',
|
||
"• Kids-ministry staff see the children checked in, with their allergies, medical and custody notes, the parents' names and phone numbers, and the adults allowed to collect them.",
|
||
'• Staff running a volunteer roster see who is serving in each role, their contact details, check-ins and hours. If you ask for someone to take over your shift, your first name, the role and any note you add are shown to the event\x27s other volunteers and others who could take it over.',
|
||
'• If the organisation has several campuses, a staff member may be limited to their own campuses\' events.',
|
||
'• 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.',
|
||
'• hope_events_campus — only on churches with more than one campus: the campus you chose on the events page, so it stays chosen.',
|
||
'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.',
|
||
"• hope_events_kids_event and hope_events_kids_room — on a kids check-in device: the event and room last chosen.",
|
||
'• cross_events_dismissed_notices — notices from the software provider (such as planned maintenance) that you have closed.',
|
||
"• hope_events_kids_device and hope_events_kids_offline_… — on a kids check-in desk in offline mode: the device's id, the list of families and children (with allergies, medical and custody notes), pickup codes kept for the device, and check-ins waiting to sync.",
|
||
'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, and children's allergies, medical and custody notes, 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.',
|
||
'You are asked to agree to this notice when you create an account, or when you activate an account that was made for you (for example when someone registered you, or at the door). If you have never agreed to it — such as an account from before we asked — we ask once, the next time you log in.',
|
||
'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'),
|
||
},
|
||
];
|
||
|
||
/**
|
||
* Changes to the built-in text, newest last. A site that published its own version keeps its own
|
||
* text, so the editor lists the changes made since the revision it last reviewed
|
||
* (`privacy_notice_builtin_reviewed`) and offers the new text section by section.
|
||
*/
|
||
const BUILT_IN_UPDATES = [
|
||
{
|
||
revision: '1.48.1',
|
||
summary: [
|
||
'Volunteer rosters: what is kept about people who serve, reminders, and who sees the roster.',
|
||
'Following an event series, and season passes.',
|
||
'Webhooks: other systems the organisation connects, what they receive, and that copies are kept 30 days.',
|
||
'How people agree to the notice: at sign-up, at account activation, or once after login if they never have.',
|
||
'A browser-storage item for closed provider notices.',
|
||
],
|
||
sections: ['summary', 'information', 'use', 'whatsapp', 'retention', 'sharing', 'cookies', 'changes'],
|
||
},
|
||
{
|
||
revision: '2.0.0',
|
||
summary: [
|
||
'AI helpers: staff can ask an AI service (Anthropic\'s Claude, through the software provider) to draft events and messages, improve text and summarise reports and feedback; a person checks every suggestion, and no names, contact details, medical or children\'s information are sent.',
|
||
'Where AI requests go (the United States), that the provider doesn\'t keep them, and that they aren\'t used to train AI.',
|
||
],
|
||
sections: ['use', 'sharing'],
|
||
},
|
||
];
|
||
const BUILT_IN_REVISION = BUILT_IN_UPDATES[BUILT_IN_UPDATES.length - 1].revision;
|
||
const REVIEWED_KEY = 'privacy_notice_builtin_reviewed';
|
||
|
||
function revisionLess(a, b) {
|
||
const pa = String(a || '0').split('.').map(Number);
|
||
const pb = String(b || '0').split('.').map(Number);
|
||
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) < (pb[i] || 0);
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* Built-in text changes this site hasn't reviewed yet. None while nothing is published (the site
|
||
* shows the built-in text, so it is always current).
|
||
*/
|
||
async function builtInUpdates(db = prisma) {
|
||
if (!(await latestNotice(db))) return [];
|
||
const row = await db.appSetting.findUnique({ where: { key: REVIEWED_KEY } });
|
||
return BUILT_IN_UPDATES.filter(u => !row?.value || revisionLess(row.value, u.revision));
|
||
}
|
||
|
||
/** The admin has gone through the built-in changes (taken what they want, or not). */
|
||
async function markBuiltInReviewed(db = prisma) {
|
||
await db.appSetting.upsert({ where: { key: REVIEWED_KEY }, update: { value: BUILT_IN_REVISION }, create: { key: REVIEWED_KEY, value: BUILT_IN_REVISION } });
|
||
}
|
||
|
||
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, retention] = 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' }] }),
|
||
require('./retention').noticeLines(db),
|
||
]);
|
||
// 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,
|
||
retention,
|
||
};
|
||
}
|
||
|
||
// Placeholders that stand on a line of their own and become several bullet lines.
|
||
const LIST_PLACEHOLDERS = {
|
||
operators: ctx => (ctx.operators.length ? ctx.operators.map(operatorLine) : ['• (No service providers listed.)']),
|
||
retention: ctx => ctx.retention || [],
|
||
};
|
||
|
||
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 => {
|
||
const list = line.trim().match(/^\{(\w+)\}$/)?.[1];
|
||
return list && LIST_PLACEHOLDERS[list] ? LIST_PLACEHOLDERS[list](ctx) : [line];
|
||
})
|
||
.map(line => line.replace(/\{(\w+)\}/g, (m, key) => (!LIST_PLACEHOLDERS[key] && 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 accept the notice before carrying on, and why: 'first' — they never
|
||
* accepted any version (an account made for them by staff, at the door or by someone who
|
||
* registered them, or from before acceptances were recorded); 'updated' — a version marked as a
|
||
* significant change came out after the one they accepted. false when nothing is needed.
|
||
*/
|
||
async function noticePromptPending(user, db = prisma) {
|
||
if (user.noticeVersionAccepted == null) return 'first';
|
||
const required = await requiredVersion(db);
|
||
if (required == null) return false;
|
||
return user.noticeVersionAccepted < required ? 'updated' : false;
|
||
}
|
||
|
||
/**
|
||
* 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,
|
||
BUILT_IN_UPDATES,
|
||
BUILT_IN_REVISION,
|
||
builtInUpdates,
|
||
markBuiltInReviewed,
|
||
revisionLess,
|
||
defaultSections,
|
||
cleanSections,
|
||
noticeContext,
|
||
renderSections,
|
||
operatorLine,
|
||
requiredVersion,
|
||
noticePromptPending,
|
||
publicNotice,
|
||
currentVersion,
|
||
acceptNotice,
|
||
getDraft,
|
||
saveDraft,
|
||
discardDraft,
|
||
publish,
|
||
};
|