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
This commit is contained in:
parent
5828d65a00
commit
971efebcdb
13 changed files with 749 additions and 8 deletions
31
app-admin/src/lib/customers.ts
Normal file
31
app-admin/src/lib/customers.ts
Normal 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 }[];
|
||||||
|
};
|
||||||
24
app-admin/src/lib/server/customers.ts
Normal file
24
app-admin/src/lib/server/customers.ts
Normal 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 });
|
||||||
|
}
|
||||||
|
|
@ -38,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' }
|
||||||
|
|
|
||||||
90
app-admin/src/routes/customers/+page.server.ts
Normal file
90
app-admin/src/routes/customers/+page.server.ts
Normal 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).' };
|
||||||
|
}
|
||||||
|
};
|
||||||
209
app-admin/src/routes/customers/+page.svelte
Normal file
209
app-admin/src/routes/customers/+page.svelte
Normal 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>
|
||||||
20
app-admin/src/routes/customers/export/+server.ts
Normal file
20
app-admin/src/routes/customers/export/+server.ts
Normal 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'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
@ -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 || ''),
|
||||||
|
|
|
||||||
|
|
@ -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}
|
||||||
|
|
||||||
<div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3">
|
{#if !order.anonymisedAt}
|
||||||
{@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)}
|
<div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3">
|
||||||
{@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)}
|
{@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)}
|
||||||
</div>
|
{@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)}
|
||||||
|
</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}
|
||||||
|
|
|
||||||
|
|
@ -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": {}
|
||||||
|
|
|
||||||
47
pocketbase/pb_hooks/privacy.pb.js
Normal file
47
pocketbase/pb_hooks/privacy.pb.js
Normal 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
271
pocketbase/pb_hooks/privacy/lib.js
Normal file
271
pocketbase/pb_hooks/privacy/lib.js
Normal 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
|
||||||
|
};
|
||||||
|
|
@ -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;
|
||||||
});
|
});
|
||||||
|
|
|
||||||
40
pocketbase/pb_migrations/1793000000_orders_anonymise.js
Normal file
40
pocketbase/pb_migrations/1793000000_orders_anonymise.js
Normal 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);
|
||||||
|
}
|
||||||
|
);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue