Bundles: protect their parts from deletion, show the saving #8
5 changed files with 109 additions and 13 deletions
|
|
@ -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 });
|
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`. */
|
/** The hook's own message (e.g. "Choose a bundle"), or `fallback`. */
|
||||||
export function hookError(e: unknown, fallback: string) {
|
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);
|
if (e instanceof ClientResponseError && e.status >= 400 && e.status < 500 && e.response?.message) return String(e.response.message);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
import { fail } from '@sveltejs/kit';
|
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 { parseDurations } from '$shared/items';
|
||||||
import { mapItemRecord } from '$shared/server/shop';
|
import { mapItemRecord } from '$shared/server/shop';
|
||||||
import type { BundlePart, ItemDuration, ItemType } from '$lib/types';
|
import type { BundlePart, ItemDuration, ItemType } from '$lib/types';
|
||||||
|
|
@ -119,11 +121,14 @@ function allItems(pb: App.Locals['pb']) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ locals }) => {
|
export const load: PageServerLoad = async ({ locals }) => {
|
||||||
const records = await locals.pb
|
const [records, waiting] = await Promise.all([
|
||||||
.collection('items')
|
locals.pb
|
||||||
.getFullList({ sort: 'name', expand: 'image' })
|
.collection('items')
|
||||||
.catch(() => []);
|
.getFullList({ sort: 'name', expand: 'image' })
|
||||||
return { items: records.map(mapItemRecord) };
|
.catch(() => []),
|
||||||
|
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>)
|
||||||
|
]);
|
||||||
|
return { items: records.map(mapItemRecord), waiting };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const actions: Actions = {
|
export const actions: Actions = {
|
||||||
|
|
@ -148,8 +153,14 @@ export const actions: Actions = {
|
||||||
const data = await request.formData();
|
const data = await request.formData();
|
||||||
const id = String(data.get('id') || '');
|
const id = String(data.get('id') || '');
|
||||||
if (!id) return fail(400, { message: 'Item id is required.' });
|
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));
|
try {
|
||||||
if (!result.ok) return result.failure;
|
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 };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,18 @@
|
||||||
/** "3× Massage (1 hour), 1× Oil" for the table. */
|
/** "3× Massage (1 hour), 1× Oil" for the table. */
|
||||||
function bundleList(item: ItemRecord) {
|
function bundleList(item: ItemRecord) {
|
||||||
const names = new Map(items.map((i) => [i.id, i.name]));
|
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. */
|
/** 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>
|
<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>
|
<tbody>
|
||||||
{#each items as item (item.id)}
|
{#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>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
|
|
@ -174,7 +187,17 @@
|
||||||
{bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'}
|
{bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'}
|
||||||
{:else}—{/if}
|
{:else}—{/if}
|
||||||
</td>
|
</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>
|
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||||
</tr>
|
</tr>
|
||||||
{:else}
|
{:else}
|
||||||
|
|
|
||||||
|
|
@ -59,12 +59,28 @@ routerAdd('POST', '/api/shop/passes/update', (e) => {
|
||||||
return e.json(200, { pass: shop.updatePass($app, e.requestInfo().body) });
|
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) => {
|
routerAdd('POST', '/api/shop/passes/issue', (e) => {
|
||||||
if (!e.auth) throw new UnauthorizedError('Sign in to issue codes');
|
if (!e.auth) throw new UnauthorizedError('Sign in to issue codes');
|
||||||
const shop = require(`${__hooks}/shop/lib.js`);
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
return e.json(200, { pass: shop.issuePass($app, e.requestInfo().body) });
|
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) => {
|
routerAdd('POST', '/api/shop/order-email-status', (e) => {
|
||||||
const shop = require(`${__hooks}/shop/lib.js`);
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
shop.recordEmailStatus($app, e.request.header.get('X-Internal-Secret'), e.requestInfo().body);
|
shop.recordEmailStatus($app, e.request.header.get('X-Internal-Secret'), e.requestInfo().body);
|
||||||
|
|
|
||||||
|
|
@ -458,15 +458,15 @@ function bundleParts(item) {
|
||||||
* (`value`, all its units together): the price split in proportion to what
|
* (`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 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
|
* 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.
|
* keeps the part with what it can find.
|
||||||
*/
|
*/
|
||||||
function bundleSnapshot(app, bundle, lenient) {
|
function bundleSnapshot(app, bundle, lenient) {
|
||||||
const name = bundle.getString('name');
|
const name = bundle.getString('name');
|
||||||
const parts = bundleParts(bundle).map((part) => {
|
const parts = bundleParts(bundle).map((part) => {
|
||||||
const item = findOrNull(app, 'items', part.item);
|
const item = findOrNull(app, 'items', part.item);
|
||||||
const own = !item ? null : isService(item) ? unitPrice(item, part.minutes) : item.getFloat('price');
|
const own = !item || isBundle(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`);
|
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) };
|
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`);
|
if (!parts.length && !lenient) throw conflict(`"${name}" has nothing in it yet`);
|
||||||
|
|
@ -635,6 +635,44 @@ function stockProblem(app, needs) {
|
||||||
return null;
|
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 ────────────────────────────────────────────────────────
|
// ── Admin: codes ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/** Codes for the admin, newest first; `query` matches the code, email, recipient or bundle name. */
|
/** 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 = {
|
module.exports = {
|
||||||
|
deleteBlocker,
|
||||||
|
codesWaiting,
|
||||||
listPasses,
|
listPasses,
|
||||||
updatePass,
|
updatePass,
|
||||||
issuePass,
|
issuePass,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue