From df840b7fd76533a8c4abde843425537fdc658bb2 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 21:39:51 +0000 Subject: [PATCH] Admin: bundles under Services & products, Vouchers & codes page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bundles are edited with their parts (service at a length, or product, × count), price and validity. /passes lists codes with used/held/left and each part's share of the price; codes can be voided, reactivated, given a new expiry, or issued without a purchase. Orders show codes bought and bookings paid with a code; the customer page lists codes and erasure covers them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- .../lib/admin/editors/ShopBlockEditor.svelte | 5 +- app-admin/src/lib/admin/privacyTemplate.ts | 1 + app-admin/src/lib/customers.ts | 2 + app-admin/src/lib/server/customers.ts | 2 +- app-admin/src/lib/server/passes.ts | 32 +++ app-admin/src/routes/+layout.svelte | 1 + .../src/routes/customers/+page.server.ts | 5 +- app-admin/src/routes/customers/+page.svelte | 13 +- app-admin/src/routes/items/+page.server.ts | 66 ++++- app-admin/src/routes/items/+page.svelte | 102 +++++++- app-admin/src/routes/orders/+page.server.ts | 30 ++- app-admin/src/routes/orders/+page.svelte | 9 + app-admin/src/routes/passes/+page.server.ts | 71 ++++++ app-admin/src/routes/passes/+page.svelte | 231 ++++++++++++++++++ 14 files changed, 543 insertions(+), 27 deletions(-) create mode 100644 app-admin/src/lib/server/passes.ts create mode 100644 app-admin/src/routes/passes/+page.server.ts create mode 100644 app-admin/src/routes/passes/+page.svelte diff --git a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte index c361298..acbe1ba 100644 --- a/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte +++ b/app-admin/src/lib/admin/editors/ShopBlockEditor.svelte @@ -28,7 +28,8 @@ const typeFilterLabels: Record = { all: 'All', item: 'Products', - item_with_time: 'Services' + item_with_time: 'Services', + bundle: 'Bundles' }; @@ -48,7 +49,7 @@ updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })} formatLabel={(v) => typeFilterLabels[String(v)] || String(v)} diff --git a/app-admin/src/lib/admin/privacyTemplate.ts b/app-admin/src/lib/admin/privacyTemplate.ts index ba881f2..05125a9 100644 --- a/app-admin/src/lib/admin/privacyTemplate.ts +++ b/app-admin/src/lib/admin/privacyTemplate.ts @@ -30,6 +30,7 @@ export const privacyTemplateHtml = `

Privacy policy

How long we keep it

  • Details entered at checkout without completing payment: deleted after [30] days.
  • +
  • Gift vouchers and bundles: the code is kept until it expires; your email and any recipient name and message you added are removed together with your order details.
  • 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.
  • Server logs (including IP addresses): [a few] days.
diff --git a/app-admin/src/lib/customers.ts b/app-admin/src/lib/customers.ts index f853d5a..a5e08c0 100644 --- a/app-admin/src/lib/customers.ts +++ b/app-admin/src/lib/customers.ts @@ -28,4 +28,6 @@ export type CustomerData = { lines: { name: string; quantity: number; price: number; start: string }[]; }[]; unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[]; + /** Bundle/voucher codes bought with this email, and who they're for. */ + codes: { code: string; name: string; created: string; expiresAt: string; status: string; recipientName: string; message: string }[]; }; diff --git a/app-admin/src/lib/server/customers.ts b/app-admin/src/lib/server/customers.ts index 6e18d8e..8fd186a 100644 --- a/app-admin/src/lib/server/customers.ts +++ b/app-admin/src/lib/server/customers.ts @@ -20,5 +20,5 @@ export function updateCustomer(pb: Pb, body: { email: string; name?: string; new } export function eraseCustomer(pb: Pb, email: string) { - return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); + return pb.send<{ ordersAnonymised: number; basketsDeleted: number; passesAnonymised: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); } diff --git a/app-admin/src/lib/server/passes.ts b/app-admin/src/lib/server/passes.ts new file mode 100644 index 0000000..1ae8380 --- /dev/null +++ b/app-admin/src/lib/server/passes.ts @@ -0,0 +1,32 @@ +// Bundle/voucher codes for the admin. Codes are commerce data: they are +// only written by the shop hooks in PocketBase (/api/shop/passes*, signed-in +// admins only), which also count what each code has left. + +import { ClientResponseError } from 'pocketbase'; +import type { createPocketBase } from '$lib/pb'; +import type { PassSummary } from '$lib/types'; + +type Pb = ReturnType; + +/** A code as the admin list shows it: the summary plus who bought it and when. */ +export type AdminPass = PassSummary & { email: string; order: string; created: string; anonymisedAt: string }; + +export async function listPasses(pb: Pb, q: string) { + const { passes } = await pb.send<{ passes: AdminPass[] }>('/api/shop/passes', { query: { q }, requestKey: null }); + return passes; +} + +export function updatePass(pb: Pb, body: { id: string; status?: 'active' | 'void'; expiresAt?: string }) { + return pb.send<{ pass: PassSummary }>('/api/shop/passes/update', { method: 'POST', body, requestKey: null }); +} + +export function issuePass(pb: Pb, body: { itemId: string; email: string; recipientName: string; message: string; months: string }) { + return pb.send<{ pass: PassSummary }>('/api/shop/passes/issue', { method: 'POST', body, requestKey: null }); +} + +/** The hook's own message (e.g. "Choose a bundle"), or `fallback`. */ +export function hookError(e: unknown, fallback: string) { + if (e instanceof ClientResponseError && e.status >= 400 && e.status < 500 && e.response?.message) return String(e.response.message); + console.error(`[passes] ${fallback}`, e); + return fallback; +} diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index 30954ef..8e68676 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -41,6 +41,7 @@ { href: '/customers', label: 'Customers' }, { href: '/slots', label: 'Slots' }, { href: '/items', label: 'Services & products' }, + { href: '/passes', label: 'Vouchers & codes' }, { href: '/calendar', label: 'Events' } ] }, diff --git a/app-admin/src/routes/customers/+page.server.ts b/app-admin/src/routes/customers/+page.server.ts index 39fa972..ed3384d 100644 --- a/app-admin/src/routes/customers/+page.server.ts +++ b/app-admin/src/routes/customers/+page.server.ts @@ -63,10 +63,11 @@ export const actions: Actions = { 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; + const { ordersAnonymised, basketsDeleted, passesAnonymised } = result.value; + const codes = passesAnonymised ? `, ${passesAnonymised} code${passesAnonymised === 1 ? '' : 's'} anonymised (still usable)` : ''; return { ok: true, - message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.` + message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted${codes}.` }; }, diff --git a/app-admin/src/routes/customers/+page.svelte b/app-admin/src/routes/customers/+page.svelte index 9c0f8c3..3427d15 100644 --- a/app-admin/src/routes/customers/+page.svelte +++ b/app-admin/src/routes/customers/+page.svelte @@ -3,6 +3,7 @@ import { page } from '$app/state'; import { confirmSubmit } from '$lib/admin/confirm'; import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar'; + import { formatCode } from '$shared/items'; let { data, form } = $props(); let customer = $derived(data.customer); @@ -154,6 +155,16 @@ {/each} + {#if customer.codes?.length} +

Codes bought

+

Bundles and vouchers. Erasing keeps the codes usable but removes the email, recipient and message.

+
    + {#each customer.codes as code (code.code)} +
  • {formatCode(code.code)} — {code.name}{code.recipientName ? ` · for ${code.recipientName}` : ''}{code.message ? ` · “${code.message}”` : ''}
  • + {/each} +
+ {/if} + {#if customer.unpaidBaskets.length}

Unpaid checkouts

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

@@ -167,7 +178,7 @@

Erase this customer

- For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts) and deletes unpaid checkouts. + 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), removes their email and any recipient name and message from codes they bought (the codes keep working), and deletes unpaid checkouts. Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.

{#if upcoming.length} diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index f6b2006..a16c016 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -1,7 +1,8 @@ import { fail } from '@sveltejs/kit'; import { attempt } from '$lib/server/actions'; +import { parseDurations } from '$shared/items'; import { mapItemRecord } from '$shared/server/shop'; -import type { ItemDuration, ItemType } from '$lib/types'; +import type { BundlePart, ItemDuration, ItemType } from '$lib/types'; import type { Actions, PageServerLoad } from './$types'; /** Longest bookable length, in minutes (a booking must fit in one day's window). */ @@ -25,8 +26,39 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } { return durations.sort((a, b) => a.minutes - b.minutes); } -function itemPayload(data: FormData) { - const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; +/** Most units of one thing a bundle can hold. */ +const MAX_PART_COUNT = 50; + +/** + * A bundle's parts from the form's `partItem`/`partMinutes`/`partCount` rows: + * services (at one of their lengths) and products, not other bundles. + */ +function parseBundleRows(data: FormData, items: Record[]): BundlePart[] | { error: string } { + const ids = data.getAll('partItem').map(String); + const minutes = data.getAll('partMinutes').map(String); + const counts = data.getAll('partCount').map(String); + const parts: BundlePart[] = []; + for (let i = 0; i < ids.length; i++) { + if (!ids[i]) continue; + const item = items.find((candidate) => candidate.id === ids[i]); + if (!item || item.type === 'bundle') return { error: 'A bundle can only contain services and products.' }; + const count = Number(counts[i]); + if (!Number.isInteger(count) || count < 1 || count > MAX_PART_COUNT) return { error: `How many of “${item.name}”: a whole number from 1 to ${MAX_PART_COUNT}.` }; + let length: number | null = null; + if (item.type === 'item_with_time') { + length = Number(minutes[i]); + if (!parseDurations(item.durations).some((d) => d.minutes === length)) return { error: `Choose one of the lengths “${item.name}” is offered for.` }; + } + if (parts.some((p) => p.item === item.id && p.minutes === length)) return { error: `“${item.name}” is listed twice — raise its count instead.` }; + parts.push({ item: item.id, minutes: length, count }); + } + if (!parts.some((p) => p.minutes)) return { error: 'A bundle needs at least one service — its code is what books it.' }; + return parts; +} + +function itemPayload(data: FormData, items: Record[]) { + const rawType = String(data.get('type')); + const type: ItemType = rawType === 'item_with_time' || rawType === 'bundle' ? rawType : 'item'; const name = String(data.get('name') || '').trim(); if (!name) return { error: 'Name is required.' }; const rawStock = String(data.get('stock') ?? '').trim(); @@ -35,7 +67,18 @@ function itemPayload(data: FormData) { let price: number; let durations: ItemDuration[] = []; - if (type === 'item_with_time') { + let bundleParts: BundlePart[] = []; + let validMonths: number | null = null; + if (type === 'bundle') { + const parsed = parseBundleRows(data, items.filter((item) => item.id !== String(data.get('id') || ''))); + if ('error' in parsed) return parsed; + bundleParts = parsed; + price = parseFloat(String(data.get('price') || '')); + if (Number.isNaN(price) || price <= 0) return { error: 'A bundle needs a price above 0.' }; + const rawMonths = String(data.get('validMonths') ?? '').trim(); + validMonths = rawMonths === '' ? null : Number(rawMonths); + if (validMonths !== null && !(Number.isInteger(validMonths) && validMonths >= 1 && validMonths <= 120)) return { error: 'Valid for: 1 to 120 months, or empty for no expiry.' }; + } else if (type === 'item_with_time') { const parsed = parseDurationRows(data); if ('error' in parsed) return parsed; durations = parsed; @@ -57,8 +100,12 @@ function itemPayload(data: FormData) { price, image: String(data.get('image') || '').trim(), type, - stock: Number.isNaN(stock) ? null : stock, + // Empty = unlimited (PocketBase can't store an empty number, hence the flag). + stock: Number.isNaN(stock) ? 0 : (stock ?? 0), + trackStock: stock !== null && !Number.isNaN(stock), durations, + bundleParts, + validMonths, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, capacity: Number.isNaN(capacity) ? null : capacity, active: String(data.get('active')) === 'true' @@ -66,6 +113,11 @@ function itemPayload(data: FormData) { }; } +/** Every item, for checking what a bundle may contain. */ +function allItems(pb: App.Locals['pb']) { + return pb.collection('items').getFullList({ fields: 'id,name,type,durations' }).catch(() => []); +} + export const load: PageServerLoad = async ({ locals }) => { const records = await locals.pb .collection('items') @@ -76,7 +128,7 @@ export const load: PageServerLoad = async ({ locals }) => { export const actions: Actions = { create: async ({ request, locals }) => { - const result = itemPayload(await request.formData()); + const result = itemPayload(await request.formData(), await allItems(locals.pb)); if ('error' in result) return fail(400, { message: result.error }); const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload)); if (!created.ok) return created.failure; @@ -86,7 +138,7 @@ export const actions: Actions = { const data = await request.formData(); const id = String(data.get('id') || ''); if (!id) return fail(400, { message: 'Item id is required.' }); - const result = itemPayload(data); + const result = itemPayload(data, await allItems(locals.pb)); if ('error' in result) return fail(400, { message: result.error }); const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload)); if (!updated.ok) return updated.failure; diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index 4e2b6cb..c917bbf 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -23,6 +23,9 @@ stock: string; /** Service lengths and prices, as typed (one form row each). */ durations: { minutes: string; price: string }[]; + /** Bundle contents, as typed (one form row each); minutes '' for a product. */ + parts: { item: string; minutes: string; count: string }[]; + validMonths: string; bufferMinutes: string; capacity: string; active: boolean; @@ -34,9 +37,48 @@ let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); function emptyDraft(): ItemDraft { - return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true }; + return { + id: '', + name: '', + description: '', + price: 0, + image: '', + imageUrl: '', + type: 'item', + stock: '', + durations: [{ minutes: '60', price: '' }], + parts: [{ item: '', minutes: '', count: '1' }], + validMonths: '12', + bufferMinutes: '', + capacity: '', + active: true + }; } + /** What a bundle can contain: services and products (never itself or another bundle). */ + let partChoices = $derived(items.filter((item) => item.type !== 'bundle' && item.id !== draft.id)); + + function choosePartItem(row: ItemDraft['parts'][number], id: string) { + row.item = id; + const item = items.find((candidate) => candidate.id === id); + row.minutes = item?.durations[0] ? String(item.durations[0].minutes) : ''; + } + + /** "3× Massage (1 hour), 1× Oil" for the table. */ + function bundleList(item: ItemRecord) { + const names = new Map(items.map((i) => [i.id, i.name])); + return item.bundleParts.map((p) => `${p.count}× ${names.get(p.item) ?? '?'}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', '); + } + + /** What the parts cost on their own, to compare with the bundle price. */ + let partsListPrice = $derived( + draft.parts.reduce((sum, row) => { + const item = items.find((candidate) => candidate.id === row.item); + const unit = item?.type === 'item_with_time' ? (item.durations.find((d) => String(d.minutes) === row.minutes)?.price ?? 0) : (item?.price ?? 0); + return sum + unit * (Number(row.count) || 0); + }, 0) + ); + function addDuration() { const last = Number(draft.durations.at(-1)?.minutes) || 0; draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' }); @@ -64,6 +106,8 @@ type: item.type, stock: item.stock == null ? '' : String(item.stock), durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }], + parts: item.bundleParts.length ? item.bundleParts.map((p) => ({ item: p.item, minutes: p.minutes ? String(p.minutes) : '', count: String(p.count) })) : [{ item: '', minutes: '', count: '1' }], + validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12', bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), capacity: item.capacity == null ? '' : String(item.capacity), active: item.active @@ -96,7 +140,7 @@

Services & products

-

Bookable services and products, shown in Shop blocks.

+

Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.

@@ -120,10 +164,16 @@ {item.name}
- {item.type === 'item_with_time' ? 'Service' : 'Product'} + {item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'} {item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)} {item.type === 'item' ? (item.stock ?? '∞') : '—'} - {item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'} + + {#if item.type === 'item_with_time'} + {durationList(item)}{item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}{(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''} + {:else if item.type === 'bundle'} + {bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'} + {:else}—{/if} + {item.active ? 'Active' : 'Inactive'} @@ -157,10 +207,52 @@ - {#if draft.type === 'item'} + {#if draft.type === 'bundle'} +
+ What’s in it +
+ {#each draft.parts as row, i} + {@const partItem = items.find((item) => item.id === row.item)} +
+ + × + + {#if partItem?.type === 'item_with_time'} + + {:else} + + {/if} + {#if draft.parts.length > 1} + + {/if} +
+ {/each} +
+ + The buyer gets a code; whoever has it books the services, each at the length set here, without paying again. Products are handed over with the purchase. A one-service voucher is a bundle with one part. +
+
+ + +
+ {:else if draft.type === 'item'}