From eac99b2abe017e7a1c2d1058752e235085a26cf6 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 25 Oct 2026 20:12:46 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW --- app-admin/src/routes/api/slots/+server.ts | 6 + app-admin/src/routes/preview/+page.server.ts | 5 +- app-admin/src/routes/preview/+page.svelte | 2 +- app-public/src/lib/server/shop.ts | 18 +- app-public/src/routes/+layout.server.ts | 14 +- app-public/src/routes/+page.svelte | 2 +- app-public/src/routes/[slug]/+page.svelte | 2 +- app-public/src/routes/api/basket/+server.ts | 3 + app-public/src/routes/api/slots/+server.ts | 6 + packages/shared/src/basket.svelte.ts | 8 +- .../shared/src/blocks/BlockRenderer.svelte | 7 +- .../shared/src/blocks/CheckoutBlock.svelte | 13 +- packages/shared/src/blocks/ShopBlock.svelte | 354 ++++++++++++------ packages/shared/src/items.ts | 29 ++ packages/shared/src/server/email/index.ts | 10 +- packages/shared/src/server/shop.ts | 90 +++-- packages/shared/src/slots.ts | 79 +++- packages/shared/src/types.ts | 41 +- 18 files changed, 479 insertions(+), 210 deletions(-) create mode 100644 app-admin/src/routes/api/slots/+server.ts create mode 100644 app-public/src/routes/api/slots/+server.ts create mode 100644 packages/shared/src/items.ts diff --git a/app-admin/src/routes/api/slots/+server.ts b/app-admin/src/routes/api/slots/+server.ts new file mode 100644 index 0000000..bda83fa --- /dev/null +++ b/app-admin/src/routes/api/slots/+server.ts @@ -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); diff --git a/app-admin/src/routes/preview/+page.server.ts b/app-admin/src/routes/preview/+page.server.ts index f219859..f26feb0 100644 --- a/app-admin/src/routes/preview/+page.server.ts +++ b/app-admin/src/routes/preview/+page.server.ts @@ -3,14 +3,15 @@ import { loadShopData } from '$shared/server/shop'; import type { PageServerLoad } from './$types'; // 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. export const load: PageServerLoad = async ({ locals }) => { const range = getUpcomingCalendarRange(); const [shop, events] = await Promise.all([ loadShopData(locals.pb).catch((e) => { console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e); - return { items: [], slots: [] }; + return { items: [] }; }), locals.pb .collection('events') diff --git a/app-admin/src/routes/preview/+page.svelte b/app-admin/src/routes/preview/+page.svelte index 7627ae1..ce3ac68 100644 --- a/app-admin/src/routes/preview/+page.svelte +++ b/app-admin/src/routes/preview/+page.svelte @@ -27,7 +27,7 @@ {#if blocks.length} - + {:else}

No preview content

diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts index bc1acc5..2417c44 100644 --- a/app-public/src/lib/server/shop.ts +++ b/app-public/src/lib/server/shop.ts @@ -53,7 +53,10 @@ export function postJson(path: string, data: unknown): Promise { type BasketPayload = { record: Record; lines: Record[] } | 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 { if (!payload) return null; const { record, lines } = payload; @@ -68,13 +71,15 @@ export function mapBasket(payload: BasketPayload): Basket | null { slot: line.slot || null, quantity: line.quantity, lineType: line.lineType, + start: line.start ? pbInstant(line.start) : undefined, + end: line.end || undefined, + minutes: line.minutes || undefined, itemName: item?.name, - itemPrice: item?.price, + itemPrice: line.unitPrice ?? null, itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, - slotStart: slot?.start, - slotEnd: slot?.end, + slotKind: slot?.kind, slotCapacity: slot?.capacity, - heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined + heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined }; }); return { @@ -116,7 +121,8 @@ export function mapOrder(order: Record, lines: Record[ lineType: l.lineType, name: l.name, price: l.price, - start: l.start || null + start: l.start || null, + minutes: l.minutes || null })) }; } diff --git a/app-public/src/routes/+layout.server.ts b/app-public/src/routes/+layout.server.ts index 5f630e4..9ffe08c 100644 --- a/app-public/src/routes/+layout.server.ts +++ b/app-public/src/routes/+layout.server.ts @@ -1,5 +1,5 @@ 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 { loadShopData } from '$shared/server/shop'; 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 }) => { // 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 - // (holds lapse, other customers book) while the visitor browses. + // basket is fresh on each page (holds lapse while the visitor browses). + // Shop blocks fetch bookable times themselves (GET /api/slots). void url.pathname; 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; // Commerce data for the public site. The listing is public data (API - // rules allow active items / available slots); the basket comes from the - // shop API in PocketBase. Failures leave the shop empty, never break a page. + // rules allow active items); the basket comes from the shop API in + // PocketBase. Failures leave the shop empty, never break a page. const [shop, basket] = await Promise.all([ loadShopData(locals.pb).catch((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) ]); const items: ItemRecord[] = shop?.items ?? []; - const slots: SlotRecord[] = shop?.slots ?? []; + // Booking times are shown in the studio's timezone, wherever the visitor is. const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE; // Prices are shown in the currency Stripe charges in. 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 }; }; diff --git a/app-public/src/routes/+page.svelte b/app-public/src/routes/+page.svelte index 9a906bf..1c22991 100644 --- a/app-public/src/routes/+page.svelte +++ b/app-public/src/routes/+page.svelte @@ -8,4 +8,4 @@ {data.page.title} - + diff --git a/app-public/src/routes/[slug]/+page.svelte b/app-public/src/routes/[slug]/+page.svelte index 9dc42fd..584ebeb 100644 --- a/app-public/src/routes/[slug]/+page.svelte +++ b/app-public/src/routes/[slug]/+page.svelte @@ -7,4 +7,4 @@ {data.page.title} - + diff --git a/app-public/src/routes/api/basket/+server.ts b/app-public/src/routes/api/basket/+server.ts index 29a1d15..9b43946 100644 --- a/app-public/src/routes/api/basket/+server.ts +++ b/app-public/src/routes/api/basket/+server.ts @@ -21,6 +21,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { action: body.action, itemId: body.itemId, slotId: body.slotId, + minutes: body.minutes, + start: body.start, + seats: body.seats, lineId: body.lineId, quantity: body.quantity, basketId: cookies.get(BASKET_COOKIE) || '' diff --git a/app-public/src/routes/api/slots/+server.ts b/app-public/src/routes/api/slots/+server.ts new file mode 100644 index 0000000..bda83fa --- /dev/null +++ b/app-public/src/routes/api/slots/+server.ts @@ -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); diff --git a/packages/shared/src/basket.svelte.ts b/packages/shared/src/basket.svelte.ts index 6440820..365a29d 100644 --- a/packages/shared/src/basket.svelte.ts +++ b/packages/shared/src/basket.svelte.ts @@ -72,8 +72,12 @@ export function createBasketStore(initial: Basket | null) { 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) { diff --git a/packages/shared/src/blocks/BlockRenderer.svelte b/packages/shared/src/blocks/BlockRenderer.svelte index 94524cb..67ba243 100644 --- a/packages/shared/src/blocks/BlockRenderer.svelte +++ b/packages/shared/src/blocks/BlockRenderer.svelte @@ -1,5 +1,5 @@
@@ -202,13 +287,14 @@
{#each visibleItems as item (item.id)} {@const ui = cardStates[item.id]} - {@const itemSlotsByDay = slotsByDay.get(item.id)} {@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 itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
{#if item.imageUrl} @@ -234,18 +320,48 @@

{item.description}

{/if} -
- {formatPrice(item.price, currency)} - {#if isService && item.duration != null} - {item.duration} min - {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} - - Only {item.stock} left - - {:else if soldOut} - - Sold out - +
+ {#if isService && item.durations.length > 1 && ui} + + + + {:else} +
+ {formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)} + {#if duration} + {formatDuration(duration.minutes)} + {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} + + Only {item.stock} left + + {:else if soldOut} + + Sold out + + {/if} +
{/if}
@@ -272,13 +388,14 @@ 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 ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5' - : itemSlotsByDay?.size + : bookable ? 'bg-sage text-primary-content hover:bg-sage-dark' : '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)} > - {itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} + {bookable ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} {:else}
- {#if isService && ui?.pickerOpen && itemSlotsByDay} - {@const availableKeys = [...itemSlotsByDay.keys()].sort()} + {#if isService && ui?.pickerOpen && duration} + {@const byDay = entriesByDay(item, ui, duration.minutes)} + {@const availableKeys = [...byDay.keys()].sort()} {@const months = pickerMonths(ui.monthOffset)} - {@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey} - {@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey} - {@const anyShown = availableKeys.some((key) => key >= shownFrom && key <= shownTo)} - {@const lastOffset = monthOffsetOf(availableKeys[availableKeys.length - 1]) - (MONTHS_SHOWN - 1)} + {@const shown = shownRange(ui.monthOffset)} + {@const anyShown = availableKeys.some((key) => key >= shown.from && key <= shown.to)}
-

Select a date

+

+ {#if ui.loading}{/if} + Select a date · {formatDuration(duration.minutes)} +

- {#if !anyShown && availableKeys.length} + {#if ui.loadError} + + {:else if !ui.loading && !anyShown}
- - {availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'} - {formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}. - - + {#if ui.next} + The next available date for {formatDuration(duration.minutes)} is {longDate(zonedDateKey(ui.next, timezone))}. + + {:else} + No times are available for {formatDuration(duration.minutes)} in these months{item.durations.length > 1 ? ' — try another length' : ''}. + {/if}
{/if} @@ -358,7 +480,7 @@ {letter} {/each} {#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} - {#if ui.pendingSlotId === slot.id}{:else}{line.quantity}{/if} - {line.quantity === 1 ? 'place' : 'places'} in your basket + {#if pending}{:else}{entry.line.quantity}{/if} + {entry.line.quantity === 1 ? 'place' : 'places'} in your basket @@ -424,27 +546,25 @@ {:else} {/if} {/each}
{:else if anyShown} -

- Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}. -

+

Days with availability are highlighted.

{/if} {#if ui.justAdded} diff --git a/packages/shared/src/items.ts b/packages/shared/src/items.ts new file mode 100644 index 0000000..2d1fd5c --- /dev/null +++ b/packages/shared/src/items.ts @@ -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(); + 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; +} diff --git a/packages/shared/src/server/email/index.ts b/packages/shared/src/server/email/index.ts index 9b775e0..26c284e 100644 --- a/packages/shared/src/server/email/index.ts +++ b/packages/shared/src/server/email/index.ts @@ -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 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 minutes = Number(line.minutes) || 0; const slotEnd = line.expand?.slot?.end; - const duration = Number(line.expand?.item?.duration) || 0; - const end = slotEnd - ? new Date(slotEnd).toISOString() - : start && duration - ? new Date(new Date(start).getTime() + duration * 60_000).toISOString() - : null; + const end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null; return { name: String(line.name || 'Item'), price: Number(line.price) || 0, diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts index 9d8257a..0fbfe2a 100644 --- a/packages/shared/src/server/shop.ts +++ b/packages/shared/src/server/shop.ts @@ -1,39 +1,63 @@ import type PocketBase from 'pocketbase'; 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): 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 - * blocks. Used by the public layout and the admin draft preview so both - * render the same shop. - * - * Works with an anonymous client: active items and media are public, and - * slots come from the shop hook (GET /api/shop/slots), which leaves out - * full slots and slots blocked by an overlapping booking. Errors propagate. + * Active items, shaped for the Shop/Checkout blocks. Used by the public + * layout and the admin draft preview so both render the same shop. Works + * with an anonymous client (active items and media are public). Bookable + * times are fetched by the Shop block itself, per service and duration + * (see `loadBookableTimes`). Errors propagate. */ -export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> { - const [itemRecords, { slots }] = await Promise.all([ - pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }), - pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null }) - ]); - - const items = itemRecords.map((record): ItemRecord => { - const media = record.expand?.image; - return { - id: record.id, - name: record.name, - description: record.description || '', - price: record.price, - image: record.image || '', - imageUrl: media ? getFileUrl('media', media.id, media.file) : '', - type: record.type, - stock: record.stock ?? null, - duration: record.duration ?? null, - bufferMinutes: record.bufferMinutes ?? null, - capacity: record.capacity ?? null, - active: record.active - }; - }); - - return { items, slots }; +export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> { + const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }); + return { items: records.map(mapItemRecord) }; +} + +export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string }; + +/** + * Times a customer can book for one service and duration, from the shop + * hook (GET /api/shop/slots), which applies every availability rule. When + * none start in [from, to), `next` is the first one after (or null). + */ +export function loadBookableTimes(pb: PocketBase, query: BookableTimesQuery) { + return pb.send<{ times: BookableTime[]; next: string | null }>('/api/shop/slots', { query, requestKey: null }); +} + +/** + * GET /api/slots in both apps (the Shop block's time picker): forwards + * ?item=&minutes=&from=&to= to the shop hook. A PocketBase error keeps its + * status and message; PocketBase being down is a 503. + */ +export async function bookableTimesResponse(pb: PocketBase, url: URL): Promise { + const param = (key: string) => url.searchParams.get(key) ?? ''; + try { + 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 }); + } } diff --git a/packages/shared/src/slots.ts b/packages/shared/src/slots.ts index 311ec0b..d02ba34 100644 --- a/packages/shared/src/slots.ts +++ b/packages/shared/src/slots.ts @@ -6,6 +6,7 @@ // zonedInputToIso, so a run across a DST change still starts at 09:00. 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. */ 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 - * admin (GET /api/shop/slots?detail=1). Places are taken by paid orders - * (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy` - * is the overlapping slot whose booking/hold blocks this one. + * A booked or held time, as the shop hook reports it to the admin: paid + * order lines (`booked`) and basket lines whose hold hasn't lapsed + * (`held`). The practitioner is busy until `readyAt` (end + get-ready time). + */ +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 & { id: string; - item: string; - itemName: string; - capacity: number; + kind: SlotKind; + items: string[]; + itemNames: string[]; notes: string; booked: number; held: number; - blockedBy: string; + // window + startTimes?: StartTimesMode; + free?: PlannedSlot[]; + // session + minutes?: number; + capacity?: number; + blockedBy?: SlotBooking | null; +}; + +export const START_TIMES_LABELS: Record = { + grid: 'Every 30 min', + edges: 'Next free time' +}; + +export const START_TIMES_HINTS: Record = { + 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'; @@ -70,12 +100,18 @@ export const SLOT_STATE_LABELS: Record = { }; /** - * `full` only when paid bookings fill a group; a slot whose last places are - * in baskets reads `held`, since it frees up again if those holds lapse. + * A window is `full` once no free time is left. A session is `full` only + * 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): SlotState { - if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked'; - if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held'; +export function slotState(slot: Pick): SlotState { + if (slot.kind === 'window') { + 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.held) return 'held'; return slot.blockedBy ? 'blocked' : 'free'; @@ -191,7 +227,22 @@ export type GeneratePlanInput = { 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): 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[] { const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes); const days = new Set(input.weekdays); diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 09e61c3..aa0a888 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -119,31 +119,42 @@ export const defaultPrivacy: PrivacyGlobal = { 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 = { id: string; name: string; description: string; + /** A product's price; for a service, its lowest duration price (kept in sync by the admin). */ price: number; image: string; // media record id imageUrl: string; // resolved URL (populated by server load) type: ItemType; stock: number | null; - duration: number | null; // minutes, for item_with_time - bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots - capacity: number | null; // places per slot (default for new slots; >1 = group session) + durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first + bufferMinutes: number | null; // get-ready time after each appointment + capacity: number | null; // places in a new group session (>1 = group) 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 - * with places left that no overlapping booking blocks. + * A time a customer can book, as the shop lists it (GET /api/shop/slots for + * one service and duration): a start time in a window, or a group session + * with places left. */ -export type SlotRecord = { - id: string; - item: string; // item id +export type BookableTime = { + slot: string; // slot id (window or session) + kind: SlotKind; start: string; end: string; - capacity: number; // places in total + capacity: number; // places in total (1 in a window) free: number; // places still bookable }; @@ -156,12 +167,16 @@ export type BasketLine = { slot: string | null; quantity: number; lineType: 'item' | 'slot'; + /** Slot lines: the booked time and length. */ + start?: string; + end?: string; + minutes?: number; // Expanded fields (populated server-side) 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; - slotStart?: string; - slotEnd?: string; + slotKind?: SlotKind; slotCapacity?: number; /** Slot lines: when the reservation lapses and the line is dropped (ISO). */ heldUntil?: string; @@ -211,6 +226,8 @@ export type OrderLine = { name: string; price: number; start: string | null; + /** Slot lines: the booked length. */ + minutes: number | null; }; // ── Block data types ──────────────────────────────────────────────────