domaino/app-admin/src/routes/orders/+page.server.ts
agent 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

69 lines
2.6 KiB
TypeScript

import { fail } from '@sveltejs/kit';
import { sendOrderEmails, type EmailKind } from '$lib/server/email';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
// Newest first. `created` comes from the 1791244800 migration; orders made
// before it have no date and sort last (PocketBase ids are random, so they
// can't be ordered chronologically).
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
// All lines in one request (previously one request per order).
const lineRecords = records.length
? await locals.pb
.collection('order_lines')
.getFullList({ sort: 'start' })
.catch(() => [])
: [];
const linesByOrder = new Map<string, typeof lineRecords>();
for (const line of lineRecords) {
const list = linesByOrder.get(line.order) ?? [];
list.push(line);
linesByOrder.set(line.order, list);
}
const orders = records.map((record) => ({
id: record.id,
email: String(record.email || ''),
customerDetails: record.customerDetails || {},
total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
anonymisedAt: String(record.anonymisedAt || ''),
lines: (linesByOrder.get(record.id) ?? []).map((line) => ({
id: line.id,
name: String(line.name || ''),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : ''
}))
}));
return { orders };
};
const OUTCOME_MESSAGES: Record<string, string> = {
sent: 'sent',
logged: 'not sent — SMTP is not configured (written to the server log)',
disabled: 'not sent — this email is turned off in Emails',
failed: 'failed — see the error on the order'
};
export const actions: Actions = {
resend: async ({ request, locals }) => {
const data = await request.formData();
const orderId = String(data.get('orderId') || '');
const kind = String(data.get('kind') || '');
if (!orderId || (kind !== 'customer' && kind !== 'client')) {
return fail(400, { orderId, ok: false, message: 'Invalid resend request.' });
}
const outcomes = await sendOrderEmails(locals.pb, orderId, [kind as EmailKind]);
const outcome = outcomes[kind as EmailKind] ?? 'failed';
const label = kind === 'customer' ? 'Customer confirmation' : 'Booking alert';
return { orderId, ok: outcome === 'sent', message: `${label} ${OUTCOME_MESSAGES[outcome]}.` };
}
};