Shop: duration slider on services, times fetched per service and length

Service cards step through their lengths with a slider and the price
follows. The time picker loads bookable times for the chosen length and
the months on screen from GET /api/slots (a proxy to the shop hook in each
app), and reloads when the basket's bookings change. Checkout, emails and
the basket show each booking's own length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
agent 2026-10-25 20:12:46 +00:00
parent 23df2ceced
commit eac99b2abe
18 changed files with 479 additions and 210 deletions

View file

@ -0,0 +1,6 @@
import { bookableTimesResponse } from '$shared/server/shop';
import type { RequestHandler } from './$types';
// Bookable times for the Shop block's picker (one service and duration).
// Public data from the shop hook in PocketBase — this only forwards it.
export const GET: RequestHandler = ({ locals, url }) => bookableTimesResponse(locals.pb, url);

View file

@ -3,14 +3,15 @@ import { loadShopData } from '$shared/server/shop';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
// The draft blocks come from sessionStorage (client-side), so load the data // The draft blocks come from sessionStorage (client-side), so load the data
// any block might need: shop items/slots and upcoming events. Failures leave // any block might need: shop items and upcoming events (Shop blocks fetch
// bookable times themselves). Failures leave
// the blocks empty rather than breaking the preview. // the blocks empty rather than breaking the preview.
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
const range = getUpcomingCalendarRange(); const range = getUpcomingCalendarRange();
const [shop, events] = await Promise.all([ const [shop, events] = await Promise.all([
loadShopData(locals.pb).catch((e) => { loadShopData(locals.pb).catch((e) => {
console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e); console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e);
return { items: [], slots: [] }; return { items: [] };
}), }),
locals.pb locals.pb
.collection('events') .collection('events')

View file

@ -27,7 +27,7 @@
</svelte:head> </svelte:head>
{#if blocks.length} {#if blocks.length}
<BlockRenderer {blocks} items={data.items} slots={data.slots} calendarEvents={data.calendarEvents} /> <BlockRenderer {blocks} items={data.items} calendarEvents={data.calendarEvents} />
{:else} {:else}
<section class="mx-auto max-w-3xl px-6 py-20 text-center"> <section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1> <h1 class="text-4xl">No preview content</h1>

View file

@ -53,7 +53,10 @@ export function postJson<T>(path: string, data: unknown): Promise<T> {
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null; type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null;
/** Map the API's raw basket records to the `Basket` type used by the UI. */ /** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */
const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString();
/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */
export function mapBasket(payload: BasketPayload): Basket | null { export function mapBasket(payload: BasketPayload): Basket | null {
if (!payload) return null; if (!payload) return null;
const { record, lines } = payload; const { record, lines } = payload;
@ -68,13 +71,15 @@ export function mapBasket(payload: BasketPayload): Basket | null {
slot: line.slot || null, slot: line.slot || null,
quantity: line.quantity, quantity: line.quantity,
lineType: line.lineType, lineType: line.lineType,
start: line.start ? pbInstant(line.start) : undefined,
end: line.end || undefined,
minutes: line.minutes || undefined,
itemName: item?.name, itemName: item?.name,
itemPrice: item?.price, itemPrice: line.unitPrice ?? null,
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
slotStart: slot?.start, slotKind: slot?.kind,
slotEnd: slot?.end,
slotCapacity: slot?.capacity, slotCapacity: slot?.capacity,
heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined
}; };
}); });
return { return {
@ -116,7 +121,8 @@ export function mapOrder(order: Record<string, any>, lines: Record<string, any>[
lineType: l.lineType, lineType: l.lineType,
name: l.name, name: l.name,
price: l.price, price: l.price,
start: l.start || null start: l.start || null,
minutes: l.minutes || null
})) }))
}; };
} }

View file

@ -1,5 +1,5 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord, SlotRecord } from '$lib/types'; import type { ItemRecord } from '$lib/types';
import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; import { BASKET_COOKIE, getBasket } from '$lib/server/shop';
import { loadShopData } from '$shared/server/shop'; import { loadShopData } from '$shared/server/shop';
import { DEFAULT_TIMEZONE, shopCurrency } from '$shared/calendar'; import { DEFAULT_TIMEZONE, shopCurrency } from '$shared/calendar';
@ -17,8 +17,8 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
export const load: LayoutServerLoad = async ({ locals, cookies, url }) => { export const load: LayoutServerLoad = async ({ locals, cookies, url }) => {
// Reading the path makes this load run again on every navigation, so the // Reading the path makes this load run again on every navigation, so the
// slots and basket are fresh on each page — places free up or get taken // basket is fresh on each page (holds lapse while the visitor browses).
// (holds lapse, other customers book) while the visitor browses. // Shop blocks fetch bookable times themselves (GET /api/slots).
void url.pathname; void url.pathname;
const [header, footer, colors] = await Promise.all([ const [header, footer, colors] = await Promise.all([
@ -30,8 +30,8 @@ export const load: LayoutServerLoad = async ({ locals, cookies, url }) => {
if (!header.homePage) header.homePage = defaultHeader.homePage; if (!header.homePage) header.homePage = defaultHeader.homePage;
// Commerce data for the public site. The listing is public data (API // Commerce data for the public site. The listing is public data (API
// rules allow active items / available slots); the basket comes from the // rules allow active items); the basket comes from the shop API in
// shop API in PocketBase. Failures leave the shop empty, never break a page. // PocketBase. Failures leave the shop empty, never break a page.
const [shop, basket] = await Promise.all([ const [shop, basket] = await Promise.all([
loadShopData(locals.pb).catch((e) => { loadShopData(locals.pb).catch((e) => {
console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e); console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e);
@ -40,12 +40,12 @@ export const load: LayoutServerLoad = async ({ locals, cookies, url }) => {
getBasket(cookies.get(BASKET_COOKIE)).catch(() => null) getBasket(cookies.get(BASKET_COOKIE)).catch(() => null)
]); ]);
const items: ItemRecord[] = shop?.items ?? []; const items: ItemRecord[] = shop?.items ?? [];
const slots: SlotRecord[] = shop?.slots ?? [];
// Booking times are shown in the studio's timezone, wherever the visitor is. // Booking times are shown in the studio's timezone, wherever the visitor is.
const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE; const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE;
// Prices are shown in the currency Stripe charges in. // Prices are shown in the currency Stripe charges in.
const currency = shopCurrency(env.STRIPE_CURRENCY); const currency = shopCurrency(env.STRIPE_CURRENCY);
return { header, footer, colors, user: locals.user, basket, items, slots, timezone, currency }; return { header, footer, colors, user: locals.user, basket, items, timezone, currency };
}; };

View file

@ -8,4 +8,4 @@
<title>{data.page.title}</title> <title>{data.page.title}</title>
</svelte:head> </svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} /> <BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} />

View file

@ -7,4 +7,4 @@
<title>{data.page.title}</title> <title>{data.page.title}</title>
</svelte:head> </svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} /> <BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} />

View file

@ -21,6 +21,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
action: body.action, action: body.action,
itemId: body.itemId, itemId: body.itemId,
slotId: body.slotId, slotId: body.slotId,
minutes: body.minutes,
start: body.start,
seats: body.seats,
lineId: body.lineId, lineId: body.lineId,
quantity: body.quantity, quantity: body.quantity,
basketId: cookies.get(BASKET_COOKIE) || '' basketId: cookies.get(BASKET_COOKIE) || ''

View file

@ -0,0 +1,6 @@
import { bookableTimesResponse } from '$shared/server/shop';
import type { RequestHandler } from './$types';
// Bookable times for the Shop block's picker (one service and duration).
// Public data from the shop hook in PocketBase — this only forwards it.
export const GET: RequestHandler = ({ locals, url }) => bookableTimesResponse(locals.pb, url);

View file

@ -72,8 +72,12 @@ export function createBasketStore(initial: Basket | null) {
applyBasket(await callApi({ action: 'add_item', itemId, quantity })); applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
} }
async function addSlotLine(slotId: string) { /**
await applySlotChange(await callApi({ action: 'add_slot', slotId })); * Book a time: in a window, `slotId` plus the service, length and start
* picked; for a group session, `slotId` alone (one place).
*/
async function addSlotLine(slotId: string, booking: { itemId: string; minutes: number; start: string } | null = null) {
await applySlotChange(await callApi({ action: 'add_slot', slotId, ...booking }));
} }
async function updateQuantity(lineId: string, quantity: number) { async function updateQuantity(lineId: string, quantity: number) {

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord, SlotRecord } from '$shared/types'; import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord } from '$shared/types';
import BackgroundWrapper from './BackgroundWrapper.svelte'; import BackgroundWrapper from './BackgroundWrapper.svelte';
import TextBlock from './TextBlock.svelte'; import TextBlock from './TextBlock.svelte';
import ImageTextBlock from './ImageTextBlock.svelte'; import ImageTextBlock from './ImageTextBlock.svelte';
@ -12,11 +12,10 @@
import ShopBlock from './ShopBlock.svelte'; import ShopBlock from './ShopBlock.svelte';
import CheckoutBlock from './CheckoutBlock.svelte'; import CheckoutBlock from './CheckoutBlock.svelte';
let { blocks = [], calendarEvents = [], items = [], slots = [] } = $props<{ let { blocks = [], calendarEvents = [], items = [] } = $props<{
blocks: ContentBlock[]; blocks: ContentBlock[];
calendarEvents?: CalendarEventRecord[]; calendarEvents?: CalendarEventRecord[];
items?: ItemRecord[]; items?: ItemRecord[];
slots?: SlotRecord[];
}>(); }>();
function getBg(block: ContentBlock): BlockBackground { function getBg(block: ContentBlock): BlockBackground {
@ -47,7 +46,7 @@
{:else if block.type === 'upcoming_calendar'} {:else if block.type === 'upcoming_calendar'}
<UpcomingCalendarBlock data={block.data} events={calendarEvents} /> <UpcomingCalendarBlock data={block.data} events={calendarEvents} />
{:else if block.type === 'shop'} {:else if block.type === 'shop'}
<ShopBlock data={block.data} {items} {slots} /> <ShopBlock data={block.data} {items} />
{:else if block.type === 'checkout'} {:else if block.type === 'checkout'}
<CheckoutBlock data={block.data} /> <CheckoutBlock data={block.data} />
{/if} {/if}

View file

@ -6,6 +6,7 @@
import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type BasketLine, type CheckoutBlockData } from '$shared/types'; import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type BasketLine, type CheckoutBlockData } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar';
import { formatDuration } from '$shared/items';
import { loadStripe } from '$shared/stripe-client'; import { loadStripe } from '$shared/stripe-client';
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js'; import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
@ -90,7 +91,7 @@
} }
function describeLine(line: BasketLine) { function describeLine(line: BasketLine) {
return [line.itemName ?? 'A time slot', line.slotStart ? formatSlotTime(line.slotStart) : ''].filter(Boolean).join(', '); return [line.itemName ?? 'A time slot', line.start ? formatSlotTime(line.start) : ''].filter(Boolean).join(', ');
} }
// At zero, reload the basket: the server drops the lapsed line. Retry every // At zero, reload the basket: the server drops the lapsed line. Retry every
@ -345,10 +346,14 @@
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<p class="truncate font-medium">{line.itemName ?? 'Item'}</p> <p class="truncate font-medium">{line.itemName ?? 'Item'}</p>
{#if line.lineType === 'slot' && line.slotStart} {#if line.lineType === 'slot' && line.start}
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p> <p class="text-sm text-fg-body/70">{formatSlotTime(line.start)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</p>
{/if}
{#if line.itemPrice == null}
<p class="text-sm text-terracotta">No longer offered at this length — please remove it and pick again.</p>
{:else}
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice, currency)}</p>
{/if} {/if}
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice ?? 0, currency)}</p>
</div> </div>
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. --> <!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->

View file

@ -1,14 +1,14 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types'; import type { BasketLine, BookableTime, ShopBlockData, 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 } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
import { formatDateKey } from '$shared/slots'; import { formatDuration, lowestPrice } from '$shared/items';
import { addDaysToKey, formatDateKey } from '$shared/slots';
let { data = {}, items = [], slots = [] } = $props<{ let { data = {}, items = [] } = $props<{
data: ShopBlockData; data: ShopBlockData;
items?: ItemRecord[]; items?: ItemRecord[];
slots?: SlotRecord[];
}>(); }>();
const basket = getBasketContext(); const basket = getBasketContext();
@ -16,20 +16,33 @@
// Per-card interaction state. Instances are created per component instance // Per-card interaction state. Instances are created per component instance
// (never shared at module level); keyed by item id so each card is independent. // (never shared at module level); keyed by item id so each card is independent.
class CardState { class CardState {
/** Index into the service's durations (the slider). */
durationIndex = $state(0);
pickerOpen = $state(false); pickerOpen = $state(false);
selectedDayKey = $state<string | null>(null); selectedDayKey = $state<string | null>(null);
adding = $state(false); adding = $state(false);
errorMsg = $state<string | null>(null); errorMsg = $state<string | null>(null);
justAdded = $state(false); justAdded = $state(false);
pendingSlotId = $state<string | null>(null); /** `slot|start` of the time being added or changed. */
pendingKey = $state<string | null>(null);
/** Months from the current one to the first month shown in the picker. */ /** Months from the current one to the first month shown in the picker. */
monthOffset = $state(0); monthOffset = $state(0);
// Bookable times for the selected duration in the months shown (GET /api/slots).
times = $state<BookableTime[]>([]);
next = $state<string | null>(null);
loading = $state(false);
loadError = $state<string | null>(null);
/** What `times` was loaded for; a reload starts when this differs. */
loadedKey = $state('');
requestId = 0;
} }
let cardStates = $state<Record<string, CardState>>({}); let cardStates = $state<Record<string, CardState>>({});
/** The picker shows this many months side by side; the arrows move one month. */ /** The picker shows this many months side by side; the arrows move one month. */
const MONTHS_SHOWN = 2; const MONTHS_SHOWN = 2;
/** How far ahead the picker goes (the shop hook lists up to a year). */
const MAX_MONTH_OFFSET = 12;
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE); const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY); const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
@ -48,42 +61,16 @@
return result; return result;
}); });
// The listing leaves out full slots — including ones whose last places are
// in this visitor's own basket. Add those back (no places left) so the
// visitor still sees their times and can change or drop their places.
let shownSlots = $derived.by<SlotRecord[]>(() => {
const listed = new Set(slots.map((s: SlotRecord) => s.id));
const own = basket.lines
.filter((l) => l.lineType === 'slot' && l.slot && !listed.has(l.slot) && l.slotStart && Date.parse(l.slotStart) > Date.now())
.map((l) => ({ id: l.slot!, item: l.item, start: l.slotStart!, end: l.slotEnd ?? l.slotStart!, capacity: l.slotCapacity ?? 1, free: 0 }));
return own.length ? [...slots, ...own] : slots;
});
// item id -> day key ('YYYY-MM-DD', in the studio's timezone) -> slots on that day, sorted by start time
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
const map = new Map<string, Map<string, SlotRecord[]>>();
for (const slot of shownSlots) {
const key = zonedDateKey(slot.start, timezone);
if (!key) continue;
let itemMap = map.get(slot.item);
if (!itemMap) {
itemMap = new Map();
map.set(slot.item, itemMap);
}
const list = itemMap.get(key);
if (list) list.push(slot);
else itemMap.set(key, [slot]);
}
for (const itemMap of map.values()) {
for (const list of itemMap.values()) {
list.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
}
}
return map;
});
let isList = $derived(data.layout === 'list'); let isList = $derived(data.layout === 'list');
/** Changes whenever the basket's bookings do, so open pickers reload (a booking blocks other times). */
let basketBookingsKey = $derived(
basket.lines
.filter((l) => l.lineType === 'slot')
.map((l) => `${l.id}:${l.quantity}`)
.join(',')
);
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */ /** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
function monthOffsetOf(key: string) { function monthOffsetOf(key: string) {
const today = new Date(); const today = new Date();
@ -96,6 +83,19 @@
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1)); return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1));
} }
/** First and last date key of the months shown at `offset`. */
function shownRange(offset: number) {
const months = pickerMonths(offset);
return {
from: months[0].days.find((d) => d.inMonth)!.dateKey,
to: months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey
};
}
function selectedDuration(item: ItemRecord, state: CardState | undefined) {
return item.durations[Math.min(state?.durationIndex ?? 0, item.durations.length - 1)] ?? null;
}
// Lazily create card state for whatever items are rendered. // Lazily create card state for whatever items are rendered.
$effect(() => { $effect(() => {
for (const item of visibleItems) { for (const item of visibleItems) {
@ -103,6 +103,78 @@
} }
}); });
// Load the bookable times for every open picker: again when the duration,
// the months shown or the basket's bookings change.
$effect(() => {
for (const item of visibleItems) {
const state = cardStates[item.id];
const duration = selectedDuration(item, state);
if (!state?.pickerOpen || !duration) continue;
const range = shownRange(state.monthOffset);
const key = [item.id, duration.minutes, range.from, range.to, timezone, basketBookingsKey].join('|');
if (key !== state.loadedKey) void loadTimes(state, item.id, duration.minutes, range, key);
}
});
async function loadTimes(state: CardState, itemId: string, minutes: number, range: { from: string; to: string }, key: string) {
const requestId = ++state.requestId;
state.loadedKey = key;
state.loading = true;
state.loadError = null;
const params = new URLSearchParams({
item: itemId,
minutes: String(minutes),
from: zonedInputToIso(`${range.from}T00:00`, timezone),
to: zonedInputToIso(`${addDaysToKey(range.to, 1)}T00:00`, timezone)
});
try {
const res = await fetch(`/api/slots?${params}`);
const body = await res.json().catch(() => ({}));
if (requestId !== state.requestId) return; // a newer request is under way
if (!res.ok) throw new Error(body?.message || 'Could not load the available times.');
state.times = body.times ?? [];
state.next = body.next ?? null;
} catch (e) {
if (requestId !== state.requestId) return;
state.times = [];
state.next = null;
state.loadError = errorMessage(e, 'Could not load the available times.');
state.loadedKey = ''; // try again on the next change
} finally {
if (requestId === state.requestId) state.loading = false;
}
}
type DayEntry = { time: BookableTime | null; line: BasketLine | null; start: string; end: string; slot: string };
/**
* Day key → what to show that day: the bookable times, plus this
* visitor's own bookings of this service and length (a time they hold
* is no longer listed as bookable, but they should still see it).
*/
function entriesByDay(item: ItemRecord, state: CardState, minutes: number) {
const own = basket.lines.filter(
(l) => l.lineType === 'slot' && l.item === item.id && l.minutes === minutes && l.start && Date.parse(l.start) > Date.now()
);
const entries: DayEntry[] = state.times.map((time) => ({
time,
line: own.find((l) => l.slot === time.slot && l.start && Date.parse(l.start) === Date.parse(time.start)) ?? null,
start: time.start,
end: time.end,
slot: time.slot
}));
for (const line of own) {
if (entries.some((e) => e.line === line)) continue;
entries.push({ time: null, line, start: line.start!, end: line.end ?? line.start!, slot: line.slot ?? '' });
}
const byDay = new Map<string, DayEntry[]>();
for (const entry of entries.sort((a, b) => Date.parse(a.start) - Date.parse(b.start))) {
const key = zonedDateKey(entry.start, timezone);
if (key) byDay.set(key, [...(byDay.get(key) ?? []), entry]);
}
return byDay;
}
function togglePicker(itemId: string) { function togglePicker(itemId: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state) return; if (!state) return;
@ -113,11 +185,21 @@
state.monthOffset = 0; state.monthOffset = 0;
} }
/** Show the month of the first available day and select it. */ function selectDuration(itemId: string, index: number) {
function showFirstAvailable(itemId: string, key: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state) return; if (!state || state.durationIndex === index) return;
state.monthOffset = Math.max(0, monthOffsetOf(key)); state.durationIndex = index;
state.selectedDayKey = null;
state.justAdded = false;
state.errorMsg = null;
}
/** Show the month of `iso`'s day and select that day. */
function showDay(itemId: string, iso: string) {
const state = cardStates[itemId];
const key = zonedDateKey(iso, timezone);
if (!state || !key) return;
state.monthOffset = Math.min(MAX_MONTH_OFFSET, Math.max(0, monthOffsetOf(key)));
state.selectedDayKey = key; state.selectedDayKey = key;
} }
@ -139,31 +221,32 @@
} }
} }
async function addSlot(itemId: string, slotId: string) { async function addTime(item: ItemRecord, minutes: number, time: BookableTime) {
const state = cardStates[itemId]; const state = cardStates[item.id];
if (!state || state.adding) return; if (!state || state.adding) return;
state.adding = true; state.adding = true;
state.pendingSlotId = slotId; state.pendingKey = `${time.slot}|${time.start}`;
state.errorMsg = null; state.errorMsg = null;
try { try {
// The store reloads the listing afterwards: a booking can block other // The picker reloads afterwards (basketBookingsKey changes): this
// times (one practitioner) or fill a group session. // booking takes its time, plus get-ready time, out of the day.
await basket.addSlotLine(slotId); await basket.addSlotLine(time.slot, time.kind === 'window' ? { itemId: item.id, minutes, start: time.start } : null);
state.justAdded = true; state.justAdded = true;
} catch (e) { } catch (e) {
state.errorMsg = errorMessage(e, 'Could not book this time slot.'); state.errorMsg = errorMessage(e, 'Could not book this time.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingSlotId = null; state.pendingKey = null;
} }
} }
/** One place more or fewer in a group session already in the basket (0 removes it). */ /** One place more or fewer in a group session already in the basket (0 removes it). */
async function changeSeats(itemId: string, line: BasketLine, delta: number) { async function changeSeats(itemId: string, entry: DayEntry, delta: number) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state || state.adding) return; const line = entry.line;
if (!state || !line || state.adding) return;
state.adding = true; state.adding = true;
state.pendingSlotId = line.slot; state.pendingKey = `${entry.slot}|${entry.start}`;
state.errorMsg = null; state.errorMsg = null;
try { try {
const seats = line.quantity + delta; const seats = line.quantity + delta;
@ -173,7 +256,7 @@
state.errorMsg = errorMessage(e, 'Could not change the number of places.'); state.errorMsg = errorMessage(e, 'Could not change the number of places.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingSlotId = null; state.pendingKey = null;
} }
} }
@ -184,6 +267,8 @@
function placesLeft(free: number) { function placesLeft(free: number) {
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left'; return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left';
} }
const longDate = (key: string) => formatDateKey(key, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
</script> </script>
<section class="mx-auto max-w-6xl px-6 py-16"> <section class="mx-auto max-w-6xl px-6 py-16">
@ -202,13 +287,14 @@
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}> <div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}>
{#each visibleItems as item (item.id)} {#each visibleItems as item (item.id)}
{@const ui = cardStates[item.id]} {@const ui = cardStates[item.id]}
{@const itemSlotsByDay = slotsByDay.get(item.id)}
{@const isService = item.type === 'item_with_time'} {@const isService = item.type === 'item_with_time'}
{@const duration = isService ? selectedDuration(item, ui) : null}
{@const bookable = !isService || !!duration}
{@const soldOut = !isService && item.stock === 0} {@const soldOut = !isService && item.stock === 0}
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)} {@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
<article <article
class={isList class={isList
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6' ? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:flex-wrap sm:gap-6'
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'} : 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
> >
{#if item.imageUrl} {#if item.imageUrl}
@ -234,18 +320,48 @@
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p> <p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
{/if} {/if}
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3"> <div class="mt-auto pt-3">
<span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price, currency)}</span> {#if isService && item.durations.length > 1 && ui}
{#if isService && item.duration != null} <!-- Several lengths: a slider steps through them and the price follows. -->
<span class="text-xs text-charcoal/60">{item.duration} min</span> <label class="block">
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} <span class="flex items-baseline justify-between gap-3">
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta"> <span class="text-sm font-medium text-charcoal">{formatDuration(duration!.minutes)}</span>
Only {item.stock} left <span class="text-lg font-semibold text-sage-dark">{formatPrice(duration!.price, currency)}</span>
</span> </span>
{:else if soldOut} <input
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta"> type="range"
Sold out class="mt-2 w-full cursor-pointer accent-sage"
</span> min="0"
max={item.durations.length - 1}
step="1"
value={ui.durationIndex}
aria-label="Length of {item.name}"
aria-valuetext="{formatDuration(duration!.minutes)}, {formatPrice(duration!.price, currency)}"
oninput={(e) => selectDuration(item.id, Number(e.currentTarget.value))}
/>
</label>
<div class="mt-1 flex justify-between text-xs text-charcoal/50" aria-hidden="true">
{#each item.durations as option, i (option.minutes)}
<button type="button" tabindex="-1" class="hover:text-charcoal {i === ui.durationIndex ? 'font-semibold text-charcoal' : ''}" onclick={() => selectDuration(item.id, i)}>
{formatDuration(option.minutes)}
</button>
{/each}
</div>
{:else}
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<span class="text-lg font-semibold text-sage-dark">{formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)}</span>
{#if duration}
<span class="text-xs text-charcoal/60">{formatDuration(duration.minutes)}</span>
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Only {item.stock} left
</span>
{:else if soldOut}
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Sold out
</span>
{/if}
</div>
{/if} {/if}
</div> </div>
@ -272,13 +388,14 @@
type="button" type="button"
class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5' ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
: itemSlotsByDay?.size : bookable
? 'bg-sage text-primary-content hover:bg-sage-dark' ? 'bg-sage text-primary-content hover:bg-sage-dark'
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}" : 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen} disabled={!bookable && !ui?.pickerOpen}
aria-expanded={!!ui?.pickerOpen}
onclick={() => togglePicker(item.id)} onclick={() => togglePicker(item.id)}
> >
{itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} {bookable ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
</button> </button>
{:else} {:else}
<button <button
@ -301,13 +418,12 @@
</div> </div>
</div> </div>
{#if isService && ui?.pickerOpen && itemSlotsByDay} {#if isService && ui?.pickerOpen && duration}
{@const availableKeys = [...itemSlotsByDay.keys()].sort()} {@const byDay = entriesByDay(item, ui, duration.minutes)}
{@const availableKeys = [...byDay.keys()].sort()}
{@const months = pickerMonths(ui.monthOffset)} {@const months = pickerMonths(ui.monthOffset)}
{@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey} {@const shown = shownRange(ui.monthOffset)}
{@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey} {@const anyShown = availableKeys.some((key) => key >= shown.from && key <= shown.to)}
{@const anyShown = availableKeys.some((key) => key >= shownFrom && key <= shownTo)}
{@const lastOffset = monthOffsetOf(availableKeys[availableKeys.length - 1]) - (MONTHS_SHOWN - 1)}
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}> <div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
<div class="mb-3 flex items-center justify-between gap-2"> <div class="mb-3 flex items-center justify-between gap-2">
<button <button
@ -319,33 +435,39 @@
> >
‹ ‹
</button> </button>
<p class="text-sm font-medium text-charcoal/70">Select a date</p> <p class="flex items-center gap-2 text-sm font-medium text-charcoal/70">
{#if ui.loading}<span class="loading loading-spinner loading-xs" aria-label="Loading times"></span>{/if}
Select a date · {formatDuration(duration.minutes)}
</p>
<button <button
type="button" type="button"
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30" class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
aria-label="Next month" aria-label="Next month"
disabled={ui.monthOffset >= lastOffset} disabled={ui.monthOffset >= MAX_MONTH_OFFSET}
onclick={() => ui.monthOffset++} onclick={() => ui.monthOffset++}
> >
› ›
</button> </button>
</div> </div>
{#if !anyShown && availableKeys.length} {#if ui.loadError}
<p class="mb-4 rounded-xl border border-terracotta/30 bg-terracotta/10 px-4 py-3 text-sm text-charcoal" role="alert">{ui.loadError}</p>
{:else if !ui.loading && !anyShown}
<!-- Nothing in the months on screen: say when the next date is, so <!-- Nothing in the months on screen: say when the next date is, so
nobody books January thinking it is this month. --> nobody books January thinking it is this month. -->
<div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal"> <div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal">
<span> {#if ui.next}
{availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'} <span>The next available date for {formatDuration(duration.minutes)} is <strong>{longDate(zonedDateKey(ui.next, timezone))}</strong>.</span>
<strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>. <button
</span> type="button"
<button class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark"
type="button" onclick={() => showDay(item.id, ui.next!)}
class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark" >
onclick={() => showFirstAvailable(item.id, availableKeys.find((key) => key > shownTo) ?? availableKeys[0])} Go to next available date →
> </button>
Go to {availableKeys[0] > shownTo ? 'first' : 'next'} available date → {:else}
</button> <span>No times are available for {formatDuration(duration.minutes)} in these months{item.durations.length > 1 ? ' — try another length' : ''}.</span>
{/if}
</div> </div>
{/if} {/if}
@ -358,7 +480,7 @@
<span class="py-1 text-xs text-charcoal/40">{letter}</span> <span class="py-1 text-xs text-charcoal/40">{letter}</span>
{/each} {/each}
{#each month.days as day (day.dateKey)} {#each month.days as day (day.dateKey)}
{@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)} {@const selectable = day.inMonth && byDay.has(day.dateKey)}
{@const selected = selectable && ui.selectedDayKey === day.dateKey} {@const selected = selectable && ui.selectedDayKey === day.dateKey}
<button <button
type="button" type="button"
@ -382,40 +504,40 @@
{/each} {/each}
</div> </div>
{#if ui.selectedDayKey} {#if ui.selectedDayKey && byDay.has(ui.selectedDayKey)}
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70"> <p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">
Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })} Available times · {longDate(ui.selectedDayKey)}
</p> </p>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
{#each daySlots as slot (slot.id)} {#each byDay.get(ui.selectedDayKey) ?? [] as entry (`${entry.slot}|${entry.start}`)}
{@const line = basket.lines.find((l) => l.slot === slot.id)} {@const isGroup = (entry.time?.capacity ?? entry.line?.slotCapacity ?? 1) > 1}
{@const isGroup = slot.capacity > 1} {@const free = entry.time?.free ?? 0}
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`} {@const pending = ui.pendingKey === `${entry.slot}|${entry.start}`}
{#if isGroup && line} {@const label = `${formatTime(entry.start)}–${formatTime(entry.end)}`}
{#if isGroup && entry.line}
<!-- Places in a group session already in the basket: − / + --> <!-- Places in a group session already in the basket: − / + -->
<div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark"> <div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark">
<span>{label} · {placesLeft(slot.free)}</span> <span>{label} · {placesLeft(free)}</span>
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5"> <span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
<button <button
type="button" type="button"
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40" class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
aria-label="One place fewer" aria-label="One place fewer"
disabled={ui.adding} disabled={ui.adding}
onclick={() => changeSeats(item.id, line, -1)} onclick={() => changeSeats(item.id, entry, -1)}
> >
− −
</button> </button>
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite"> <span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
{#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if} {#if pending}<span class="loading loading-spinner loading-xs"></span>{:else}{entry.line.quantity}{/if}
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span> <span class="sr-only">{entry.line.quantity === 1 ? 'place' : 'places'} in your basket</span>
</span> </span>
<button <button
type="button" type="button"
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40" class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
aria-label="One place more" aria-label="One place more"
disabled={ui.adding || slot.free <= 0} disabled={ui.adding || free <= 0}
onclick={() => changeSeats(item.id, line, 1)} onclick={() => changeSeats(item.id, entry, 1)}
> >
+ +
</button> </button>
@ -424,27 +546,25 @@
{:else} {:else}
<button <button
type="button" type="button"
disabled={!!line || ui.adding} disabled={!!entry.line || !entry.time || ui.adding}
onclick={() => addSlot(item.id, slot.id)} onclick={() => entry.time && addTime(item, duration.minutes, entry.time)}
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {line class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {entry.line
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark' ? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding && : 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
!line !entry.line
? 'cursor-wait' ? 'cursor-wait'
: ''}" : ''}"
> >
{#if ui.pendingSlotId === slot.id} {#if pending}
<span class="loading loading-spinner loading-xs"></span> <span class="loading loading-spinner loading-xs"></span>
{/if} {/if}
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''} {label}{isGroup ? ` · ${placesLeft(free)}` : ''}{entry.line ? ' · In basket' : ''}
</button> </button>
{/if} {/if}
{/each} {/each}
</div> </div>
{:else if anyShown} {:else if anyShown}
<p class="mt-4 text-sm text-charcoal/60"> <p class="mt-4 text-sm text-charcoal/60">Days with availability are highlighted.</p>
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
</p>
{/if} {/if}
{#if ui.justAdded} {#if ui.justAdded}

View file

@ -0,0 +1,29 @@
// Services and their durations — pure helpers shared by the admin editor,
// 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 { ItemDuration } from './types';
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
export function parseDurations(raw: unknown): ItemDuration[] {
const list = Array.isArray(raw) ? raw : [];
const seen = new Set<number>();
return list
.map((d) => ({ minutes: Math.floor(Number(d?.minutes)), price: Number(d?.price) }))
.filter((d) => d.minutes > 0 && Number.isFinite(d.price) && d.price >= 0 && !seen.has(d.minutes) && seen.add(d.minutes))
.sort((a, b) => a.minutes - b.minutes);
}
/** `45` → "45 min", `60` → "1 hour", `120` → "2 hours", `90` → "1 h 30 min". */
export function formatDuration(minutes: number) {
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (!rest) return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
return `${hours} h ${rest} min`;
}
/** The lowest price among a service's durations (what "from …" shows), or null without any. */
export function lowestPrice(durations: ItemDuration[]) {
return durations.length ? Math.min(...durations.map((d) => d.price)) : null;
}

View file

@ -148,14 +148,12 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || ''))); const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || '')));
const lines: EmailLine[] = lineRecords.map((line) => { const lines: EmailLine[] = lineRecords.map((line) => {
// A booking ends after its own length (order lines from before
// lengths were stored fall back to their slot's end).
const start = line.start ? new Date(line.start).toISOString() : null; const start = line.start ? new Date(line.start).toISOString() : null;
const minutes = Number(line.minutes) || 0;
const slotEnd = line.expand?.slot?.end; const slotEnd = line.expand?.slot?.end;
const duration = Number(line.expand?.item?.duration) || 0; const end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null;
const end = slotEnd
? new Date(slotEnd).toISOString()
: start && duration
? new Date(new Date(start).getTime() + duration * 60_000).toISOString()
: null;
return { return {
name: String(line.name || 'Item'), name: String(line.name || 'Item'),
price: Number(line.price) || 0, price: Number(line.price) || 0,

View file

@ -1,39 +1,63 @@
import type PocketBase from 'pocketbase'; import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb'; import { getFileUrl } from '../pb';
import type { ItemRecord, SlotRecord } from '../types'; import { parseDurations } from '../items';
import type { BookableTime, ItemRecord } from '../types';
/** An `items` record (with `expand.image`) → `ItemRecord`. */
export function mapItemRecord(record: Record<string, any>): ItemRecord {
const media = record.expand?.image;
const type = record.type === 'item_with_time' ? 'item_with_time' : 'item';
return {
id: record.id,
name: String(record.name || ''),
description: String(record.description || ''),
price: Number(record.price) || 0,
image: String(record.image || ''),
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type,
stock: record.stock ?? null,
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
};
}
/** /**
* Active items and bookable future slots, shaped for the Shop/Checkout * Active items, shaped for the Shop/Checkout blocks. Used by the public
* blocks. Used by the public layout and the admin draft preview so both * layout and the admin draft preview so both render the same shop. Works
* render the same shop. * with an anonymous client (active items and media are public). Bookable
* * times are fetched by the Shop block itself, per service and duration
* Works with an anonymous client: active items and media are public, and * (see `loadBookableTimes`). Errors propagate.
* slots come from the shop hook (GET /api/shop/slots), which leaves out
* full slots and slots blocked by an overlapping booking. Errors propagate.
*/ */
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> { export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
const [itemRecords, { slots }] = await Promise.all([ const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }), return { items: records.map(mapItemRecord) };
pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null }) }
]);
export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string };
const items = itemRecords.map((record): ItemRecord => {
const media = record.expand?.image; /**
return { * Times a customer can book for one service and duration, from the shop
id: record.id, * hook (GET /api/shop/slots), which applies every availability rule. When
name: record.name, * none start in [from, to), `next` is the first one after (or null).
description: record.description || '', */
price: record.price, export function loadBookableTimes(pb: PocketBase, query: BookableTimesQuery) {
image: record.image || '', return pb.send<{ times: BookableTime[]; next: string | null }>('/api/shop/slots', { query, requestKey: null });
imageUrl: media ? getFileUrl('media', media.id, media.file) : '', }
type: record.type,
stock: record.stock ?? null, /**
duration: record.duration ?? null, * GET /api/slots in both apps (the Shop block's time picker): forwards
bufferMinutes: record.bufferMinutes ?? null, * ?item=&minutes=&from=&to= to the shop hook. A PocketBase error keeps its
capacity: record.capacity ?? null, * status and message; PocketBase being down is a 503.
active: record.active */
}; export async function bookableTimesResponse(pb: PocketBase, url: URL): Promise<Response> {
}); const param = (key: string) => url.searchParams.get(key) ?? '';
try {
return { items, slots }; return Response.json(await loadBookableTimes(pb, { item: param('item'), minutes: param('minutes'), from: param('from'), to: param('to') }));
} catch (e) {
const status = Number((e as { status?: number })?.status) || 0;
const message = (e as { response?: { message?: string } })?.response?.message;
return Response.json({ message: message || 'Could not load the available times — please try again' }, { status: status >= 400 ? status : 503 });
}
} }

View file

@ -6,6 +6,7 @@
// zonedInputToIso, so a run across a DST change still starts at 09:00. // zonedInputToIso, so a run across a DST change still starts at 09:00.
import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar'; import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar';
import type { SlotKind, StartTimesMode } from './types';
/** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */ /** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */
export type TimeWindow = { from: string; to: string }; export type TimeWindow = { from: string; to: string };
@ -43,20 +44,49 @@ export type BulkResult = {
}; };
/** /**
* A slot with its places and blocking, as the shop hook reports it to the * A booked or held time, as the shop hook reports it to the admin: paid
* admin (GET /api/shop/slots?detail=1). Places are taken by paid orders * order lines (`booked`) and basket lines whose hold hasn't lapsed
* (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy` * (`held`). The practitioner is busy until `readyAt` (end + get-ready time).
* is the overlapping slot whose booking/hold blocks this one. */
export type SlotBooking = PlannedSlot & {
slot: string;
item: string;
itemName: string;
readyAt: string;
quantity: number;
status: 'booked' | 'held';
};
/**
* A slot with what's booked in it (GET /api/shop/slots?detail=1). A window
* counts its bookings in `booked`/`held` and lists its `free` stretches; a
* group session has places and may be blocked by an overlapping booking.
*/ */
export type SlotDetail = PlannedSlot & { export type SlotDetail = PlannedSlot & {
id: string; id: string;
item: string; kind: SlotKind;
itemName: string; items: string[];
capacity: number; itemNames: string[];
notes: string; notes: string;
booked: number; booked: number;
held: number; held: number;
blockedBy: string; // window
startTimes?: StartTimesMode;
free?: PlannedSlot[];
// session
minutes?: number;
capacity?: number;
blockedBy?: SlotBooking | null;
};
export const START_TIMES_LABELS: Record<StartTimesMode, string> = {
grid: 'Every 30 min',
edges: 'Next free time'
};
export const START_TIMES_HINTS: Record<StartTimesMode, string> = {
grid: 'Customers can start at any half hour where their booking fits.',
edges: 'Customers can only book right at the start or the end of the free time, so the window shrinks from either end and no gaps are left.'
}; };
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked'; export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
@ -70,12 +100,18 @@ export const SLOT_STATE_LABELS: Record<SlotState, string> = {
}; };
/** /**
* `full` only when paid bookings fill a group; a slot whose last places are * A window is `full` once no free time is left. A session is `full` only
* in baskets reads `held`, since it frees up again if those holds lapse. * when paid bookings fill a group; one whose last places are in baskets
* reads `held`, since it frees up again if those holds lapse.
*/ */
export function slotState(slot: Pick<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): SlotState { export function slotState(slot: Pick<SlotDetail, 'kind' | 'booked' | 'held' | 'capacity' | 'blockedBy' | 'free'>): SlotState {
if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked'; if (slot.kind === 'window') {
if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held'; if ((slot.booked || slot.held) && !slot.free?.length) return slot.booked ? 'full' : 'held';
return slot.booked ? 'booked' : slot.held ? 'held' : 'free';
}
const capacity = slot.capacity ?? 1;
if (slot.booked >= capacity) return capacity > 1 ? 'full' : 'booked';
if (slot.held && slot.booked + slot.held >= capacity) return 'held';
if (slot.booked) return 'booked'; if (slot.booked) return 'booked';
if (slot.held) return 'held'; if (slot.held) return 'held';
return slot.blockedBy ? 'blocked' : 'free'; return slot.blockedBy ? 'blocked' : 'free';
@ -191,7 +227,22 @@ export type GeneratePlanInput = {
timeZone: string; timeZone: string;
}; };
/** Every slot the generator would create, before skipping overlaps/past ones. */ /** Each chosen day's opening hours as windows (dates in `timeZone`), before skipping overlaps/past ones. */
export function planWindows(input: Omit<GeneratePlanInput, 'durationMinutes' | 'bufferMinutes'>): PlannedSlot[] {
const days = new Set(input.weekdays);
const slots: PlannedSlot[] = [];
for (const key of dateKeysBetween(input.fromDate, input.toDate)) {
if (!days.has(weekdayOfKey(key))) continue;
for (const window of input.windows) {
const start = zonedInputToIso(`${key}T${window.from}`, input.timeZone);
const end = zonedInputToIso(`${key}T${window.to}`, input.timeZone);
if (start && end && end > start) slots.push({ start, end });
}
}
return slots;
}
/** Every group session the generator would create, before skipping overlaps/past ones. */
export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] { export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] {
const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes); const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes);
const days = new Set(input.weekdays); const days = new Set(input.weekdays);

View file

@ -119,31 +119,42 @@ export const defaultPrivacy: PrivacyGlobal = {
export type ItemType = 'item' | 'item_with_time'; export type ItemType = 'item' | 'item_with_time';
/** One length a service can be booked for, and its price. */
export type ItemDuration = { minutes: number; price: number };
export type ItemRecord = { export type ItemRecord = {
id: string; id: string;
name: string; name: string;
description: string; description: string;
/** A product's price; for a service, its lowest duration price (kept in sync by the admin). */
price: number; price: number;
image: string; // media record id image: string; // media record id
imageUrl: string; // resolved URL (populated by server load) imageUrl: string; // resolved URL (populated by server load)
type: ItemType; type: ItemType;
stock: number | null; stock: number | null;
duration: number | null; // minutes, for item_with_time durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots bufferMinutes: number | null; // get-ready time after each appointment
capacity: number | null; // places per slot (default for new slots; >1 = group session) capacity: number | null; // places in a new group session (>1 = group)
active: boolean; active: boolean;
}; };
/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */
export type SlotKind = 'window' | 'session';
/** Where bookings may start in a window: every 30 minutes, or only at the start/end of the free time. */
export type StartTimesMode = 'grid' | 'edges';
/** /**
* A bookable slot as the shop lists it (GET /api/shop/slots): only slots * A time a customer can book, as the shop lists it (GET /api/shop/slots for
* with places left that no overlapping booking blocks. * one service and duration): a start time in a window, or a group session
* with places left.
*/ */
export type SlotRecord = { export type BookableTime = {
id: string; slot: string; // slot id (window or session)
item: string; // item id kind: SlotKind;
start: string; start: string;
end: string; end: string;
capacity: number; // places in total capacity: number; // places in total (1 in a window)
free: number; // places still bookable free: number; // places still bookable
}; };
@ -156,12 +167,16 @@ export type BasketLine = {
slot: string | null; slot: string | null;
quantity: number; quantity: number;
lineType: 'item' | 'slot'; lineType: 'item' | 'slot';
/** Slot lines: the booked time and length. */
start?: string;
end?: string;
minutes?: number;
// Expanded fields (populated server-side) // Expanded fields (populated server-side)
itemName?: string; itemName?: string;
itemPrice?: number; /** Price of one unit (a product, or the service at this length); null if no longer offered. */
itemPrice?: number | null;
itemImageUrl?: string; itemImageUrl?: string;
slotStart?: string; slotKind?: SlotKind;
slotEnd?: string;
slotCapacity?: number; slotCapacity?: number;
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */ /** Slot lines: when the reservation lapses and the line is dropped (ISO). */
heldUntil?: string; heldUntil?: string;
@ -211,6 +226,8 @@ export type OrderLine = {
name: string; name: string;
price: number; price: number;
start: string | null; start: string | null;
/** Slot lines: the booked length. */
minutes: number | null;
}; };
// ── Block data types ────────────────────────────────────────────────── // ── Block data types ──────────────────────────────────────────────────