Services & products: set the shop order by dragging the list

Priority is no longer a number typed per item. The list is the shop's
Recommended order: drag a row by its handle (touch too), or focus the
handle and press up/down, then Save order. ?/reorder renumbers the
priorities n..1 and writes only the ones that changed. New items go to
the end. Unsaved order: a sticky Save/Undo bar, and a warning before
leaving the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gWt7pNdAsocjxujY3m
This commit is contained in:
agent 2026-11-10 11:10:57 +00:00
parent 80cbe6ddb2
commit 2633f5031e
4 changed files with 183 additions and 37 deletions

View file

@ -201,5 +201,5 @@ cd app-public && npm run build
- `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency.
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
- Shop order: `items.priority` (higher first) is *Recommended*; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`.
- Shop order: `items.priority` (higher first) is *Recommended*. It's set by dragging the `/items` list (`?/reorder` renumbers n…1), not typed in the item form; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`.
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`). The Shop block fetches bookable times itself, per service and length, from `GET /api/slots` in each app (a proxy to `GET /api/shop/slots`); if it has nothing to show it says "Nothing is available".

View file

@ -133,7 +133,7 @@ If schema import fails because of a PocketBase version mismatch, create these co
Commerce collections (see the Stripe section above for context):
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name), `active` bool
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name; set by dragging the `/items` list, never typed), `active` bool
- `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text, `pass` relation→passes (the code applied at checkout)
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold), `pass` relation→passes (the code paying for this booking), `giftTo` / `giftMessage` text (who a bundle is for)
@ -159,7 +159,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages` — list/create pages
- `/pages/[slug]` — block editor with draft preview. Text is edited visually (headings, bold, italic, strikethrough, links, lists, pull quotes, lines; alignment and a small *footnote* size per block). Layouts have their own blocks: **Cards** (pictures or numbered steps, optionally linked — e.g. *Who I work with*, *Read next*, *How it works*) and **FAQ** (questions that open to show the answer). An **HTML** block takes raw HTML for embeds and one-offs (inline styles only; anything it loads from another site shares visitors' IPs). Every block has an *Anchor*, so a button or link to `#prices` jumps to it.
- `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services, products and bundles shown in Shop blocks, listed in shop order (highest *Priority in the shop* first, then by name)
- `/items` — services, products and bundles shown in Shop blocks, listed in shop order. Drag a row by its ⠿ handle (or focus the handle and press ↑/↓), then *Save order*: the `?/reorder` action stores it as `items.priority` (n…1, first = highest), writing only what changed. New items go to the end
- Shop block order: *Recommended* (by priority), *Most popular*, *Price: low to high / high to low*, *Name (A–Z)*, chosen per block (`sort`); *Let visitors sort* (`showSort`) adds a "Sort by" menu that starts at that order. *Most popular* = units in paid orders over the last 90 days, from `GET /api/shop/popular` (public; item ids best-selling first, never the numbers; refunded orders and products handed over inside a bundle don't count, bookings paid with a code do). Items without recent sales follow in Recommended order, and the menu leaves the choice out until something has sold. Chosen items (`itemIds`) follow the block's order too, not the order they were picked in.
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). No two slots may overlap (windows and group sessions alike); bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.
- `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them.

View file

@ -28,7 +28,7 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
return durations.sort((a, b) => a.minutes - b.minutes);
}
/** Priorities go from -this to this (the field's limits in pb_schema.json). */
/** Priorities go from -this to this (the field's limits in pb_schema.json). Set by dragging the list (?/reorder), never typed. */
const MAX_PRIORITY = 1000;
/** Most units of one thing a bundle can hold. */
@ -69,9 +69,6 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
const rawStock = String(data.get('stock') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').trim();
const rawPriority = String(data.get('priority') ?? '').trim();
const priority = rawPriority === '' ? 0 : Number(rawPriority);
if (!Number.isInteger(priority) || Math.abs(priority) > MAX_PRIORITY) return { error: `Priority: a whole number from -${MAX_PRIORITY} to ${MAX_PRIORITY} (0 = normal).` };
let price: number;
let durations: ItemDuration[] = [];
@ -116,7 +113,6 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
validMonths,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
capacity: Number.isNaN(capacity) ? null : capacity,
priority,
active: String(data.get('active')) === 'true'
}
};
@ -124,7 +120,7 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
/** 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(() => []);
return pb.collection('items').getFullList({ fields: 'id,name,type,durations,priority' }).catch(() => []);
}
export const load: PageServerLoad = async ({ locals }) => {
@ -140,9 +136,13 @@ export const load: PageServerLoad = async ({ locals }) => {
export const actions: Actions = {
create: async ({ request, locals }) => {
const result = itemPayload(await request.formData(), await allItems(locals.pb));
const items = await allItems(locals.pb);
const result = itemPayload(await request.formData(), items);
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));
// New items go to the end of the shop order; drag them up from there.
const lowest = items.length ? Math.min(...items.map((item) => Number(item.priority) || 0)) : 1;
const priority = Math.max(-MAX_PRIORITY, lowest - 1);
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create({ ...result.payload, priority }));
if (!created.ok) return created.failure;
return { ok: true };
},
@ -156,6 +156,33 @@ export const actions: Actions = {
if (!updated.ok) return updated.failure;
return { ok: true };
},
/**
* The list's new order (`order`: JSON item ids, first = shown first) →
* priorities n…1. Only items whose priority changes are written; items
* missing from the list (added meanwhile) go after it.
*/
reorder: async ({ request, locals }) => {
let ids: unknown;
try {
ids = JSON.parse(String((await request.formData()).get('order') || '[]'));
} catch {
ids = null;
}
if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string')) return fail(400, { message: 'Could not read the new order — reload the page and try again.' });
const records = await locals.pb.collection('items').getFullList({ fields: 'id,priority', sort: '-priority,name' });
const known = new Set(records.map((record) => record.id));
const listed = [...new Set(ids as string[])].filter((id) => known.has(id));
const ordered = [...listed, ...records.map((record) => record.id).filter((id) => !listed.includes(id))];
if (ordered.length > MAX_PRIORITY) return fail(400, { message: `The order can only be set for up to ${MAX_PRIORITY} items.` });
const current = new Map(records.map((record) => [record.id, Number(record.priority) || 0]));
for (const [index, id] of ordered.entries()) {
const priority = ordered.length - index;
if (current.get(id) === priority) continue;
const saved = await attempt('Could not save the order.', () => locals.pb.collection('items').update(id, { priority }));
if (!saved.ok) return saved.failure;
}
return { ok: true, message: 'Order saved.' };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');

View file

@ -1,7 +1,10 @@
<script lang="ts">
import { enhance } from '$app/forms';
import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
import SaveStatus from '$lib/admin/SaveStatus.svelte';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
import type { ItemRecord, ItemType } from '$lib/types';
import { formatDuration } from '$shared/items';
@ -10,6 +13,85 @@
let showEditor = $state(false);
let uploading = $state(false);
// ── Shop order ─────────────────────────────────────────────────────
// The list is in shop order (highest priority first). Dragging a row (or
// the arrow keys on its handle) changes `order` here; "Save order" turns
// it into priorities on the server (?/reorder). null = as saved.
let order = $state<string[] | null>(null);
let shown = $derived.by(() => {
if (!order) return items;
const byId = new Map(items.map((item: ItemRecord) => [item.id, item]));
const listed = order.map((id) => byId.get(id)).filter((item): item is ItemRecord => !!item);
// Anything added meanwhile (another tab) goes at the end.
return [...listed, ...items.filter((item: ItemRecord) => !order!.includes(item.id))];
});
let orderChanged = $derived(!!order && shown.map((item) => item.id).join() !== items.map((item: ItemRecord) => item.id).join());
let savingOrder = $state(false);
warnOnUnsavedChanges(() => orderChanged);
function move(from: number, to: number) {
if (to < 0 || to >= shown.length || from === to) return;
const ids = shown.map((item) => item.id);
const [id] = ids.splice(from, 1);
ids.splice(to, 0, id);
order = ids;
}
// Mouse: native drag and drop on the whole row. Touch: phones don't fire
// drag events, so the handle follows the finger with pointer events (as
// in the page editor's block list).
let dragIndex = $state<number | null>(null);
let dropIndex = $state<number | null>(null);
function endDrag() {
if (dragIndex !== null && dropIndex !== null) move(dragIndex, dropIndex);
dragIndex = null;
dropIndex = null;
}
function rowDrag(index: number) {
return {
draggable: true,
ondragstart: (e: DragEvent) => {
dragIndex = index;
// Firefox won't start a drag without data.
e.dataTransfer?.setData('text/plain', String(index));
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
},
ondragover: (e: DragEvent) => {
e.preventDefault();
dropIndex = index;
},
ondrop: (e: DragEvent) => {
e.preventDefault();
endDrag();
},
ondragend: () => {
dragIndex = null;
dropIndex = null;
}
};
}
function touchDragStart(e: PointerEvent, index: number) {
if (e.pointerType === 'mouse') return;
e.preventDefault();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragIndex = index;
dropIndex = index;
}
function touchDragMove(e: PointerEvent) {
if (dragIndex === null) return;
// The rows are the children of the list (phones) or the table body.
const rows = [...((e.currentTarget as HTMLElement).closest('ul, tbody')?.children ?? [])] as HTMLElement[];
const over = rows.findIndex((row) => e.clientY < row.getBoundingClientRect().bottom);
dropIndex = over === -1 ? rows.length - 1 : over;
// The handle blocks scrolling, so scroll for the finger near the screen's edges.
if (e.clientY < 64) window.scrollBy(0, -12);
else if (e.clientY > window.innerHeight - 64) window.scrollBy(0, 12);
}
type ItemDraft = {
id: string;
name: string;
@ -26,8 +108,6 @@
validMonths: string;
bufferMinutes: string;
capacity: string;
/** Shop order under Recommended, as typed ('' = 0). */
priority: string;
active: boolean;
};
@ -51,7 +131,6 @@
validMonths: '12',
bufferMinutes: '',
capacity: '',
priority: '',
active: true
};
}
@ -121,7 +200,6 @@
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),
priority: item.priority ? String(item.priority) : '',
active: item.active
};
showEditor = true;
@ -134,12 +212,38 @@
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Services & products</h1>
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks — in this order, highest priority first.</p>
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later). Shop blocks show them in this order (their <em>Recommended</em> order): drag <span aria-hidden="true">⠿</span> to change it.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
</div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
<SaveStatus result={form} />
{#if orderChanged}
<!-- Sticky, so Save stays in reach while dragging down a long list. -->
<form
method="POST"
action="?/reorder"
class="sticky top-2 z-10 flex flex-wrap items-center gap-3 rounded-box bg-base-100 p-3 shadow-lg"
use:enhance={() => {
savingOrder = true;
return async ({ result, update }) => {
await update();
savingOrder = false;
// Saved: the reloaded list is in the new order.
if (result.type === 'success') order = null;
};
}}
>
<input type="hidden" name="order" value={JSON.stringify(shown.map((item) => item.id))} />
<span class="badge badge-warning">Unsaved order</span>
<span class="min-w-40 flex-1 text-sm text-base-content/70">Shop blocks change once it’s saved.</span>
<span class="ml-auto flex gap-2">
<button class="btn btn-sm" type="button" disabled={savingOrder} onclick={() => (order = null)}>Undo</button>
<button class="btn btn-primary btn-sm" type="submit" disabled={savingOrder}>Save order</button>
</span>
</form>
{/if}
{#snippet thumbnail(item: ItemRecord)}
{#if item.imageUrl}
@ -149,8 +253,31 @@
{/if}
{/snippet}
{#snippet priorityNote(item: ItemRecord)}
{#if item.priority}<span class="block text-xs text-base-content/60">Priority {item.priority}</span>{/if}
{#snippet handle(item: ItemRecord, index: number)}
<!-- A button so the keyboard can move it too (↑/↓); the pointer drags the whole row. -->
<button
class="btn btn-ghost btn-sm btn-square shrink-0 cursor-grab touch-none text-xl text-base-content/50"
type="button"
title="Drag to change the order (or focus and press ↑/↓)"
aria-label="Move {item.name} — use the arrow keys"
disabled={shown.length < 2}
onpointerdown={(e) => touchDragStart(e, index)}
onpointermove={touchDragMove}
onpointerup={endDrag}
onpointercancel={() => {
dragIndex = null;
dropIndex = null;
}}
onkeydown={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
e.preventDefault();
const to = index + (e.key === 'ArrowUp' ? -1 : 1);
move(index, to);
// Keep the focus on this item's handle in its new place.
const button = e.currentTarget;
requestAnimationFrame(() => (button.closest('ul, tbody')?.children[Math.max(0, Math.min(to, shown.length - 1))]?.querySelector('button') as HTMLElement | null)?.focus());
}}>⠿</button
>
{/snippet}
{#snippet typeBadge(item: ItemRecord)}
@ -186,15 +313,15 @@
<!-- Phones and tablets: one card per item (seven columns didn't fit; long bundle lists made rows very tall). -->
<ul class="divide-y divide-base-200 rounded-box bg-base-100 shadow lg:hidden">
{#each items as item (item.id)}
{#each shown as item, i (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}
<li class="p-4">
<div class="flex items-start gap-3">
<li class="p-4 pl-2 transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
<div class="flex items-start gap-2">
{@render handle(item, i)}
{@render thumbnail(item)}
<div class="min-w-0 flex-1">
<span class="block font-semibold break-words">{item.name}</span>
{@render priorityNote(item)}
<div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
{@render typeBadge(item)}
{@render status(item, problem)}
@ -216,19 +343,17 @@
<div class="hidden rounded-box bg-base-100 p-5 shadow lg:block">
<div class="overflow-x-auto">
<table class="table">
<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 class="w-0"><span class="sr-only">Order</span></th><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)}
{#each shown as item, i (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 class="transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
<td class="pr-0">{@render handle(item, i)}</td>
<td>
<div class="flex items-center gap-3">
{@render thumbnail(item)}
<div>
<span class="font-semibold">{item.name}</span>
{@render priorityNote(item)}
</div>
</div>
</td>
<td>{@render typeBadge(item)}</td>
@ -242,7 +367,7 @@
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr>
{:else}
<tr><td colspan="7" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
<tr><td colspan="8" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
{/each}
</tbody>
</table>
@ -372,12 +497,6 @@
</ImagePicker>
</div>
<label class="fieldset">
<span class="fieldset-legend">Priority in the shop</span>
<input class="input w-full md:w-40" type="number" min="-1000" max="1000" step="1" name="priority" placeholder="0" bind:value={draft.priority} />
<span class="label whitespace-normal">Shop blocks show higher numbers first (their Recommended order); equal ones go by name. Leave at 0 for normal, use a negative number to push something to the end.</span>
</label>
<label class="label mt-2 cursor-pointer gap-3 whitespace-normal text-base-content">
<input class="toggle toggle-success shrink-0" type="checkbox" bind:checked={draft.active} />
<span>Active <span class="text-base-content/60">— inactive items are hidden from the shop</span></span>