Compare commits

...

4 commits

Author SHA1 Message Date
0b3f8eabab Docs: personal data (GDPR) — what is stored, the customer tools, retention
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 10:44:45 +00:00
971efebcdb Customers page: export, correct and erase personal data; automatic retention
Admin /customers finds a customer by name, email, phone or notes (orders and unpaid checkouts), exports everything stored as JSON, corrects details on every record, and erases them — anonymising orders (amounts, services and dates stay for the accounts) and deleting unpaid checkouts. A daily cron (and PocketBase start) deletes unpaid checkouts after N days and, when set, anonymises orders after M months, skipping orders with a booking ahead. A paid basket's copy of the details is cleared when its order is created. All writes are in pocketbase/pb_hooks/privacy (orders and baskets are superuser-only); migration 1793000000 makes orders.email optional and adds orders.anonymisedAt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 10:44:45 +00:00
5828d65a00 Privacy policy link in the footer and checkout, notes hint, and a policy draft
Site design → Footer picks the privacy policy page; it is linked from the footer and from a short notice above Pay. The notes field asks customers not to write health details (special-category data). 'Create a privacy policy draft' makes an unpublished page describing what this software does with customer data, with gaps for the studio to fill in. No consent checkbox: booking data is processed to perform the contract. Also adds the PrivacyGlobal type used by the retention settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 10:44:45 +00:00
73e8c5dc5d 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 10:44:45 +00:00
30 changed files with 962 additions and 17 deletions

View file

@ -31,6 +31,7 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── 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) │ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
│ │ ├── backup/ # Export/import UI (calls api/export, api/import) │ │ ├── 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. - **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. - **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*. - **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). - **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 ### Styling

View file

@ -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 - `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 - `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) - `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) - `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 - `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 - `/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. - `/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 - `/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) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
- `/globals` — header/footer/colors editor - `/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. 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) ## Public routes (public app)
- `/` renders `pages.slug = "home"` - `/` renders `pages.slug = "home"`

View file

@ -26,6 +26,8 @@
"uuid": "^14.0.0" "uuid": "^14.0.0"
}, },
"devDependencies": { "devDependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -118,6 +120,26 @@
"license": "MIT", "license": "MIT",
"peer": true "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": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",

View file

@ -10,6 +10,8 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}, },
"devDependencies": { "devDependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",

View file

@ -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'; @import 'tailwindcss';
@plugin 'daisyui' { @plugin 'daisyui' {
themes: light --default; themes: light --default;

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import type { ContentBlock, CheckoutBlockData } from '$lib/types'; import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type ContentBlock, type CheckoutBlockData } from '$lib/types';
let { let {
block, block,
@ -27,5 +27,15 @@
<span class="fieldset-legend">Notes label</span> <span class="fieldset-legend">Notes label</span>
<input class="input w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} /> <input class="input w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} />
</label> </label>
<label class="fieldset">
<span class="fieldset-legend">Notes hint</span>
<textarea class="textarea w-full" rows="2" placeholder={DEFAULT_NOTES_HINT} value={block.data.notesHint || ''} oninput={(e) => updateData({ notesHint: e.currentTarget.value })}></textarea>
<span class="label whitespace-normal">Shown under the notes field. Health details are sensitive data under GDPR — keep asking for them in person unless you have a lawful basis to collect them online.</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Privacy notice</span>
<textarea class="textarea w-full" rows="2" placeholder={DEFAULT_PRIVACY_NOTICE} value={block.data.privacyNotice || ''} oninput={(e) => updateData({ privacyNotice: e.currentTarget.value })}></textarea>
<span class="label whitespace-normal">Shown above the Pay button, followed by a link to the privacy policy page chosen in Site design → Footer.</span>
</label>
<p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p> <p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p>
</div> </div>

View file

@ -0,0 +1,42 @@
// Starting text for the privacy policy page (Site design → Footer → "Create
// a draft"). It describes what this software does with customer data; the
// studio fills in the [bracketed] parts and stays responsible for the
// content being accurate. Keep it in step with pocketbase/pb_hooks/privacy.
export const PRIVACY_PAGE_SLUG = 'privacy';
export const privacyTemplateHtml = `<h2>Privacy policy</h2>
<p><em>Last updated: [date]</em></p>
<h3>Who we are</h3>
<p>[Business name], [address], [company registration number if any] is responsible for your personal data. Contact: [email].</p>
<h3>What we collect and why</h3>
<p>When you book or buy something on this website we collect your <strong>name, email address, phone number</strong> (optional) and any <strong>notes</strong> you add. We use them to arrange your appointment, send your confirmation and contact you about your booking. The legal basis is the performance of our contract with you (Article 6(1)(b) GDPR). We keep a record of your order (what you booked, when and the amount paid) because accounting law requires it (Article 6(1)(c)).</p>
<p>Please do not write health information in the booking notes. We ask about anything relevant in person at your appointment.</p>
<h3>Payments</h3>
<p>Card payments are handled by Stripe. We never see or store your card details. Stripe processes your payment and email address under its own privacy policy: <a href="https://stripe.com/privacy">stripe.com/privacy</a>.</p>
<h3>Who else processes your data</h3>
<ul>
<li>[Hosting provider, country] — hosts this website and its database.</li>
<li>Stripe — payment processing.</li>
<li>[Email provider, e.g. Brevo] — sends booking confirmations.</li>
<li>[Google Calendar — if bookings are added to our calendar: which details]</li>
</ul>
<p>We do not sell your data or use it for advertising.</p>
<h3>How long we keep it</h3>
<ul>
<li>Details entered at checkout without completing payment: deleted after [30] days.</li>
<li>Orders: your contact details are removed [after N months / when you ask]; the order record without them is kept for [N] years as required for our accounts.</li>
<li>Server logs (including IP addresses): [a few] days.</li>
</ul>
<h3>Cookies</h3>
<p>This website uses only cookies that are needed for it to work: one that remembers your basket while you book (deleted after checkout), and the payment form's own cookies set by Stripe to prevent fraud. We do not use analytics or advertising cookies. The site's fonts are served from our own server.</p>
<h3>Your rights</h3>
<p>You can ask us for a copy of your data, to correct it, to delete it, to restrict or object to how we use it, or to receive it in a portable format. Email [email] and we will reply within one month. Where we must keep an order for accounting, we remove your contact details from it instead of deleting it.</p>
<p>You can also complain to a data protection authority — [e.g. the Office for Personal Data Protection (ÚOOÚ), www.uoou.cz].</p>`;

View file

@ -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 }[];
};

View file

@ -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<typeof createPocketBase>;
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<CustomerData>('/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 });
}

View file

@ -1,5 +1,13 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
// Fonts are bundled and served by this app, not loaded from Google: a
// Google Fonts request sends every visitor's IP address to Google (GDPR).
import '@fontsource/dm-sans/400.css';
import '@fontsource/dm-sans/500.css';
import '@fontsource/dm-sans/600.css';
import '@fontsource/dm-sans/700.css';
import '@fontsource/playfair-display/600.css';
import '@fontsource/playfair-display/700.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import { afterNavigate } from '$app/navigation'; import { afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
@ -30,6 +38,7 @@
title: 'Bookings', title: 'Bookings',
links: [ links: [
{ href: '/orders', label: 'Orders' }, { href: '/orders', label: 'Orders' },
{ href: '/customers', label: 'Customers' },
{ href: '/slots', label: 'Slots' }, { href: '/slots', label: 'Slots' },
{ href: '/items', label: 'Services & products' }, { href: '/items', label: 'Services & products' },
{ href: '/calendar', label: 'Events' } { href: '/calendar', label: 'Events' }

View file

@ -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).' };
}
};

View file

@ -0,0 +1,209 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { page } from '$app/state';
import { confirmSubmit } from '$lib/admin/confirm';
import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar';
let { data, form } = $props();
let customer = $derived(data.customer);
let saving = $state('');
let money = $derived(new Intl.NumberFormat(DISPLAY_LOCALE, { style: 'currency', currency: data.currency }));
// The newest order's details are the current ones (unpaid checkouts can be newer still).
let current = $derived(customer?.orders[0]?.customerDetails ?? customer?.unpaidBaskets[0]?.customerDetails ?? {});
let hasRecords = $derived(!!customer && (customer.orders.length > 0 || customer.unpaidBaskets.length > 0));
let hasNotes = $derived(!!customer?.orders.some((order) => order.customerDetails.notes) || !!customer?.unpaidBaskets.some((basket) => basket.customerDetails.notes));
let upcoming = $derived(
customer?.orders.flatMap((order) => order.lines).filter((line) => line.start && new Date(line.start.replace(' ', 'T')).getTime() > Date.now()) ?? []
);
const customerHref = (email: string) => {
const params = new URLSearchParams(page.url.searchParams);
params.set('email', email);
return `?${params}`;
};
const submitting = (name: string) => () => {
saving = name;
return async ({ update }: { update: (options?: { reset?: boolean }) => Promise<void> }) => {
await update({ reset: false });
saving = '';
};
};
const eraseMessage = $derived(
`Erase ${customer?.email}?\n\n` +
(upcoming.length ? `They still have ${upcoming.length} upcoming booking${upcoming.length === 1 ? '' : 's'} — you won't be able to contact them about it.\n\n` : '') +
'Their name, email, phone and notes are removed from every order (amounts, services and dates stay for your accounts), and unpaid checkouts are deleted. This cannot be undone.'
);
</script>
<svelte:head><title>Customers | CMS</title></svelte:head>
{#snippet message(show: boolean)}
{#if show && form?.message}
<div class="alert mt-4 py-2 text-sm" class:alert-success={form.ok} class:alert-error={!form.ok} role="status">{form.message}</div>
{/if}
{/snippet}
<div class="space-y-6">
<div>
<h1 class="text-3xl font-bold">Customers</h1>
<p class="text-base-content/60">Personal data from bookings — look someone up to send them a copy, correct it or erase it (GDPR).</p>
</div>
<div class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]">
<section class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">Find a customer</h2>
<form method="GET" class="flex gap-2" role="search">
<input class="input w-full" type="search" name="q" value={data.q} placeholder="Name, email, phone or notes" aria-label="Search customers" />
<button class="btn btn-primary" type="submit">Search</button>
</form>
{#if data.customers.length === 0}
<p class="mt-6 text-base-content/60">{data.q ? 'No customer matches.' : 'No customers yet.'}</p>
{:else}
<ul class="mt-4 divide-y divide-base-300">
{#each data.customers as row (row.email)}
<li>
<a
class="flex items-center justify-between gap-3 rounded px-2 py-3 hover:bg-base-200 {customer?.email === row.email ? 'bg-primary/20 shadow-[inset_3px_0_0_var(--color-primary)]' : ''}"
href={customerHref(row.email)}
aria-current={customer?.email === row.email ? 'true' : undefined}
>
<span class="min-w-0">
<span class="block truncate font-semibold">{row.name || row.email}</span>
<span class="block truncate text-sm text-base-content/60">{row.email}{row.phone ? ` · ${row.phone}` : ''}</span>
</span>
<span class="shrink-0 text-right text-sm text-base-content/60">
{row.orders ? `${row.orders} order${row.orders === 1 ? '' : 's'}` : 'Unpaid checkout only'}<br />{formatDateTime(row.lastSeen, data.timezone)}
</span>
</a>
</li>
{/each}
</ul>
{#if data.truncated}
<p class="mt-3 text-sm text-base-content/60">Showing customers from the newest orders only — search to narrow it down.</p>
{/if}
{/if}
</section>
<section class="rounded-box bg-base-100 p-5 shadow">
{#if !customer}
<p class="text-base-content/60">Pick a customer to see everything stored about them.</p>
{:else if !hasRecords}
<h2 class="text-2xl font-bold">{customer.email}</h2>
<p class="mt-2 text-base-content/60">Nothing is stored for this email address.</p>
{@render message(true)}
{:else}
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 class="text-2xl font-bold">{current.name || customer.email}</h2>
<p class="text-sm text-base-content/60">{customer.email}</p>
</div>
<a class="btn btn-sm" href={`/customers/export?email=${encodeURIComponent(customer.email)}`} download>Export data (JSON)</a>
</div>
<form class="mt-4 grid gap-x-4 sm:grid-cols-3" method="POST" action="?/update" use:enhance={submitting('update')}>
<input type="hidden" name="email" value={customer.email} />
<label class="fieldset">
<span class="fieldset-legend">Name</span>
<input class="input w-full" name="name" value={current.name ?? ''} required />
</label>
<label class="fieldset">
<span class="fieldset-legend">Email</span>
<input class="input w-full" type="email" name="newEmail" value={customer.email} required />
</label>
<label class="fieldset">
<span class="fieldset-legend">Phone</span>
<input class="input w-full" type="tel" name="phone" value={current.phone ?? ''} />
</label>
{#if hasNotes}
<label class="label mt-2 cursor-pointer gap-2 sm:col-span-3">
<input class="checkbox checkbox-sm" type="checkbox" name="clearNotes" />
Remove their booking notes
</label>
{/if}
<div class="mt-3 sm:col-span-3">
<button class="btn btn-primary" type="submit" disabled={saving !== ''}>
{#if saving === 'update'}<span class="loading loading-spinner loading-sm"></span>{/if}
Save on all their orders
</button>
</div>
</form>
{@render message(!form?.settings)}
<h3 class="mt-6 font-bold">Orders</h3>
<ul class="mt-2 space-y-3">
{#each customer.orders as order (order.id)}
<li class="rounded-box border border-base-300 p-3">
<div class="flex justify-between gap-3 text-sm">
<span>{formatDateTime(order.created, data.timezone)} · <span class="capitalize">{order.status}</span></span>
<span class="font-semibold">{money.format(order.total)}</span>
</div>
<ul class="mt-1 text-sm text-base-content/70">
{#each order.lines as line}
<li>{line.quantity}× {line.name}{line.start ? ` — ${formatDateTime(line.start, data.timezone)}` : ''}</li>
{/each}
</ul>
{#if order.customerDetails.notes}
<p class="mt-1 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
{/if}
</li>
{/each}
</ul>
{#if customer.unpaidBaskets.length}
<h3 class="mt-6 font-bold">Unpaid checkouts</h3>
<p class="text-sm text-base-content/60">Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.</p>
<ul class="mt-2 space-y-1 text-sm">
{#each customer.unpaidBaskets as basket (basket.id)}
<li>{formatDateTime(basket.updated, data.timezone)} — {basket.customerDetails.name || '(no name)'}{basket.customerDetails.phone ? ` · ${basket.customerDetails.phone}` : ''}</li>
{/each}
</ul>
{/if}
<div class="mt-6 rounded-box border border-error/40 p-4">
<h3 class="font-bold">Erase this customer</h3>
<p class="mt-1 text-sm text-base-content/70">
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.
</p>
{#if upcoming.length}
<p class="mt-2 text-sm font-semibold">They have {upcoming.length} upcoming booking{upcoming.length === 1 ? '' : 's'}.</p>
{/if}
<form method="POST" action="?/erase" use:enhance={submitting('erase')}>
<input type="hidden" name="email" value={customer.email} />
<button class="btn btn-error btn-outline btn-sm mt-3" type="submit" disabled={saving !== ''} onclick={confirmSubmit(eraseMessage)}>
{#if saving === 'erase'}<span class="loading loading-spinner loading-sm"></span>{/if}
Erase customer
</button>
</form>
</div>
{/if}
</section>
</div>
<form class="rounded-box bg-base-100 p-5 shadow" method="POST" action="?/settings" use:enhance={submitting('settings')}>
<h2 class="text-2xl font-bold">Data retention</h2>
<p class="mt-1 text-sm text-base-content/60">Applied automatically every night. Check how long your accountant needs booking records before turning on anonymising.</p>
<div class="mt-2 grid gap-x-4 sm:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Delete unpaid checkouts after (days)</span>
<input class="input w-full" type="number" min="1" step="1" name="abandonedBasketDays" value={data.settings.abandonedBasketDays} required />
<span class="label whitespace-normal">Details someone typed at checkout without paying.</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Anonymise orders after (months)</span>
<input class="input w-full" type="number" min="0" step="1" name="anonymiseOrdersAfterMonths" value={data.settings.anonymiseOrdersAfterMonths} required />
<span class="label whitespace-normal">0 = keep until you erase a customer by hand. Orders with a booking still ahead are skipped.</span>
</label>
</div>
<button class="btn btn-primary mt-3" type="submit" disabled={saving !== ''}>
{#if saving === 'settings'}<span class="loading loading-spinner loading-sm"></span>{/if}
Save retention
</button>
{@render message(!!form?.settings)}
</form>
</div>

View file

@ -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'
}
});
};

View file

@ -1,5 +1,6 @@
import { fail } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase'; import { ClientResponseError } from 'pocketbase';
import { PRIVACY_PAGE_SLUG, privacyTemplateHtml } from '$lib/admin/privacyTemplate';
import { attempt } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
@ -51,5 +52,19 @@ export const actions: Actions = {
const result = await attempt('Could not save.', () => locals.pb.collection('globals').update(id, { data: value })); const result = await attempt('Could not save.', () => locals.pb.collection('globals').update(id, { data: value }));
if (!result.ok) return fail(400, { section, ok: false, message: result.failure.data.message }); if (!result.ok) return fail(400, { section, ok: false, message: result.failure.data.message });
return { section, ok: true, message: 'Saved.' }; return { section, ok: true, message: 'Saved.' };
},
// An unpublished privacy policy page to fill in, opened in the page editor.
createPrivacyDraft: async ({ locals }) => {
const result = await attempt('Could not create the privacy policy draft.', () =>
locals.pb.collection('pages').create({
slug: PRIVACY_PAGE_SLUG,
title: 'Privacy policy',
published: false,
blocks: [{ id: crypto.randomUUID(), type: 'text', data: { content: privacyTemplateHtml } }]
})
);
if (!result.ok) return fail(400, { section: 'footer', ok: false, message: result.failure.data.message });
redirect(303, `/pages/${PRIVACY_PAGE_SLUG}`);
} }
}; };

View file

@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte'; import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
import { PRIVACY_PAGE_SLUG } from '$lib/admin/privacyTemplate';
import type { SubmitFunction } from '@sveltejs/kit'; import type { SubmitFunction } from '@sveltejs/kit';
let { data, form } = $props(); let { data, form } = $props();
@ -10,6 +11,7 @@
let saving = $state(''); let saving = $state('');
// Older records may predate the CTA button; the inputs below need an object. // Older records may predate the CTA button; the inputs below need an object.
header.ctaButton ??= { label: '', href: '' }; header.ctaButton ??= { label: '', href: '' };
footer.privacyPage ??= '';
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; } function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; } function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
@ -124,6 +126,18 @@
</div> </div>
{/each} {/each}
<button class="btn btn-sm mt-1" type="button" onclick={addSocial}>Add social link</button> <button class="btn btn-sm mt-1" type="button" onclick={addSocial}>Add social link</button>
<h3 class="mt-6 mb-2 font-bold">Privacy policy page</h3>
<select class="select w-full" aria-label="Privacy policy page" bind:value={footer.privacyPage}>
<option value="">— None —</option>
{#each data.pages as page (page.id)}
<option value={page.slug}>{page.title} [{page.slug}]</option>
{/each}
</select>
<p class="mt-1 text-sm text-base-content/60">Linked from the footer and the checkout. Only published pages work as links.</p>
{#if !data.pages.some((page) => page.slug === PRIVACY_PAGE_SLUG)}
<button class="btn btn-sm mt-2 self-start" type="submit" formaction="?/createPrivacyDraft" formnovalidate>Create a privacy policy draft</button>
<p class="mt-1 text-sm text-base-content/60">An unpublished page describing what this site does with customer data, with [gaps] for you to fill in. You're responsible for it being accurate.</p>
{/if}
{@render saveButton('footer', 'Save footer')} {@render saveButton('footer', 'Save footer')}
</form> </form>

View file

@ -32,6 +32,7 @@ export const load: PageServerLoad = async ({ locals }) => {
customerEmailSentAt: String(record.customerEmailSentAt || ''), customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''), clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''), emailError: String(record.emailError || ''),
anonymisedAt: String(record.anonymisedAt || ''),
lines: (linesByOrder.get(record.id) ?? []).map((line) => ({ lines: (linesByOrder.get(record.id) ?? []).map((line) => ({
id: line.id, id: line.id,
name: String(line.name || ''), name: String(line.name || ''),

View file

@ -49,9 +49,9 @@
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box bg-base-100 p-5 shadow">
<div class="flex flex-col justify-between gap-3 md:flex-row md:items-center"> <div class="flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div> <div>
<h2 class="text-xl font-bold">{order.customerDetails?.name || order.email || 'Order'}</h2> <h2 class="text-xl font-bold">{order.anonymisedAt ? 'Anonymised customer' : order.customerDetails?.name || order.email || 'Order'}</h2>
<p class="text-sm text-base-content/60"> <p class="text-sm text-base-content/60">
{order.email} {#if order.email}<a class="link link-hover" href={`/customers?email=${encodeURIComponent(order.email)}`}>{order.email}</a>{/if}
{#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if} {#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if}
{#if order.created} · {formatDateTime(order.created, data.timezone)}{/if} {#if order.created} · {formatDateTime(order.created, data.timezone)}{/if}
</p> </p>
@ -82,10 +82,12 @@
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p> <p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
{/if} {/if}
{#if !order.anonymisedAt}
<div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3"> <div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3">
{@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)} {@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)}
{@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)} {@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)}
</div> </div>
{/if}
{#if order.emailError} {#if order.emailError}
<p class="mt-2 whitespace-pre-line text-sm text-error">{order.emailError}</p> <p class="mt-2 whitespace-pre-line text-sm text-error">{order.emailError}</p>
{/if} {/if}

View file

@ -17,6 +17,8 @@
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -27,6 +29,26 @@
"vite": "^8.0.7" "vite": "^8.0.7"
} }
}, },
"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": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",

View file

@ -10,6 +10,8 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}, },
"devDependencies": { "devDependencies": {
"@fontsource/dm-sans": "^5.3.0",
"@fontsource/playfair-display": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",

View file

@ -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'; @import 'tailwindcss';
@plugin 'daisyui' { @plugin 'daisyui' {
themes: light --default; themes: light --default;

View file

@ -22,5 +22,11 @@
{/each} {/each}
</div> </div>
</div> </div>
<div class="border-t border-charcoal/5 px-6 py-5 text-center text-sm text-charcoal/55">{footer.copyrightText}</div> <div class="border-t border-charcoal/5 px-6 py-5 text-center text-sm text-charcoal/55">
{footer.copyrightText}
{#if footer.privacyPage}
<span aria-hidden="true">·</span>
<a class="underline-offset-2 hover:text-sage-dark hover:underline" href={`/${footer.privacyPage}`}>Privacy policy</a>
{/if}
</div>
</footer> </footer>

View file

@ -1,5 +1,13 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
// Fonts are bundled and served by this app, not loaded from Google: a
// Google Fonts request sends every visitor's IP address to Google (GDPR).
import '@fontsource/dm-sans/400.css';
import '@fontsource/dm-sans/500.css';
import '@fontsource/dm-sans/600.css';
import '@fontsource/dm-sans/700.css';
import '@fontsource/playfair-display/600.css';
import '@fontsource/playfair-display/700.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte'; import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte'; import Footer from '$lib/components/Footer.svelte';

View file

@ -3,7 +3,7 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import type { BasketLine, CheckoutBlockData } from '$shared/types'; import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type BasketLine, type CheckoutBlockData } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar'; import { DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar';
import { loadStripe } from '$shared/stripe-client'; import { loadStripe } from '$shared/stripe-client';
@ -12,6 +12,8 @@
let { data = {} } = $props<{ data: CheckoutBlockData }>(); let { data = {} } = $props<{ data: CheckoutBlockData }>();
const basket = getBasketContext(); const basket = getBasketContext();
// Not set in the admin preview, which has no footer data.
const privacyPage = $derived(page.data.footer?.privacyPage || '');
const customer = $state({ name: '', email: '', phone: '', notes: '' }); const customer = $state({ name: '', email: '', phone: '', notes: '' });
let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle'); let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle');
@ -446,11 +448,20 @@
<textarea <textarea
id="checkout-notes" id="checkout-notes"
rows="3" rows="3"
aria-describedby="checkout-notes-hint"
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none" class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={customer.notes} bind:value={customer.notes}
></textarea> ></textarea>
<p id="checkout-notes-hint" class="mt-1 text-sm text-fg-body/70">{data.notesHint || DEFAULT_NOTES_HINT}</p>
</div> </div>
<p class="text-sm text-fg-body/70">
{data.privacyNotice || DEFAULT_PRIVACY_NOTICE}
{#if privacyPage}
<a class="underline underline-offset-2 hover:text-sage-dark" href={`/${privacyPage}`} target="_blank" rel="noopener">Privacy policy</a>
{/if}
</p>
{#if payState === 'idle' || payState === 'creating'} {#if payState === 'idle' || payState === 'creating'}
<button <button
type="submit" type="submit"

View file

@ -1,4 +1,7 @@
import { loadStripe as _loadStripe } from '@stripe/stripe-js'; // The `pure` entry point loads Stripe.js only when loadStripe() is called
// (when the customer presses Pay). The default entry injects it on import,
// i.e. on every page, sending every visitor's IP address to Stripe.
import { loadStripe as _loadStripe } from '@stripe/stripe-js/pure';
import { env } from '$env/dynamic/public'; import { env } from '$env/dynamic/public';
import { browser } from '$app/environment'; import { browser } from '$app/environment';

View file

@ -73,6 +73,8 @@ export type FooterGlobal = {
email: string; email: string;
socialLinks: { platform: string; url: string }[]; socialLinks: { platform: string; url: string }[];
copyrightText: string; copyrightText: string;
/** Slug of the privacy policy page, linked from the footer and the checkout ('' = none). */
privacyPage?: string;
}; };
export const defaultHeader: HeaderGlobal = { export const defaultHeader: HeaderGlobal = {
@ -93,7 +95,24 @@ export const defaultFooter: FooterGlobal = {
phone: '', phone: '',
email: '', email: '',
socialLinks: [{ platform: 'instagram', url: '' }], socialLinks: [{ platform: 'instagram', url: '' }],
copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.` copyrightText: `© ${new Date().getFullYear()} Eva Shafik Massage. All rights reserved.`,
privacyPage: ''
};
/**
* How long customer details are kept (the `privacy` global). Applied daily by
* pocketbase/pb_hooks/privacy, which has the same defaults.
*/
export type PrivacyGlobal = {
/** Unpaid baskets, with whatever was typed at checkout, are deleted after this many days. */
abandonedBasketDays: number;
/** Orders are anonymised this many months after they were placed; 0 = never automatically. */
anonymiseOrdersAfterMonths: number;
};
export const defaultPrivacy: PrivacyGlobal = {
abandonedBasketDays: 30,
anonymiseOrdersAfterMonths: 0
}; };
// ── Commerce types ───────────────────────────────────────────────────── // ── Commerce types ─────────────────────────────────────────────────────
@ -207,8 +226,15 @@ export type CheckoutBlockData = {
title?: string; title?: string;
heading?: string; heading?: string;
notesLabel?: string; notesLabel?: string;
/** Under the notes field; steers customers away from sharing health details. */
notesHint?: string;
/** Above the Pay button, next to the privacy policy link. */
privacyNotice?: string;
}; };
export const DEFAULT_NOTES_HINT = "Please don't include health details here — we'll talk about anything we should know at your appointment.";
export const DEFAULT_PRIVACY_NOTICE = 'We use your details only to arrange your booking and send your confirmation.';
// ── Email types ─────────────────────────────────────────────────────── // ── Email types ───────────────────────────────────────────────────────
// Email blocks are a separate, smaller set than page blocks: email clients // Email blocks are a separate, smaller set than page blocks: email clients

View file

@ -434,7 +434,7 @@
"fields": [ "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": "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": "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": "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": "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"] }, { "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_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": "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": "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_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} {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "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, "autodate": true,
"options": {} "options": {}

View file

@ -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);
}
});

View file

@ -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
};

View file

@ -629,6 +629,9 @@ function createOrderFromIntent(app, intent) {
// Basket done — order_lines hold the snapshot. // Basket done — order_lines hold the snapshot.
for (const line of lines) tx.delete(line); for (const line of lines) tx.delete(line);
basket.set('status', 'completed'); 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); tx.save(basket);
orderId = order.id; orderId = order.id;
}); });

View file

@ -0,0 +1,40 @@
/// <reference path="../pb_data/types.d.ts" />
// 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);
}
);