Compare commits

..

3 commits

Author SHA1 Message Date
27d95e6f8e Merge pull request 'Shop: item priority, block sort order and a Sort by menu' (#29) from session/add-service-priority into main
Reviewed-on: #29
2026-11-10 12:00:38 +01:00
80cbe6ddb2 Services: editing a saved service no longer fails validation
PocketBase reads an empty number back as 0, so mapItemRecord gave every
service capacity 0 and bufferMinutes 0. The edit form then showed
'Places in a group session: 0', below the field's min of 1, and the
browser refused to submit. 0 now maps to null (not set) for both;
every reader already treats them alike.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gWt7pNdAsocjxujY3m
2026-11-04 22:47:01 +00:00
e896fd3c99 Shop: item priority, block sort order and an optional "Sort by" menu
- items.priority (migration + pb_schema.json): Recommended order in Shop
  blocks, higher first, then by name. Set under Services & products, which
  now lists items in that order.
- Shop block: choose its order (Recommended, Most popular, price up/down,
  name) and optionally let visitors re-sort with a "Sort by" menu.
  sortItems() in shared/items.ts is the one place items are ordered.
- Most popular: GET /api/shop/popular returns item ids by units sold in
  paid orders over the last 90 days (ids only, no sales figures).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gWt7pNdAsocjxujY3m
2026-11-04 22:36:50 +00:00
14 changed files with 215 additions and 21 deletions

View file

@ -201,4 +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. - `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`. - 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. - `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 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". - 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): 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), `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), `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 - `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) - `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) - `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,8 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages` — list/create pages - `/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. - `/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 - `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services, products and bundles shown in Shop blocks - `/items` — services, products and bundles shown in Shop blocks, listed in shop order (highest *Priority in the shop* first, then by name)
- 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. - `/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. - `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them.
- `/passes` — *Vouchers & codes*: search codes (code, email, recipient, bundle), see what each has used/held/left and each part's share of the price, change the expiry, void/reactivate, and issue a code without a purchase - `/passes` — *Vouchers & codes*: search codes (code, email, recipient, bundle), see what each has used/held/left and each part's share of the price, change the expiry, void/reactivate, and issue a code without a purchase

View file

@ -73,7 +73,9 @@ export function createBlock(type: BlockType): ContentBlock {
title: 'Our Services', title: 'Our Services',
itemTypeFilter: 'all', itemTypeFilter: 'all',
itemIds: [], itemIds: [],
layout: 'grid' layout: 'grid',
sort: 'recommended',
showSort: false
}; };
break; break;
case 'checkout': case 'checkout':

View file

@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import type { ContentBlock, ShopBlockData } from '$lib/types'; import type { ContentBlock, ShopBlockData, ShopSort } from '$lib/types';
import { SHOP_SORTS } from '$shared/items';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
let { let {
@ -55,11 +56,28 @@
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)} formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
/> />
<label class="fieldset">
<span class="fieldset-legend">Order</span>
<select class="select w-full" value={block.data.sort || 'recommended'} onchange={(e) => updateData({ sort: e.currentTarget.value as ShopSort })}>
{#each SHOP_SORTS as choice (choice.value)}
<option value={choice.value}>{choice.label}</option>
{/each}
</select>
<span class="label whitespace-normal">
Recommended follows each item’s priority (Services & products). Most popular counts what sold in the last 90 days; items without recent sales come after, in Recommended order.
</span>
</label>
<label class="label cursor-pointer gap-3 whitespace-normal text-base-content">
<input class="toggle toggle-primary shrink-0" type="checkbox" checked={!!block.data.showSort} onchange={(e) => updateData({ showSort: e.currentTarget.checked })} />
<span>Let visitors sort <span class="text-base-content/60">— a “Sort by” menu above the items, starting at the order chosen above</span></span>
</label>
{#if items.length} {#if items.length}
<div class="rounded-box border border-base-300 p-4"> <div class="rounded-box border border-base-300 p-4">
<div class="mb-3"> <div class="mb-3">
<h3 class="font-semibold">Items</h3> <h3 class="font-semibold">Items</h3>
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p> <p class="text-sm text-base-content/60">Leave empty to show all items of the selected type. Chosen items are shown in the order above, not the order you pick them.</p>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
{#each items as item} {#each items as item}

View file

@ -28,6 +28,9 @@ function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
return durations.sort((a, b) => a.minutes - b.minutes); return durations.sort((a, b) => a.minutes - b.minutes);
} }
/** Priorities go from -this to this (the field's limits in pb_schema.json). */
const MAX_PRIORITY = 1000;
/** Most units of one thing a bundle can hold. */ /** Most units of one thing a bundle can hold. */
const MAX_PART_COUNT = 50; const MAX_PART_COUNT = 50;
@ -66,6 +69,9 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
const rawStock = String(data.get('stock') ?? '').trim(); const rawStock = String(data.get('stock') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').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 price: number;
let durations: ItemDuration[] = []; let durations: ItemDuration[] = [];
@ -110,6 +116,7 @@ function itemPayload(data: FormData, items: Record<string, any>[]) {
validMonths, validMonths,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
capacity: Number.isNaN(capacity) ? null : capacity, capacity: Number.isNaN(capacity) ? null : capacity,
priority,
active: String(data.get('active')) === 'true' active: String(data.get('active')) === 'true'
} }
}; };
@ -124,7 +131,7 @@ export const load: PageServerLoad = async ({ locals }) => {
const [records, waiting] = await Promise.all([ const [records, waiting] = await Promise.all([
locals.pb locals.pb
.collection('items') .collection('items')
.getFullList({ sort: 'name', expand: 'image' }) .getFullList({ sort: '-priority,name', expand: 'image' })
.catch(() => []), .catch(() => []),
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>) codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>)
]); ]);

View file

@ -26,6 +26,8 @@
validMonths: string; validMonths: string;
bufferMinutes: string; bufferMinutes: string;
capacity: string; capacity: string;
/** Shop order under Recommended, as typed ('' = 0). */
priority: string;
active: boolean; active: boolean;
}; };
@ -49,6 +51,7 @@
validMonths: '12', validMonths: '12',
bufferMinutes: '', bufferMinutes: '',
capacity: '', capacity: '',
priority: '',
active: true active: true
}; };
} }
@ -118,6 +121,7 @@
validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12', validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12',
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity), capacity: item.capacity == null ? '' : String(item.capacity),
priority: item.priority ? String(item.priority) : '',
active: item.active active: item.active
}; };
showEditor = true; showEditor = true;
@ -130,7 +134,7 @@
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div>
<h1 class="text-3xl font-bold">Services & products</h1> <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.</p> <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>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button> <button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
</div> </div>
@ -145,6 +149,10 @@
{/if} {/if}
{/snippet} {/snippet}
{#snippet priorityNote(item: ItemRecord)}
{#if item.priority}<span class="block text-xs text-base-content/60">Priority {item.priority}</span>{/if}
{/snippet}
{#snippet typeBadge(item: ItemRecord)} {#snippet typeBadge(item: ItemRecord)}
<span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span> <span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span>
{/snippet} {/snippet}
@ -186,6 +194,7 @@
{@render thumbnail(item)} {@render thumbnail(item)}
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<span class="block font-semibold break-words">{item.name}</span> <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"> <div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
{@render typeBadge(item)} {@render typeBadge(item)}
{@render status(item, problem)} {@render status(item, problem)}
@ -216,7 +225,10 @@
<td> <td>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
{@render thumbnail(item)} {@render thumbnail(item)}
<div>
<span class="font-semibold">{item.name}</span> <span class="font-semibold">{item.name}</span>
{@render priorityNote(item)}
</div>
</div> </div>
</td> </td>
<td>{@render typeBadge(item)}</td> <td>{@render typeBadge(item)}</td>
@ -360,6 +372,12 @@
</ImagePicker> </ImagePicker>
</div> </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"> <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} /> <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> <span>Active <span class="text-base-content/60">— inactive items are hidden from the shop</span></span>

View file

@ -1,9 +1,9 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ItemRecord } from '$shared/types'; import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ShopSort, type ItemRecord } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
import { bundleListPrice, formatDuration, lowestPrice } from '$shared/items'; import { SHOP_SORTS, bundleListPrice, formatDuration, lowestPrice, sortItems } from '$shared/items';
import { addDaysToKey, formatDateKey } from '$shared/slots'; import { addDaysToKey, formatDateKey } from '$shared/slots';
let { data = {}, items = [] } = $props<{ let { data = {}, items = [] } = $props<{
@ -55,13 +55,22 @@
} }
if (data.itemIds?.length) { if (data.itemIds?.length) {
const wanted = new Set(data.itemIds); const wanted = new Set(data.itemIds);
result = result result = result.filter((i) => wanted.has(i.id));
.filter((i) => wanted.has(i.id))
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
} }
return result; return sortItems(result, sort);
}); });
/** What the visitor picked in "Sort by" (only while the menu is shown); else the block's own order. */
let pickedSort = $state<ShopSort | null>(null);
// "Most popular" needs recent sales to go by; without any it would only repeat Recommended, so it's left out.
let hasSales = $derived(items.some((item: ItemRecord) => item.popularRank !== null));
let sort = $derived.by<ShopSort>(() => {
const wanted = (data.showSort && pickedSort) || data.sort || 'recommended';
return wanted === 'popular' && !hasSales ? 'recommended' : wanted;
});
let sortChoices = $derived(SHOP_SORTS.filter((choice) => choice.value !== 'popular' || hasSales));
let showSortMenu = $derived(!!data.showSort && visibleItems.length > 1);
let isList = $derived(data.layout === 'list'); let isList = $derived(data.layout === 'list');
/** Item id → name, for what bundles contain. */ /** Item id → name, for what bundles contain. */
@ -277,7 +286,24 @@
<section class="mx-auto max-w-6xl px-6 py-16"> <section class="mx-auto max-w-6xl px-6 py-16">
{#if data.title} {#if data.title}
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2> <h2 class={showSortMenu ? 'mb-8 text-center font-serif text-3xl text-charcoal md:text-4xl' : 'mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl'}>{data.title}</h2>
{/if}
{#if showSortMenu}
<div class="mb-6 flex justify-end">
<label class="inline-flex items-center gap-2 text-sm text-charcoal/70">
Sort by
<select
class="rounded-button border border-charcoal/15 bg-white py-1.5 pr-8 pl-3.5 text-sm text-charcoal"
value={sort}
onchange={(e) => (pickedSort = e.currentTarget.value as ShopSort)}
>
{#each sortChoices as choice (choice.value)}
<option value={choice.value}>{choice.label}</option>
{/each}
</select>
</label>
</div>
{/if} {/if}
{#if !visibleItems.length} {#if !visibleItems.length}

View file

@ -2,7 +2,7 @@
// the Shop block and the checkout. Which duration costs what is decided // 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. // (and charged) by the shop hooks in PocketBase; this only reads and shows it.
import type { BundlePart, ItemDuration, ItemRecord } from './types'; import type { BundlePart, ItemDuration, ItemRecord, ShopSort } from './types';
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */ /** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
export function parseDurations(raw: unknown): ItemDuration[] { export function parseDurations(raw: unknown): ItemDuration[] {
@ -49,3 +49,37 @@ export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) {
} }
return Math.round(total * 100) / 100; return Math.round(total * 100) / 100;
} }
/** The Shop block's sort choices, in menu order, with what visitors see. */
export const SHOP_SORTS: { value: ShopSort; label: string }[] = [
{ value: 'recommended', label: 'Recommended' },
{ value: 'popular', label: 'Most popular' },
{ value: 'price_asc', label: 'Price: low to high' },
{ value: 'price_desc', label: 'Price: high to low' },
{ value: 'name', label: 'Name (A–Z)' }
];
const byName = (a: ItemRecord, b: ItemRecord) => a.name.localeCompare(b.name, 'en-GB', { sensitivity: 'base' });
const byPriority = (a: ItemRecord, b: ItemRecord) => b.priority - a.priority || byName(a, b);
/**
* `items` in the Shop block's `sort` order (a new array). Ties — and, for
* "Most popular", items that haven't sold lately — fall back to Recommended,
* so the admin's priorities still decide whatever the numbers don't.
* Services sort by their lowest price (what "from …" shows).
*/
export function sortItems(items: ItemRecord[], sort: ShopSort = 'recommended') {
const list = [...items];
switch (sort) {
case 'popular':
return list.sort((a, b) => (a.popularRank ?? Infinity) - (b.popularRank ?? Infinity) || byPriority(a, b));
case 'price_asc':
return list.sort((a, b) => a.price - b.price || byPriority(a, b));
case 'price_desc':
return list.sort((a, b) => b.price - a.price || byPriority(a, b));
case 'name':
return list.sort(byName);
default:
return list.sort(byPriority);
}
}

View file

@ -27,9 +27,13 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
durations: type === 'item_with_time' ? parseDurations(record.durations) : [], durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [], bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [],
validMonths: type === 'bundle' ? Number(record.validMonths) || null : null, validMonths: type === 'bundle' ? Number(record.validMonths) || null : null,
bufferMinutes: record.bufferMinutes ?? null, // PocketBase reads an empty number back as 0, never null: 0 means "not set" for both
capacity: record.capacity ?? null, // (and a 0 in the admin form would fail capacity's min of 1, blocking every save).
active: record.active !== false bufferMinutes: Number(record.bufferMinutes) || null,
capacity: Number(record.capacity) || null,
active: record.active !== false,
priority: Number(record.priority) || 0,
popularRank: null
}; };
} }
@ -41,8 +45,16 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
* (see `loadBookableTimes`). Errors propagate. * (see `loadBookableTimes`). Errors propagate.
*/ */
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> { export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }); const [records, popular] = await Promise.all([
const items = records.map(mapItemRecord); pb.collection('items').getFullList({ filter: 'active = true', sort: '-priority,name', expand: 'image' }),
// Only orders the "Most popular" sort; without it the shop still works.
pb.send<{ items: string[] }>('/api/shop/popular', { requestKey: null }).catch((e) => {
console.warn('Best sellers unavailable ("Most popular" falls back to Recommended):', e instanceof Error ? e.message : e);
return { items: [] as string[] };
})
]);
const rank = new Map(popular.items.map((id, i) => [id, i]));
const items = records.map((record) => ({ ...mapItemRecord(record), popularRank: rank.get(record.id) ?? null }));
// A bundle with a part that isn't on sale (inactive, deleted, or a length // 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. // 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) }; return { items: items.filter((item) => item.type !== 'bundle' || bundleListPrice(item.bundleParts, items) !== null) };

View file

@ -156,6 +156,10 @@ export type ItemRecord = {
bufferMinutes: number | null; // get-ready time after each appointment bufferMinutes: number | null; // get-ready time after each appointment
capacity: number | null; // places in a new group session (>1 = group) capacity: number | null; // places in a new group session (>1 = group)
active: boolean; active: boolean;
/** Shop order under "Recommended": higher first, then by name (0 = not set). */
priority: number;
/** Place among the best sellers (0 = best), null if it hasn't sold lately. Set only by `loadShopData`. */
popularRank: number | null;
}; };
/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */ /** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */
@ -291,11 +295,18 @@ export type OrderLine = {
// ── Block data types ────────────────────────────────────────────────── // ── Block data types ──────────────────────────────────────────────────
/** How a Shop block orders its items (`recommended` = by each item's priority). */
export type ShopSort = 'recommended' | 'popular' | 'price_asc' | 'price_desc' | 'name';
export type ShopBlockData = { export type ShopBlockData = {
title?: string; title?: string;
itemTypeFilter?: 'all' | ItemType; itemTypeFilter?: 'all' | ItemType;
itemIds?: string[]; itemIds?: string[];
layout?: 'grid' | 'list'; layout?: 'grid' | 'list';
/** Order shown first (default `recommended`). */
sort?: ShopSort;
/** Show a "Sort by" menu so visitors can reorder the items. */
showSort?: boolean;
}; };
export type CheckoutBlockData = { export type CheckoutBlockData = {

View file

@ -330,6 +330,7 @@
{ "id": "num_itemvalidmo1", "name": "validMonths", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 1, "max": 120, "onlyInt": true }, { "id": "num_itemvalidmo1", "name": "validMonths", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 1, "max": 120, "onlyInt": true },
{ "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true }, { "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true },
{ "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true }, { "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
{ "id": "num_itempriority", "name": "priority", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": -1000, "max": 1000, "onlyInt": true },
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}

View file

@ -16,6 +16,12 @@ routerAdd('GET', '/api/shop/slots', (e) => {
return e.json(200, shop.bookableTimes($app, { item: query.get('item'), minutes: query.get('minutes'), from: query.get('from'), to: query.get('to') })); return e.json(200, shop.bookableTimes($app, { item: query.get('item'), minutes: query.get('minutes'), from: query.get('from'), to: query.get('to') }));
}); });
// Best sellers first (ids only), for the Shop block's "Most popular" sort.
routerAdd('GET', '/api/shop/popular', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, { items: shop.popularItems($app) });
});
routerAdd('GET', '/api/shop/basket/{id}', (e) => { routerAdd('GET', '/api/shop/basket/{id}', (e) => {
const shop = require(`${__hooks}/shop/lib.js`); const shop = require(`${__hooks}/shop/lib.js`);
shop.sweepExpiredHolds($app); shop.sweepExpiredHolds($app);

View file

@ -1305,6 +1305,33 @@ function createOrder(app, basketId, payment) {
return orderId; return orderId;
} }
// ── Popularity ──────────────────────────────────────────────────────────
/** "Most popular" in the Shop block counts what sold in this many days. */
const POPULAR_DAYS = 90;
/**
* Item ids, best-selling first, by units in paid orders over the last
* POPULAR_DAYS (refunded orders don't count). A booking paid with a code
* counts for its service; products handed over inside a bundle (price 0, no
* code) don't — the bundle's own line counts for it. Only the order is
* returned, never the numbers: this is public, and sales figures aren't.
*/
function popularItems(app) {
const rows = arrayOf(new DynamicModel({ item: '', sold: 0 }));
app
.db()
.newQuery(
`SELECT ol.item AS item, SUM(ol.quantity) AS sold
FROM order_lines ol JOIN orders o ON o.id = ol.[[order]]
WHERE o.status = 'paid' AND o.created >= {:since} AND (ol.price > 0 OR ol.pass != '')
GROUP BY ol.item HAVING sold > 0 ORDER BY sold DESC, ol.item`
)
.bind({ since: pbDate(Date.now() - POPULAR_DAYS * DAY_MS) })
.all(rows);
return rows.map((row) => row.item);
}
// ── Orders ────────────────────────────────────────────────────────────── // ── Orders ──────────────────────────────────────────────────────────────
function globalData(app, key) { function globalData(app, key) {
@ -1409,6 +1436,7 @@ module.exports = {
issuePass, issuePass,
bookableTimes, bookableTimes,
slotDetails, slotDetails,
popularItems,
sweepExpiredHolds, sweepExpiredHolds,
loadActiveBasket, loadActiveBasket,
basketPayload, basketPayload,

View file

@ -0,0 +1,29 @@
/// <reference path="../pb_data/types.d.ts" />
// items.priority: where an item comes in Shop blocks under "Recommended"
// (the default order). Higher comes first; equal priorities go by name.
// Empty reads back as 0, so every existing item starts at 0 and the shop
// keeps its old alphabetical order until priorities are set.
function find(app, name) {
try {
return app.findCollectionByNameOrId(name);
} catch (e) {
return null; // fresh install: pb_schema.json (already with the field) is imported later
}
}
migrate(
(app) => {
const items = find(app, 'items');
if (!items || items.fields.getByName('priority')) return;
items.fields.add(new NumberField({ id: 'num_itempriority', name: 'priority', min: -1000, max: 1000, onlyInt: true }));
app.save(items);
},
(app) => {
const items = find(app, 'items');
if (!items || !items.fields.getByName('priority')) return;
items.fields.removeByName('priority');
app.save(items);
}
);