diff --git a/app-admin/src/lib/customers.ts b/app-admin/src/lib/customers.ts new file mode 100644 index 0000000..f853d5a --- /dev/null +++ b/app-admin/src/lib/customers.ts @@ -0,0 +1,31 @@ +// Shapes returned by PocketBase's /api/privacy routes (pocketbase/pb_hooks/privacy/lib.js). + +export type CustomerSummary = { + email: string; + name: string; + phone: string; + orders: number; + /** Checkouts started but not paid for. */ + unpaid: number; + lastSeen: string; +}; + +export type CustomerDetails = { name?: string; email?: string; phone?: string; notes?: string }; + +/** Everything stored about one customer; also the GDPR export file. */ +export type CustomerData = { + email: string; + exportedAt: string; + orders: { + id: string; + created: string; + status: string; + total: number; + email: string; + customerDetails: CustomerDetails; + customerEmailSentAt: string; + clientEmailSentAt: string; + lines: { name: string; quantity: number; price: number; start: string }[]; + }[]; + unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[]; +}; diff --git a/app-admin/src/lib/server/customers.ts b/app-admin/src/lib/server/customers.ts new file mode 100644 index 0000000..6e18d8e --- /dev/null +++ b/app-admin/src/lib/server/customers.ts @@ -0,0 +1,24 @@ +// Customer personal data for the /customers page. All reads and writes go +// through PocketBase's /api/privacy routes (orders and baskets are +// superuser-only collections; the hook does the writes). + +import type { createPocketBase } from '$lib/pb'; +import type { CustomerData, CustomerSummary } from '$lib/customers'; + +type Pb = ReturnType; + +export function searchCustomers(pb: Pb, q: string) { + return pb.send<{ customers: CustomerSummary[]; truncated: boolean }>('/api/privacy/customers', { query: { q }, requestKey: null }); +} + +export function loadCustomer(pb: Pb, email: string) { + return pb.send('/api/privacy/customer', { query: { email }, requestKey: null }); +} + +export function updateCustomer(pb: Pb, body: { email: string; name?: string; newEmail?: string; phone?: string; clearNotes?: boolean }) { + return pb.send<{ updated: number; email: string }>('/api/privacy/customer/update', { method: 'POST', body, requestKey: null }); +} + +export function eraseCustomer(pb: Pb, email: string) { + return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); +} diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index 2c0da83..30954ef 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -38,6 +38,7 @@ title: 'Bookings', links: [ { href: '/orders', label: 'Orders' }, + { href: '/customers', label: 'Customers' }, { href: '/slots', label: 'Slots' }, { href: '/items', label: 'Services & products' }, { href: '/calendar', label: 'Events' } diff --git a/app-admin/src/routes/customers/+page.server.ts b/app-admin/src/routes/customers/+page.server.ts new file mode 100644 index 0000000..39fa972 --- /dev/null +++ b/app-admin/src/routes/customers/+page.server.ts @@ -0,0 +1,90 @@ +import { fail, redirect } from '@sveltejs/kit'; +import { ClientResponseError } from 'pocketbase'; +import { attempt } from '$lib/server/actions'; +import { eraseCustomer, loadCustomer, searchCustomers, updateCustomer } from '$lib/server/customers'; +import { defaultPrivacy, type PrivacyGlobal } from '$lib/types'; +import type { Actions, PageServerLoad } from './$types'; + +async function findPrivacyGlobal(pb: App.Locals['pb']) { + try { + return await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key: 'privacy' })); + } catch (e) { + if (e instanceof ClientResponseError && e.status === 404) return null; + throw e; + } +} + +export const load: PageServerLoad = async ({ locals, url }) => { + const q = url.searchParams.get('q')?.trim() ?? ''; + const email = url.searchParams.get('email')?.trim() ?? ''; + const [search, customer, privacy] = await Promise.all([ + searchCustomers(locals.pb, q), + email ? loadCustomer(locals.pb, email) : null, + findPrivacyGlobal(locals.pb) + ]); + const settings: PrivacyGlobal = { ...defaultPrivacy, ...(privacy?.data ?? {}) }; + return { q, ...search, customer, settings }; +}; + +/** Back to the customer just changed, keeping the search. */ +function customerUrl(url: URL, email: string) { + const params = new URLSearchParams(); + const q = url.searchParams.get('q'); + if (q) params.set('q', q); + if (email) params.set('email', email); + return `/customers${params.size ? `?${params}` : ''}`; +} + +const wholeNumber = (value: FormDataEntryValue | null, min: number) => { + const n = Number(value); + return Number.isInteger(n) && n >= min ? n : null; +}; + +export const actions: Actions = { + update: async ({ request, locals, url }) => { + const data = await request.formData(); + const email = String(data.get('email') || ''); + const result = await attempt('Could not save the changes.', () => + updateCustomer(locals.pb, { + email, + name: String(data.get('name') ?? ''), + newEmail: String(data.get('newEmail') ?? ''), + phone: String(data.get('phone') ?? ''), + clearNotes: data.get('clearNotes') === 'on' + }) + ); + if (!result.ok) return result.failure; + // A new email address moves the customer to a new URL. + if (result.value.email !== email.trim().toLowerCase()) redirect(303, customerUrl(url, result.value.email)); + return { ok: true, message: `Saved on ${result.value.updated} record${result.value.updated === 1 ? '' : 's'}.` }; + }, + + erase: async ({ request, locals }) => { + const email = String((await request.formData()).get('email') || ''); + const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email)); + if (!result.ok) return result.failure; + const { ordersAnonymised, basketsDeleted } = result.value; + return { + ok: true, + message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.` + }; + }, + + settings: async ({ request, locals }) => { + const data = await request.formData(); + const abandonedBasketDays = wholeNumber(data.get('abandonedBasketDays'), 1); + const anonymiseOrdersAfterMonths = wholeNumber(data.get('anonymiseOrdersAfterMonths'), 0); + if (abandonedBasketDays === null || anonymiseOrdersAfterMonths === null) { + return fail(400, { settings: true, message: 'Use whole numbers: at least 1 day, and 0 or more months.' }); + } + const value: PrivacyGlobal = { abandonedBasketDays, anonymiseOrdersAfterMonths }; + const result = await attempt('Could not save the retention settings.', async () => { + const existing = await findPrivacyGlobal(locals.pb); + return existing + ? locals.pb.collection('globals').update(existing.id, { data: value }) + : locals.pb.collection('globals').create({ key: 'privacy', data: value }); + }); + if (!result.ok) return fail(400, { settings: true, message: result.failure.data.message }); + return { settings: true, ok: true, message: 'Saved. Applied every night (and when PocketBase starts).' }; + } +}; diff --git a/app-admin/src/routes/customers/+page.svelte b/app-admin/src/routes/customers/+page.svelte new file mode 100644 index 0000000..9c0f8c3 --- /dev/null +++ b/app-admin/src/routes/customers/+page.svelte @@ -0,0 +1,209 @@ + + +Customers | CMS + +{#snippet message(show: boolean)} + {#if show && form?.message} +
{form.message}
+ {/if} +{/snippet} + +
+
+

Customers

+

Personal data from bookings — look someone up to send them a copy, correct it or erase it (GDPR).

+
+ +
+
+

Find a customer

+ + + {#if data.customers.length === 0} +

{data.q ? 'No customer matches.' : 'No customers yet.'}

+ {:else} + + {#if data.truncated} +

Showing customers from the newest orders only — search to narrow it down.

+ {/if} + {/if} +
+ +
+ {#if !customer} +

Pick a customer to see everything stored about them.

+ {:else if !hasRecords} +

{customer.email}

+

Nothing is stored for this email address.

+ {@render message(true)} + {:else} +
+
+

{current.name || customer.email}

+

{customer.email}

+
+ Export data (JSON) +
+ +
+ + + + + {#if hasNotes} + + {/if} +
+ +
+
+ {@render message(!form?.settings)} + +

Orders

+
    + {#each customer.orders as order (order.id)} +
  • +
    + {formatDateTime(order.created, data.timezone)} · {order.status} + {money.format(order.total)} +
    +
      + {#each order.lines as line} +
    • {line.quantity}× {line.name}{line.start ? ` — ${formatDateTime(line.start, data.timezone)}` : ''}
    • + {/each} +
    + {#if order.customerDetails.notes} +

    "{order.customerDetails.notes}"

    + {/if} +
  • + {/each} +
+ + {#if customer.unpaidBaskets.length} +

Unpaid checkouts

+

Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.

+
    + {#each customer.unpaidBaskets as basket (basket.id)} +
  • {formatDateTime(basket.updated, data.timezone)} — {basket.customerDetails.name || '(no name)'}{basket.customerDetails.phone ? ` · ${basket.customerDetails.phone}` : ''}
  • + {/each} +
+ {/if} + +
+

Erase this customer

+

+ For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts) and deletes unpaid checkouts. + Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services. +

+ {#if upcoming.length} +

They have {upcoming.length} upcoming booking{upcoming.length === 1 ? '' : 's'}.

+ {/if} +
+ + +
+
+ {/if} +
+
+ +
+

Data retention

+

Applied automatically every night. Check how long your accountant needs booking records before turning on anonymising.

+
+ + +
+ + {@render message(!!form?.settings)} +
+
diff --git a/app-admin/src/routes/customers/export/+server.ts b/app-admin/src/routes/customers/export/+server.ts new file mode 100644 index 0000000..be0b7af --- /dev/null +++ b/app-admin/src/routes/customers/export/+server.ts @@ -0,0 +1,20 @@ +import { error } from '@sveltejs/kit'; +import { loadCustomer } from '$lib/server/customers'; +import type { RequestHandler } from './$types'; + +// A customer's data as a JSON file — what to send someone who asks for a +// copy of their data (GDPR access / portability). Auth-guarded like every +// admin route (hooks.server.ts). +export const GET: RequestHandler = async ({ locals, url }) => { + const email = url.searchParams.get('email')?.trim() ?? ''; + if (!email) error(400, 'Missing email'); + const data = await loadCustomer(locals.pb, email); + const name = email.replace(/[^a-z0-9@._-]+/gi, '_'); + return new Response(JSON.stringify(data, null, 2), { + headers: { + 'content-type': 'application/json; charset=utf-8', + 'content-disposition': `attachment; filename="customer-data-${name}.json"`, + 'cache-control': 'no-store' + } + }); +}; diff --git a/app-admin/src/routes/orders/+page.server.ts b/app-admin/src/routes/orders/+page.server.ts index 34df546..2d4d6a1 100644 --- a/app-admin/src/routes/orders/+page.server.ts +++ b/app-admin/src/routes/orders/+page.server.ts @@ -32,6 +32,7 @@ export const load: PageServerLoad = async ({ locals }) => { customerEmailSentAt: String(record.customerEmailSentAt || ''), clientEmailSentAt: String(record.clientEmailSentAt || ''), emailError: String(record.emailError || ''), + anonymisedAt: String(record.anonymisedAt || ''), lines: (linesByOrder.get(record.id) ?? []).map((line) => ({ id: line.id, name: String(line.name || ''), diff --git a/app-admin/src/routes/orders/+page.svelte b/app-admin/src/routes/orders/+page.svelte index 07621b1..a59e0d0 100644 --- a/app-admin/src/routes/orders/+page.svelte +++ b/app-admin/src/routes/orders/+page.svelte @@ -49,9 +49,9 @@
-

{order.customerDetails?.name || order.email || 'Order'}

+

{order.anonymisedAt ? 'Anonymised customer' : order.customerDetails?.name || order.email || 'Order'}

- {order.email} + {#if order.email}{order.email}{/if} {#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if} {#if order.created} · {formatDateTime(order.created, data.timezone)}{/if}

@@ -82,10 +82,12 @@

"{order.customerDetails.notes}"

{/if} -
- {@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)} - {@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)} -
+ {#if !order.anonymisedAt} +
+ {@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)} + {@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)} +
+ {/if} {#if order.emailError}

{order.emailError}

{/if} diff --git a/pb_schema.json b/pb_schema.json index 9d4a987..f2d9e40 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -434,7 +434,7 @@ "fields": [ { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, - { "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, + { "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, { "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, { "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] }, @@ -442,11 +442,13 @@ { "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, + { "id": "date_ordanonym01", "name": "anonymisedAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ - "CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)" + "CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)", + "CREATE INDEX `idx_orders_email` ON `orders` (`email`)" ], "autodate": true, "options": {} diff --git a/pocketbase/pb_hooks/privacy.pb.js b/pocketbase/pb_hooks/privacy.pb.js new file mode 100644 index 0000000..30a3279 --- /dev/null +++ b/pocketbase/pb_hooks/privacy.pb.js @@ -0,0 +1,47 @@ +/// Customer personal data (GDPR) — see privacy/lib.js. Every route is for +/// the signed-in admin only (`users` has no public sign-up). + +routerAdd('GET', '/api/privacy/customers', (e) => { + const privacy = require(`${__hooks}/privacy/lib.js`); + privacy.requireAdmin(e); + return e.json(200, privacy.searchCustomers($app, e.request.url.query().get('q'))); +}); + +routerAdd('GET', '/api/privacy/customer', (e) => { + const privacy = require(`${__hooks}/privacy/lib.js`); + privacy.requireAdmin(e); + return e.json(200, privacy.customerData($app, e.request.url.query().get('email'))); +}); + +routerAdd('POST', '/api/privacy/customer/update', (e) => { + const privacy = require(`${__hooks}/privacy/lib.js`); + privacy.requireAdmin(e); + return e.json(200, privacy.updateCustomer($app, e.requestInfo().body)); +}); + +routerAdd('POST', '/api/privacy/customer/erase', (e) => { + const privacy = require(`${__hooks}/privacy/lib.js`); + privacy.requireAdmin(e); + return e.json(200, privacy.eraseCustomer($app, e.requestInfo().body)); +}); + +routerAdd('GET', '/api/privacy/settings', (e) => { + const privacy = require(`${__hooks}/privacy/lib.js`); + privacy.requireAdmin(e); + return e.json(200, privacy.settings($app)); +}); + +// Delete unpaid baskets and anonymise old orders, per the `privacy` global. +cronAdd('privacyRetention', '15 3 * * *', () => { + require(`${__hooks}/privacy/lib.js`).applyRetention($app); +}); + +// Also once at startup, so a box that is down at 03:15 still catches up. +onBootstrap((e) => { + e.next(); + try { + require(`${__hooks}/privacy/lib.js`).applyRetention($app); + } catch (err) { + console.error('[privacy] retention at startup failed:', err); + } +}); diff --git a/pocketbase/pb_hooks/privacy/lib.js b/pocketbase/pb_hooks/privacy/lib.js new file mode 100644 index 0000000..451841f --- /dev/null +++ b/pocketbase/pb_hooks/privacy/lib.js @@ -0,0 +1,271 @@ +// Customer personal data (GDPR), run inside PocketBase (JSVM). Routes and +// the daily retention cron are registered in ../privacy.pb.js; see the +// JSVM notes at the top of ../shop/lib.js. +// +// Where a customer's details live: +// - orders.email + orders.customerDetails ({ name, email, phone, notes }) — +// one copy per order; the order itself (amount, services, dates) is kept +// for the accounts, so "erase" anonymises it instead of deleting it. +// - baskets.email + baskets.customerDetails — set when checkout starts. A +// paid basket's copy is cleared once the order exists; a basket that was +// never paid for is deleted after `abandonedBasketDays`. +// Outside this database: Stripe (receipt email, payment) and the email +// provider's send logs. Those are handled in their own dashboards. + +const DAY_MS = 24 * 60 * 60 * 1000; +const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; + +/** Defaults for the `privacy` global (edited in the admin's Customers page). */ +const DEFAULT_SETTINGS = { + /** Unpaid baskets — with whatever details were typed at checkout — are deleted after this. */ + abandonedBasketDays: 30, + /** Orders are anonymised this long after they were placed; 0 = keep until erased by hand. */ + anonymiseOrdersAfterMonths: 0 +}; + +/** How many orders a customer search looks at (newest first). */ +const SEARCH_LIMIT = 500; + +/** Route guard: only a signed-in admin may see or change customer data. */ +function requireAdmin(e) { + if (!e.auth) throw new UnauthorizedError('Sign in to manage customer data'); +} + +function pbDate(ms) { + return new Date(ms).toISOString().replace('T', ' '); +} + +function plain(record) { + return JSON.parse(JSON.stringify(record)); +} + +function details(record) { + return JSON.parse(toString(record.get('customerDetails')) || 'null') || {}; +} + +function normaliseEmail(value) { + return String(value || '').trim().toLowerCase(); +} + +function settings(app) { + let data = null; + try { + data = plain(app.findFirstRecordByFilter('globals', "key = 'privacy'")).data; + } catch (_) { + // Not saved yet — defaults. + } + const days = Number(data && data.abandonedBasketDays); + const months = Number(data && data.anonymiseOrdersAfterMonths); + return { + abandonedBasketDays: days >= 1 ? Math.floor(days) : DEFAULT_SETTINGS.abandonedBasketDays, + anonymiseOrdersAfterMonths: months >= 0 ? Math.floor(months) : DEFAULT_SETTINGS.anonymiseOrdersAfterMonths + }; +} + +/** Orders and unpaid baskets whose email is `email` (case-insensitive, exact). */ +function customerRecords(app, email) { + const wanted = normaliseEmail(email); + if (!wanted) return { orders: [], baskets: [] }; + // `~` is a case-insensitive LIKE, but also a substring match (and `_` is a + // wildcard), so narrow it to the exact address here. + const same = (record) => normaliseEmail(record.getString('email')) === wanted; + return { + orders: app.findRecordsByFilter('orders', 'email ~ {:email}', '-created', 0, 0, { email: wanted }).filter(same), + baskets: app.findRecordsByFilter('baskets', "email ~ {:email} && status != 'completed'", '-updated', 0, 0, { email: wanted }).filter(same) + }; +} + +function hasUpcomingBooking(app, orderId) { + return app.findRecordsByFilter('order_lines', "order = {:order} && lineType = 'slot' && start > {:now}", '', 1, 0, { order: orderId, now: pbDate(Date.now()) }).length > 0; +} + +function anonymiseOrder(app, order) { + order.set('email', ''); + order.set('customerDetails', {}); + order.set('emailError', ''); // SMTP errors often quote the address + order.set('anonymisedAt', new Date().toISOString()); + app.save(order); +} + +function clearBasketDetails(app, basket) { + basket.set('email', ''); + basket.set('customerDetails', null); + app.save(basket); +} + +// ── Retention (daily cron) ────────────────────────────────────────────── + +function applyRetention(app) { + const { abandonedBasketDays, anonymiseOrdersAfterMonths } = settings(app); + const counts = { basketsDeleted: 0, basketsCleared: 0, ordersAnonymised: 0 }; + + // Unpaid baskets (their lines cascade). Active ones expire after a day + // and are swept to `abandoned`, so `updated` is when they were last used. + const basketCutoff = pbDate(Date.now() - abandonedBasketDays * DAY_MS); + for (const basket of app.findRecordsByFilter('baskets', "status != 'completed' && updated < {:cutoff}", '', 0, 0, { cutoff: basketCutoff })) { + try { + app.delete(basket); + counts.basketsDeleted++; + } catch (e) { + console.error('[privacy] could not delete basket', basket.id, e); + } + } + + // Paid baskets: the order has its own copy of the details. + for (const basket of app.findRecordsByFilter('baskets', "status = 'completed' && email != ''", '', 0, 0)) { + try { + clearBasketDetails(app, basket); + counts.basketsCleared++; + } catch (e) { + console.error('[privacy] could not clear basket', basket.id, e); + } + } + + if (anonymiseOrdersAfterMonths > 0) { + const cutoff = new Date(); + cutoff.setUTCMonth(cutoff.getUTCMonth() - anonymiseOrdersAfterMonths); + for (const order of app.findRecordsByFilter('orders', "anonymisedAt = '' && created < {:cutoff}", '', 0, 0, { cutoff: pbDate(cutoff.getTime()) })) { + // An old order can still have a booking ahead (booked far in advance). + if (hasUpcomingBooking(app, order.id)) continue; + try { + anonymiseOrder(app, order); + counts.ordersAnonymised++; + } catch (e) { + console.error('[privacy] could not anonymise order', order.id, e); + } + } + } + + if (counts.basketsDeleted || counts.basketsCleared || counts.ordersAnonymised) { + console.log('[privacy] retention:', JSON.stringify(counts)); + } + return counts; +} + +// ── Admin: find, export, correct, erase ───────────────────────────────── + +/** + * Customers whose email, name, phone or notes contain `query`, grouped by + * email — from orders and from unpaid checkouts (someone who never paid can + * still ask what we hold about them). + */ +function searchCustomers(app, query) { + const q = String(query || '').trim(); + const match = q ? ' && (email ~ {:q} || customerDetails ~ {:q})' : ''; + const orders = app.findRecordsByFilter('orders', "email != ''" + match, '-created', SEARCH_LIMIT, 0, { q }); + const baskets = app.findRecordsByFilter('baskets', "email != '' && status != 'completed'" + match, '-updated', SEARCH_LIMIT, 0, { q }); + const byEmail = new Map(); + const add = (record, date, isOrder) => { + const email = normaliseEmail(record.getString('email')); + let found = byEmail.get(email); + if (!found) { + // Records come newest first, so the first one seen has the current details. + const d = details(record); + found = { email, name: String(d.name || ''), phone: String(d.phone || ''), orders: 0, unpaid: 0, lastSeen: date }; + byEmail.set(email, found); + } + if (isOrder) found.orders++; + else found.unpaid++; + if (date > found.lastSeen) found.lastSeen = date; + }; + for (const order of orders) add(order, order.getString('created'), true); + for (const basket of baskets) add(basket, basket.getString('updated'), false); + const customers = [...byEmail.values()].sort((a, b) => (a.lastSeen < b.lastSeen ? 1 : -1)); + return { customers, truncated: orders.length === SEARCH_LIMIT || baskets.length === SEARCH_LIMIT }; +} + +/** Everything stored about one customer — the admin's detail view and the GDPR export. */ +function customerData(app, email) { + const { orders, baskets } = customerRecords(app, email); + return { + email: normaliseEmail(email), + exportedAt: new Date().toISOString(), + orders: orders.map((order) => { + const lines = app.findRecordsByFilter('order_lines', 'order = {:order}', 'start', 0, 0, { order: order.id }); + return { + id: order.id, + created: order.getString('created'), + status: order.getString('status'), + total: order.getFloat('total'), + email: order.getString('email'), + customerDetails: details(order), + customerEmailSentAt: order.getString('customerEmailSentAt'), + clientEmailSentAt: order.getString('clientEmailSentAt'), + lines: lines.map((line) => ({ + name: line.getString('name'), + quantity: line.getInt('quantity'), + price: line.getFloat('price'), + start: line.getString('start') + })) + }; + }), + // Checkouts that were started but never paid for. + unpaidBaskets: baskets.map((basket) => ({ + id: basket.id, + updated: basket.getString('updated'), + status: basket.getString('status'), + customerDetails: details(basket) + })) + }; +} + +/** + * Correct a customer's details on every order and unpaid basket. + * `body`: { email, name?, newEmail?, phone?, clearNotes? } — omitted fields are left alone. + */ +function updateCustomer(app, body) { + const email = normaliseEmail(body.email); + const patch = {}; + if (body.name !== undefined) { + patch.name = String(body.name).trim(); + if (!patch.name) throw new BadRequestError('Name cannot be empty'); + } + if (body.newEmail !== undefined) { + patch.email = String(body.newEmail).trim(); + if (!EMAIL_PATTERN.test(patch.email)) throw new BadRequestError('That email address is not valid'); + } + if (body.phone !== undefined) patch.phone = String(body.phone).trim(); + if (body.clearNotes) patch.notes = ''; + + let updated = 0; + app.runInTransaction((tx) => { + const { orders, baskets } = customerRecords(tx, email); + if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email'); + for (const record of [...orders, ...baskets]) { + record.set('customerDetails', Object.assign(details(record), patch)); + if (patch.email) record.set('email', patch.email); + tx.save(record); + updated++; + } + }); + return { updated, email: patch.email ? normaliseEmail(patch.email) : email }; +} + +/** Right to erasure: anonymise the customer's orders and delete their unpaid baskets. */ +function eraseCustomer(app, body) { + const counts = { ordersAnonymised: 0, basketsDeleted: 0 }; + app.runInTransaction((tx) => { + const { orders, baskets } = customerRecords(tx, body.email); + if (!orders.length && !baskets.length) throw new NotFoundError('No customer with that email'); + for (const order of orders) { + anonymiseOrder(tx, order); + counts.ordersAnonymised++; + } + for (const basket of baskets) { + tx.delete(basket); + counts.basketsDeleted++; + } + }); + return counts; +} + +module.exports = { + requireAdmin, + DEFAULT_SETTINGS, + settings, + applyRetention, + searchCustomers, + customerData, + updateCustomer, + eraseCustomer +}; diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index 640dea6..dc68283 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -629,6 +629,9 @@ function createOrderFromIntent(app, intent) { // Basket done — order_lines hold the snapshot. for (const line of lines) tx.delete(line); basket.set('status', 'completed'); + // The order now holds the customer's details; keep only that copy. + basket.set('email', ''); + basket.set('customerDetails', null); tx.save(basket); orderId = order.id; }); diff --git a/pocketbase/pb_migrations/1793000000_orders_anonymise.js b/pocketbase/pb_migrations/1793000000_orders_anonymise.js new file mode 100644 index 0000000..fb894b1 --- /dev/null +++ b/pocketbase/pb_migrations/1793000000_orders_anonymise.js @@ -0,0 +1,40 @@ +/// + +// GDPR erasure keeps an order (amounts, services, dates — needed for the +// accounts) but strips who it was for. See pb_hooks/privacy/lib.js. +// +// 1. orders.email no longer required: an anonymised order has none. +// 2. orders.anonymisedAt: when the personal details were removed. +// 3. Index orders.email, for looking a customer up in the admin. + +function find(app, name) { + try { + return app.findCollectionByNameOrId(name); + } catch (e) { + return null; // fresh install: pb_schema.json (already in this shape) is imported later + } +} + +migrate( + (app) => { + const orders = find(app, 'orders'); + if (!orders) return; + const email = orders.fields.getByName('email'); + if (email) email.required = false; + if (!orders.fields.getByName('anonymisedAt')) { + orders.fields.add(new DateField({ id: 'date_ordanonym01', name: 'anonymisedAt' })); + } + if (!orders.indexes.some((index) => index.includes('idx_orders_email'))) { + orders.indexes = [...orders.indexes, 'CREATE INDEX `idx_orders_email` ON `orders` (`email`)']; + } + app.save(orders); + }, + (app) => { + // Anonymised orders have an empty email, so `required` is not restored. + const orders = find(app, 'orders'); + if (!orders) return; + if (orders.fields.getByName('anonymisedAt')) orders.fields.removeByName('anonymisedAt'); + orders.indexes = orders.indexes.filter((index) => !index.includes('idx_orders_email')); + app.save(orders); + } +);