Merge pull request 'Bundles: protect their parts from deletion, show the saving' (#8) from bundle-parts-sale-price into main

Reviewed-on: #8
This commit is contained in:
reudy 2026-10-26 12:02:42 +01:00
commit 76b297153e
10 changed files with 141 additions and 18 deletions

View file

@ -135,7 +135,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- **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** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. 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`, `passes.email`/`recipientName`/`message` and (during checkout) `baskets` / `basket_lines.giftTo`/`giftMessage`. 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)*.
- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*.
- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. Bundle parts are JSON, not relations: the `onRecordDelete` hook on `items` (`deleteBlocker`) keeps parts that bundles or codes still need from being deleted, and a bundle with an inactive part isn't sold. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*.
- **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

View file

@ -181,6 +181,8 @@ A **bundle** (Services & products → type *Bundle / voucher*) has its own price
- **Buying**: the bundle goes in the basket like a product (its products' stock is checked and taken with the order). The buyer can mark it as a gift (*for* and a message). After payment every bundle bought becomes a **pass** with its own code, sent in the confirmation email and shown on the result page.
- **Redeeming**: whoever has the code enters it in the basket (`apply_code`). It covers bookings of the same service **and** length while it has places left; covered lines cost 0 and carry `pass`. A basket that codes cover entirely is confirmed without Stripe (`/api/shop/checkout` returns `{ free, orderId }`; the result page is `/checkout/return?order=…`, shown only to that basket's cookie).
- **Counting**: a pass's used places are its order lines (not refunded) and its live basket holds — never a stored counter. Refunding a booking's order gives the place back. Holds keep two people with the same code from using its last place at once.
- **Shown in the shop** with what the parts cost bought one by one, crossed out when that's more than the bundle price (`bundleListPrice` in `packages/shared/src/items.ts`).
- **Parts that go away**: a service or product can't be deleted while a bundle contains it, or while a usable code still has sessions of it to book or held (an `onRecordDelete` hook, `deleteBlocker` — bundle parts are JSON, so the database wouldn't stop it). Making it inactive is allowed: a bundle with an inactive part (or a length the service no longer offers) is hidden from the shop and can't be bought or issued; the admin items list marks it *Not on sale* and says why. Codes keep their own snapshot of names and prices, but can't book an inactive service — the items list shows how many codes are still waiting for it.
- **Value**: `parts[].value` splits the bundle price in proportion to what the parts cost on their own, for partial refunds (done in Stripe, as before).
- **Admin**: `/passes` (*Vouchers & codes*), via `GET /api/shop/passes`, `POST /api/shop/passes/update`, `POST /api/shop/passes/issue` (signed-in admins; passes are written only by the shop hooks).
- **Personal data**: a pass holds the buyer's email and possibly a recipient's name and message. Export, correction and erasure cover passes; erasure keeps the code working. Retention anonymises a pass together with orders, once it has expired or has nothing left to book.

View file

@ -24,6 +24,12 @@ export function issuePass(pb: Pb, body: { itemId: string; email: string; recipie
return pb.send<{ pass: PassSummary }>('/api/shop/passes/issue', { method: 'POST', body, requestKey: null });
}
/** Item id → how many usable codes still have sessions of it to book. */
export async function codesWaiting(pb: Pb) {
const { waiting } = await pb.send<{ waiting: Record<string, number> }>('/api/shop/passes/waiting', { requestKey: null });
return waiting;
}
/** 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);

View file

@ -1,5 +1,7 @@
import { fail } from '@sveltejs/kit';
import { attempt } from '$lib/server/actions';
import { ClientResponseError } from 'pocketbase';
import { attempt, pbErrorMessage } from '$lib/server/actions';
import { codesWaiting } from '$lib/server/passes';
import { parseDurations } from '$shared/items';
import { mapItemRecord } from '$shared/server/shop';
import type { BundlePart, ItemDuration, ItemType } from '$lib/types';
@ -119,11 +121,14 @@ function allItems(pb: App.Locals['pb']) {
}
export const load: PageServerLoad = async ({ locals }) => {
const records = await locals.pb
const [records, waiting] = await Promise.all([
locals.pb
.collection('items')
.getFullList({ sort: 'name', expand: 'image' })
.catch(() => []);
return { items: records.map(mapItemRecord) };
.catch(() => []),
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>)
]);
return { items: records.map(mapItemRecord), waiting };
};
export const actions: Actions = {
@ -148,8 +153,14 @@ 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 = await attempt('Could not delete the item — if it has past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
if (!result.ok) return result.failure;
try {
await locals.pb.collection('items').delete(id);
} catch (e) {
// In a bundle, or still to be booked with a code: the shop hook says which.
if (e instanceof ClientResponseError && e.response?.data?.item?.code === 'in_use') return fail(400, { message: String(e.response.message) });
console.error('[action] Could not delete the item', e);
return fail(400, { message: pbErrorMessage(e, 'Could not delete the item — if it has past orders, switch it to inactive instead.') });
}
return { ok: true };
}
};

View file

@ -67,7 +67,18 @@
/** "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(', ');
return item.bundleParts.map((p) => `${p.count}× ${names.get(p.item) ?? 'deleted item'}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', ');
}
/** Why an active bundle isn't on sale (the shop hides it and won't sell it), or ''. */
function bundleProblem(item: ItemRecord) {
for (const part of item.bundleParts) {
const partItem = items.find((i) => i.id === part.item);
if (!partItem) return 'One of its parts was deleted — edit the bundle.';
if (!partItem.active) return `“${partItem.name}” is inactive.`;
if (part.minutes && !partItem.durations.some((d) => d.minutes === part.minutes)) return `“${partItem.name}” is no longer offered for ${formatDuration(part.minutes)}.`;
}
return '';
}
/** What the parts cost on their own, to compare with the bundle price. */
@ -153,6 +164,8 @@
<thead><tr><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each items as item (item.id)}
{@const problem = item.type === 'bundle' && item.active ? bundleProblem(item) : ''}
{@const waiting = !item.active && item.type === 'item_with_time' ? (data.waiting[item.id] ?? 0) : 0}
<tr>
<td>
<div class="flex items-center gap-3">
@ -174,7 +187,17 @@
{bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'}
{:else}—{/if}
</td>
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
<td>
{#if problem}
<span class="badge badge-warning whitespace-nowrap">Not on sale</span>
<span class="mt-1 block text-xs text-base-content/60">{problem}</span>
{:else}
<span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span>
{/if}
{#if waiting}
<span class="mt-1 block text-xs text-base-content/70">{waiting === 1 ? '1 code has' : `${waiting} codes have`} sessions of this left to book — they can’t while it’s inactive.</span>
{/if}
</td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr>
{:else}

View file

@ -3,7 +3,7 @@
import type { BasketLine, BookableTime, ShopBlockData, ItemRecord } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
import { formatDuration, lowestPrice } from '$shared/items';
import { bundleListPrice, formatDuration, lowestPrice } from '$shared/items';
import { addDaysToKey, formatDateKey } from '$shared/slots';
let { data = {}, items = [] } = $props<{
@ -342,8 +342,13 @@
<span class="text-xs text-charcoal/60">{formatDuration(item.durations[0].minutes)} – {formatDuration(item.durations[item.durations.length - 1].minutes)}</span>
</div>
{:else}
{@const listPrice = item.type === 'bundle' ? bundleListPrice(item.bundleParts, items) : null}
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<span class="text-lg font-semibold text-sage-dark">{formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)}</span>
{#if listPrice != null && listPrice > item.price}
<!-- What the parts cost one by one: the bundle is a saving. -->
<s class="text-sm text-charcoal/50"><span class="sr-only">Bought separately: </span>{formatPrice(listPrice, currency)}</s>
{/if}
{#if duration}
<span class="text-xs text-charcoal/60">{formatDuration(duration.minutes)}</span>
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}

View file

@ -2,7 +2,7 @@
// the Shop block and the checkout. Which duration costs what is decided
// (and charged) by the shop hooks in PocketBase; this only reads and shows it.
import type { ItemDuration } from './types';
import type { BundlePart, ItemDuration, ItemRecord } from './types';
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
export function parseDurations(raw: unknown): ItemDuration[] {
@ -32,3 +32,20 @@ export function lowestPrice(durations: ItemDuration[]) {
export function formatCode(code: string) {
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
}
/**
* What a bundle's parts cost bought one by one (each service at the part's
* length), to show next to the bundle price — or null when a part isn't on
* sale (not in `items`, or a length the service no longer has).
*/
export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) {
let total = 0;
for (const part of parts) {
const item = items.find((candidate) => candidate.id === part.item);
if (!item || item.type === 'bundle') return null;
const unit = item.type === 'item_with_time' ? item.durations.find((d) => d.minutes === part.minutes)?.price : item.price;
if (unit == null) return null;
total += unit * part.count;
}
return Math.round(total * 100) / 100;
}

View file

@ -1,6 +1,6 @@
import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb';
import { parseDurations } from '../items';
import { bundleListPrice, parseDurations } from '../items';
import type { BookableTime, BundlePart, ItemRecord, ItemType } from '../types';
/** A bundle's `bundleParts` field (JSON) → valid parts. */
@ -42,7 +42,10 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
*/
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
return { items: records.map(mapItemRecord) };
const items = records.map(mapItemRecord);
// A bundle with a part that isn't on sale (inactive, deleted, or a length
// the service dropped) can't be bought — the shop hook refuses it too.
return { items: items.filter((item) => item.type !== 'bundle' || bundleListPrice(item.bundleParts, items) !== null) };
}
export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string };

View file

@ -59,12 +59,28 @@ routerAdd('POST', '/api/shop/passes/update', (e) => {
return e.json(200, { pass: shop.updatePass($app, e.requestInfo().body) });
});
routerAdd('GET', '/api/shop/passes/waiting', (e) => {
if (!e.auth) throw new UnauthorizedError('Sign in to see codes');
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, { waiting: shop.codesWaiting($app) });
});
routerAdd('POST', '/api/shop/passes/issue', (e) => {
if (!e.auth) throw new UnauthorizedError('Sign in to issue codes');
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, { pass: shop.issuePass($app, e.requestInfo().body) });
});
// Bundles hold their parts as JSON, so nothing else stops a service or
// product from being deleted out from under a bundle or an unused code.
// Runs for every delete (admin app, dashboard, API).
onRecordDelete((e) => {
const shop = require(`${__hooks}/shop/lib.js`);
const blocker = shop.deleteBlocker(e.app, e.record);
if (blocker) throw new BadRequestError(blocker, { item: new ValidationError('in_use', blocker) });
e.next();
}, 'items');
routerAdd('POST', '/api/shop/order-email-status', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
shop.recordEmailStatus($app, e.request.header.get('X-Internal-Secret'), e.requestInfo().body);

View file

@ -458,15 +458,15 @@ function bundleParts(item) {
* (`value`, all its units together): the price split in proportion to what
* the parts cost on their own (evenly when those are all 0), in cents, with
* the rounding on the last part. Throws an ApiError when a part can't be
* sold — unless `lenient` (an order being created after payment), which
* sold (missing, inactive, or a length no longer offered) — unless `lenient` (an order being created after payment), which
* keeps the part with what it can find.
*/
function bundleSnapshot(app, bundle, lenient) {
const name = bundle.getString('name');
const parts = bundleParts(bundle).map((part) => {
const item = findOrNull(app, 'items', part.item);
const own = !item ? null : isService(item) ? unitPrice(item, part.minutes) : item.getFloat('price');
if (own === null && !lenient) throw conflict(`"${name}" can't be bought right now — one of its parts is no longer offered`);
const own = !item || isBundle(item) ? null : isService(item) ? unitPrice(item, part.minutes) : item.getFloat('price');
if ((own === null || !item.getBool('active')) && !lenient) throw conflict(`"${name}" can't be bought right now — one of its parts is no longer offered`);
return { item: part.item, name: item ? item.getString('name') : 'Unknown item', minutes: isService(item) ? part.minutes : null, count: part.count, ownCents: Math.round((own || 0) * 100) };
});
if (!parts.length && !lenient) throw conflict(`"${name}" has nothing in it yet`);
@ -635,6 +635,44 @@ function stockProblem(app, needs) {
return null;
}
/**
* Why `item` can't be deleted, or '' when it can: a bundle contains it, or a
* code still has sessions of it to book (or held in a basket). Bundles keep
* their parts as JSON, so the database itself wouldn't stop the delete and
* the bundle would be left pointing at nothing. Making an item inactive is
* always allowed: bundles with it stop selling (bundleSnapshot), passes keep
* their own snapshot of names and prices, but their holders can't book an
* inactive service — the admin items list warns about that.
*/
function deleteBlocker(app, item) {
if (isBundle(item)) return '';
const name = item.getString('name');
const bundles = findAll(app, 'items', "type = 'bundle' && bundleParts ~ {:id}", { id: item.id }).filter((b) => bundleParts(b).some((p) => p.item === item.id));
if (bundles.length) {
const names = bundles.map((b) => `"${b.getString('name')}"`).join(', ');
return `"${name}" is part of ${bundles.length === 1 ? 'the bundle' : 'the bundles'} ${names}. Take it out of ${bundles.length === 1 ? 'that bundle' : 'those bundles'} first, or make "${name}" inactive instead.`;
}
const waiting = findAll(app, 'passes', "status = 'active' && parts ~ {:id}", { id: item.id }).filter(
(pass) => !passProblem(pass) && passCredits(app, pass).some((p) => p.item === item.id && p.redeemable && p.left + p.held > 0)
);
if (waiting.length) {
return `${waiting.length === 1 ? '1 code still has' : `${waiting.length} codes still have`} "${name}" sessions to book (for example ${formatCode(waiting[0].getString('code'))}), and codes can only book active services. Keep it until they're used or have expired, or void them under Vouchers & codes first.`;
}
return '';
}
/** Item id → how many usable codes still have sessions of it to book or held; for the admin items list. */
function codesWaiting(app) {
const counts = {};
for (const pass of findAll(app, 'passes', "status = 'active'")) {
if (passProblem(pass)) continue;
const items = {};
for (const part of passCredits(app, pass)) if (part.redeemable && part.left + part.held > 0) items[part.item] = true;
for (const id of Object.keys(items)) counts[id] = (counts[id] || 0) + 1;
}
return counts;
}
// ── Admin: codes ────────────────────────────────────────────────────────
/** Codes for the admin, newest first; `query` matches the code, email, recipient or bundle name. */
@ -1364,6 +1402,8 @@ function recordEmailStatus(app, secretHeader, body) {
}
module.exports = {
deleteBlocker,
codesWaiting,
listPasses,
updatePass,
issuePass,