From 73e8c5dc5d5adc776c7b867c097cb691987f496e Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 10:44:45 +0000 Subject: [PATCH 1/4] No third-party requests on page load: bundle the fonts, load Stripe.js at Pay Google Fonts and Stripe.js (imported from @stripe/stripe-js, which injects the script on import) sent every visitor's IP address to Google and Stripe on every page. Fonts now come from @fontsource packages bundled into each app; Stripe.js loads from the 'pure' entry point, only when the customer presses Pay. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- app-admin/package-lock.json | 22 ++++++++++++++++++++++ app-admin/package.json | 2 ++ app-admin/src/app.css | 1 - app-admin/src/routes/+layout.svelte | 8 ++++++++ app-public/package-lock.json | 22 ++++++++++++++++++++++ app-public/package.json | 2 ++ app-public/src/app.css | 1 - app-public/src/routes/+layout.svelte | 8 ++++++++ packages/shared/src/stripe-client.ts | 5 ++++- 9 files changed, 68 insertions(+), 3 deletions(-) diff --git a/app-admin/package-lock.json b/app-admin/package-lock.json index 85cdb4e..d0e5f0e 100644 --- a/app-admin/package-lock.json +++ b/app-admin/package-lock.json @@ -26,6 +26,8 @@ "uuid": "^14.0.0" }, "devDependencies": { + "@fontsource/dm-sans": "^5.3.0", + "@fontsource/playfair-display": "^5.3.0", "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", @@ -118,6 +120,26 @@ "license": "MIT", "peer": true }, + "node_modules/@fontsource/dm-sans": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/dm-sans/-/dm-sans-5.3.0.tgz", + "integrity": "sha512-lYJtMXXO28q1z+yz+z8XKd0s4hXaa9QdkETzkyD760sidCv5heI86weYA0sx0Nc4pAMAQTUuyf4gO44cYKKS9g==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/playfair-display": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/playfair-display/-/playfair-display-5.3.0.tgz", + "integrity": "sha512-uJSABalvdWc10fEPppQjQocamT21LEyRfzzWfRfqbkPz+sRv+kKpYDKyluBUskvJREkJTos9epj1WjQROGu99Q==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", diff --git a/app-admin/package.json b/app-admin/package.json index f2205ab..4d1be42 100644 --- a/app-admin/package.json +++ b/app-admin/package.json @@ -10,6 +10,8 @@ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" }, "devDependencies": { + "@fontsource/dm-sans": "^5.3.0", + "@fontsource/playfair-display": "^5.3.0", "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", diff --git a/app-admin/src/app.css b/app-admin/src/app.css index d0de454..811e139 100644 --- a/app-admin/src/app.css +++ b/app-admin/src/app.css @@ -1,4 +1,3 @@ -@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap'); @import 'tailwindcss'; @plugin 'daisyui' { themes: light --default; diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index ab5f4a6..2c0da83 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -1,5 +1,13 @@ + +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); + } +); From 0b3f8eababde3ed3172c6bf942247c78a0115171 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 10:44:45 +0000 Subject: [PATCH 4/4] =?UTF-8?q?Docs:=20personal=20data=20(GDPR)=20?= =?UTF-8?q?=E2=80=94=20what=20is=20stored,=20the=20customer=20tools,=20ret?= =?UTF-8?q?ention?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- AGENTS.md | 2 ++ README.md | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 12a2b43..30f842e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,7 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── orders/ # Order list + booking-email status/resend +│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings │ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── backup/ # Export/import UI (calls api/export, api/import) @@ -131,6 +132,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. - **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. - **Slot availability** (places + blocking by overlapping bookings, incl. get-ready time) is computed only by `slotStates()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots`, `?detail=1` for the admin). Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*. +- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email` and (during checkout) `baskets`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*. - **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only). ### Styling diff --git a/README.md b/README.md index 19a75e0..6784ea9 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ Commerce collections (see the Stripe section above for context): - `slots` — `item` relation→items, `start` date, `end` date, `capacity` number (places; >1 = group session), `notes` text. Nothing about bookings is stored here — see *Slot availability* below - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text - `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `heldUntil` date (a slot line's hold) -- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text +- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty) - `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot) - `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool @@ -140,6 +140,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - `/items` — services and products shown in Shop blocks - `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions. - `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons +- `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) - `/globals` — header/footer/colors editor @@ -189,6 +190,18 @@ Setup: With `SMTP_HOST` empty (local dev) emails are written to the app container logs instead of being sent. +## Personal data (GDPR) + +What the software does; the studio (the controller) is responsible for the privacy policy text and for how it uses the data. + +- **What is stored:** name, email, phone and booking notes, on `orders.customerDetails` (one copy per order) and on `baskets` while checkout is in progress. A paid basket's copy is cleared as soon as its order exists. +- **Privacy policy:** *Site design → Footer → Privacy policy page* links a page from the footer and above the Pay button. *Create a privacy policy draft* makes an unpublished `privacy` page describing what this software does, with [gaps] to fill in. +- **Checkout:** a short privacy notice with the link, and a hint under the notes field asking customers not to write health details (special-category data). There is deliberately no "I consent" box: booking data is processed to perform the contract, not on consent. Both texts are editable in the Checkout block. +- **Customers (admin):** look a customer up by name, email, phone or notes (orders and unpaid checkouts, matched by email case-insensitively); *Export data (JSON)* for access/portability requests; correct name/email/phone or remove notes on every record; *Erase* anonymises their orders (amounts, services and dates stay for the accounts) and deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards. +- **Retention:** daily at 03:15 UTC and on PocketBase start (`pocketbase/pb_hooks/privacy.pb.js`): unpaid checkouts are deleted after *N* days (default 30); orders are anonymised after *M* months (default 0 = never — set it once the accountant has said how long records must be kept). Orders with a booking still ahead are skipped. Settings live in the `privacy` global. +- **No third parties on page load:** fonts are bundled (`@fontsource/*`), not loaded from Google, and Stripe.js loads only when the customer presses Pay (`@stripe/stripe-js/pure`). The only cookies are the basket cookie and the admin login, so no cookie banner is needed — keep it that way, or add one before adding analytics. +- All customer-data reads and writes go through `/api/privacy/*` (signed-in admin only; `orders`/`baskets` are superuser-only collections). + ## Public routes (public app) - `/` renders `pages.slug = "home"`