diff --git a/app-admin/src/lib/server/passes.ts b/app-admin/src/lib/server/passes.ts index 1ae8380..cda6d53 100644 --- a/app-admin/src/lib/server/passes.ts +++ b/app-admin/src/lib/server/passes.ts @@ -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 }>('/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); diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index a16c016..9790c2e 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -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 - .collection('items') - .getFullList({ sort: 'name', expand: 'image' }) - .catch(() => []); - return { items: records.map(mapItemRecord) }; + const [records, waiting] = await Promise.all([ + locals.pb + .collection('items') + .getFullList({ sort: 'name', expand: 'image' }) + .catch(() => []), + codesWaiting(locals.pb).catch(() => ({}) as Record) + ]); + 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 }; } }; diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index c917bbf..311fb01 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -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 @@ NameTypePriceStockDurationStatus {#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}
@@ -174,7 +187,17 @@ {bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'} {:else}—{/if} - {item.active ? 'Active' : 'Inactive'} + + {#if problem} + Not on sale + {problem} + {:else} + {item.active ? 'Active' : 'Inactive'} + {/if} + {#if waiting} + {waiting === 1 ? '1 code has' : `${waiting} codes have`} sessions of this left to book — they can’t while it’s inactive. + {/if} + {:else} diff --git a/pocketbase/pb_hooks/shop.pb.js b/pocketbase/pb_hooks/shop.pb.js index cc0fff1..abd5fcc 100644 --- a/pocketbase/pb_hooks/shop.pb.js +++ b/pocketbase/pb_hooks/shop.pb.js @@ -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); diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index d5985f0..7c6b6d8 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -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,