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
This commit is contained in:
agent 2026-11-04 22:36:50 +00:00
parent 97b1da2433
commit e896fd3c99
14 changed files with 211 additions and 19 deletions

View file

@ -1,9 +1,9 @@
<script lang="ts">
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 { 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';
let { data = {}, items = [] } = $props<{
@ -55,13 +55,22 @@
}
if (data.itemIds?.length) {
const wanted = new Set(data.itemIds);
result = result
.filter((i) => wanted.has(i.id))
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
result = result.filter((i) => wanted.has(i.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');
/** Item id → name, for what bundles contain. */
@ -277,7 +286,24 @@
<section class="mx-auto max-w-6xl px-6 py-16">
{#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 !visibleItems.length}

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 { 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. */
export function parseDurations(raw: unknown): ItemDuration[] {
@ -49,3 +49,37 @@ export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) {
}
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

@ -29,7 +29,9 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
validMonths: type === 'bundle' ? Number(record.validMonths) || null : null,
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
active: record.active !== false,
priority: Number(record.priority) || 0,
popularRank: null
};
}
@ -41,8 +43,16 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
* (see `loadBookableTimes`). Errors propagate.
*/
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
const items = records.map(mapItemRecord);
const [records, popular] = await Promise.all([
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
// 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) };

View file

@ -156,6 +156,10 @@ export type ItemRecord = {
bufferMinutes: number | null; // get-ready time after each appointment
capacity: number | null; // places in a new group session (>1 = group)
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. */
@ -291,11 +295,18 @@ export type OrderLine = {
// ── 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 = {
title?: string;
itemTypeFilter?: 'all' | ItemType;
itemIds?: string[];
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 = {