Compare commits
No commits in common. "main" and "session/pocketbase-0.40" have entirely different histories.
main
...
session/po
14 changed files with 31 additions and 371 deletions
|
|
@ -201,5 +201,4 @@ 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*. 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".
|
||||
|
|
|
|||
|
|
@ -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; set by dragging the `/items` list, never typed), `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), `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,8 +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. 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.
|
||||
- `/items` — services, products and bundles shown in Shop blocks
|
||||
- `/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.
|
||||
- `/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
|
||||
|
|
|
|||
|
|
@ -73,9 +73,7 @@ export function createBlock(type: BlockType): ContentBlock {
|
|||
title: 'Our Services',
|
||||
itemTypeFilter: 'all',
|
||||
itemIds: [],
|
||||
layout: 'grid',
|
||||
sort: 'recommended',
|
||||
showSort: false
|
||||
layout: 'grid'
|
||||
};
|
||||
break;
|
||||
case 'checkout':
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
<script lang="ts">
|
||||
import type { ContentBlock, ShopBlockData, ShopSort } from '$lib/types';
|
||||
import { SHOP_SORTS } from '$shared/items';
|
||||
import type { ContentBlock, ShopBlockData } from '$lib/types';
|
||||
import SegmentedControl from './SegmentedControl.svelte';
|
||||
|
||||
let {
|
||||
|
|
@ -56,28 +55,11 @@
|
|||
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}
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<div class="mb-3">
|
||||
<h3 class="font-semibold">Items</h3>
|
||||
<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>
|
||||
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each items as item}
|
||||
|
|
|
|||
|
|
@ -28,9 +28,6 @@ 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). Set by dragging the list (?/reorder), never typed. */
|
||||
const MAX_PRIORITY = 1000;
|
||||
|
||||
/** Most units of one thing a bundle can hold. */
|
||||
const MAX_PART_COUNT = 50;
|
||||
|
||||
|
|
@ -120,14 +117,14 @@ 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,priority' }).catch(() => []);
|
||||
return pb.collection('items').getFullList({ fields: 'id,name,type,durations' }).catch(() => []);
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const [records, waiting] = await Promise.all([
|
||||
locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ sort: '-priority,name', expand: 'image' })
|
||||
.getFullList({ sort: 'name', expand: 'image' })
|
||||
.catch(() => []),
|
||||
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>)
|
||||
]);
|
||||
|
|
@ -136,13 +133,9 @@ export const load: PageServerLoad = async ({ locals }) => {
|
|||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const items = await allItems(locals.pb);
|
||||
const result = itemPayload(await request.formData(), items);
|
||||
const result = itemPayload(await request.formData(), await allItems(locals.pb));
|
||||
if ('error' in result) return fail(400, { message: result.error });
|
||||
// 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 }));
|
||||
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload));
|
||||
if (!created.ok) return created.failure;
|
||||
return { ok: true };
|
||||
},
|
||||
|
|
@ -156,33 +149,6 @@ 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') || '');
|
||||
|
|
|
|||
|
|
@ -1,10 +1,7 @@
|
|||
<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';
|
||||
|
||||
|
|
@ -13,85 +10,6 @@
|
|||
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;
|
||||
|
|
@ -212,38 +130,12 @@
|
|||
<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). Shop blocks show them in this order (their <em>Recommended</em> order): drag <span aria-hidden="true">⠿</span> to change it.</p>
|
||||
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later), shown in Shop blocks.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
|
||||
</div>
|
||||
|
||||
<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}
|
||||
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
|
||||
|
||||
{#snippet thumbnail(item: ItemRecord)}
|
||||
{#if item.imageUrl}
|
||||
|
|
@ -253,33 +145,6 @@
|
|||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#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)}
|
||||
<span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span>
|
||||
{/snippet}
|
||||
|
|
@ -313,12 +178,11 @@
|
|||
|
||||
<!-- 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 shown as item, i (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}
|
||||
<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)}
|
||||
<li class="p-4">
|
||||
<div class="flex items-start gap-3">
|
||||
{@render thumbnail(item)}
|
||||
<div class="min-w-0 flex-1">
|
||||
<span class="block font-semibold break-words">{item.name}</span>
|
||||
|
|
@ -343,13 +207,12 @@
|
|||
<div class="hidden rounded-box bg-base-100 p-5 shadow lg:block">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<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>
|
||||
<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>
|
||||
{#each shown as item, i (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 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>
|
||||
<tr>
|
||||
<td>
|
||||
<div class="flex items-center gap-3">
|
||||
{@render thumbnail(item)}
|
||||
|
|
@ -367,7 +230,7 @@
|
|||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||
</tr>
|
||||
{:else}
|
||||
<tr><td colspan="8" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
|
||||
<tr><td colspan="7" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ShopSort, type ItemRecord } from '$shared/types';
|
||||
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, 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 { SHOP_SORTS, bundleListPrice, formatDuration, lowestPrice, sortItems } from '$shared/items';
|
||||
import { bundleListPrice, formatDuration, lowestPrice } from '$shared/items';
|
||||
import { addDaysToKey, formatDateKey } from '$shared/slots';
|
||||
|
||||
let { data = {}, items = [] } = $props<{
|
||||
|
|
@ -55,22 +55,13 @@
|
|||
}
|
||||
if (data.itemIds?.length) {
|
||||
const wanted = new Set(data.itemIds);
|
||||
result = result.filter((i) => wanted.has(i.id));
|
||||
result = result
|
||||
.filter((i) => wanted.has(i.id))
|
||||
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
|
||||
}
|
||||
return sortItems(result, sort);
|
||||
return result;
|
||||
});
|
||||
|
||||
/** 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. */
|
||||
|
|
@ -286,24 +277,7 @@
|
|||
|
||||
<section class="mx-auto max-w-6xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<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>
|
||||
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
|
||||
{/if}
|
||||
|
||||
{#if !visibleItems.length}
|
||||
|
|
|
|||
|
|
@ -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, ShopSort } from './types';
|
||||
import type { BundlePart, ItemDuration, ItemRecord } 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,37 +49,3 @@ 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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,13 +27,9 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
|||
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
|
||||
bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [],
|
||||
validMonths: type === 'bundle' ? Number(record.validMonths) || null : null,
|
||||
// PocketBase reads an empty number back as 0, never null: 0 means "not set" for both
|
||||
// (and a 0 in the admin form would fail capacity's min of 1, blocking every save).
|
||||
bufferMinutes: Number(record.bufferMinutes) || null,
|
||||
capacity: Number(record.capacity) || null,
|
||||
active: record.active !== false,
|
||||
priority: Number(record.priority) || 0,
|
||||
popularRank: null
|
||||
bufferMinutes: record.bufferMinutes ?? null,
|
||||
capacity: record.capacity ?? null,
|
||||
active: record.active !== false
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -45,16 +41,8 @@ export function mapItemRecord(record: Record<string, any>): ItemRecord {
|
|||
* (see `loadBookableTimes`). Errors propagate.
|
||||
*/
|
||||
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
|
||||
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 }));
|
||||
const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
|
||||
const items = records.map(mapItemRecord);
|
||||
// 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) };
|
||||
|
|
|
|||
|
|
@ -156,10 +156,6 @@ 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. */
|
||||
|
|
@ -295,18 +291,11 @@ 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 = {
|
||||
|
|
|
|||
|
|
@ -330,7 +330,6 @@
|
|||
{ "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_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": "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}
|
||||
|
|
|
|||
|
|
@ -16,12 +16,6 @@ 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') }));
|
||||
});
|
||||
|
||||
// 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) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
shop.sweepExpiredHolds($app);
|
||||
|
|
|
|||
|
|
@ -1305,33 +1305,6 @@ function createOrder(app, basketId, payment) {
|
|||
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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
function globalData(app, key) {
|
||||
|
|
@ -1436,7 +1409,6 @@ module.exports = {
|
|||
issuePass,
|
||||
bookableTimes,
|
||||
slotDetails,
|
||||
popularItems,
|
||||
sweepExpiredHolds,
|
||||
loadActiveBasket,
|
||||
basketPayload,
|
||||
|
|
|
|||
|
|
@ -1,29 +0,0 @@
|
|||
/// <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);
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue