From 214db9518683fadc4635d3250bae5047b6119d3f Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 09:32:56 +0000 Subject: [PATCH 1/4] Show dates, times and prices in a European format and the studio's timezone Formatting with the default locale rendered US dates (MM/DD/YYYY, 12-hour) on the server. Everything shown to people now uses DISPLAY_LOCALE (en-GB) and booking times use SITE_TIMEZONE. The public layout reloads on every navigation so places left are never stale. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- AGENTS.md | 1 + app-public/src/lib/components/Header.svelte | 5 ++- app-public/src/routes/+layout.server.ts | 14 ++++++-- .../src/routes/checkout/return/+page.svelte | 15 ++------- packages/shared/src/calendar.ts | 33 ++++++++++++++++--- 5 files changed, 47 insertions(+), 21 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f5ada8f..12a2b43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,6 +142,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel). - Server actions wrap PocketBase writes in `attempt()` from `$lib/server/actions` so failures show as an error banner, not a 500. - Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`. +- **Dates, times and prices shown to people** use `DISPLAY_LOCALE` (`en-GB`: day-month-year, 24-hour clock) and the helpers in `$shared/calendar` (`formatInstant`, `formatPrice`, `formatDateTime`) — never `toLocale*(undefined)`, which renders US formats on the server. Booking times on the public site are shown in `SITE_TIMEZONE` too (layout data `timezone`, read by blocks via `page.data.timezone`). Native `` fields follow the visitor's browser language and can't be changed from the page. - **Dates/times in admin**: entered and displayed in `SITE_TIMEZONE` (layout data `timezone`), via `toZonedDatetimeInput`, `zonedInputToIso`, `formatDateTime` in `$shared/calendar`. Never `new Date(localInput)` on the server — the container runs in UTC. - **Prose**: `.prose-wellness` class for rich text content styling diff --git a/app-public/src/lib/components/Header.svelte b/app-public/src/lib/components/Header.svelte index 69caf2d..490ac3e 100644 --- a/app-public/src/lib/components/Header.svelte +++ b/app-public/src/lib/components/Header.svelte @@ -3,6 +3,7 @@ import { page } from '$app/state'; import type { HeaderGlobal } from '$lib/types'; import { getBasketContext } from '$lib/basket.svelte'; + import { formatPrice } from '$shared/calendar'; let { header } = $props<{ header: HeaderGlobal }>(); @@ -29,9 +30,7 @@ return href === '/' ? path === '/' : path === href || path.startsWith(href + '/'); } - function formatTotal(amount: number) { - return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount); - } + const formatTotal = formatPrice; {#snippet basketIcon()} diff --git a/app-public/src/routes/+layout.server.ts b/app-public/src/routes/+layout.server.ts index bbe2ecc..8a95977 100644 --- a/app-public/src/routes/+layout.server.ts +++ b/app-public/src/routes/+layout.server.ts @@ -2,6 +2,8 @@ import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import type { ItemRecord, SlotRecord } from '$lib/types'; import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; import { loadShopData } from '$shared/server/shop'; +import { DEFAULT_TIMEZONE } from '$shared/calendar'; +import { env } from '$env/dynamic/private'; import type { LayoutServerLoad } from './$types'; async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { @@ -13,7 +15,12 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { } } -export const load: LayoutServerLoad = async ({ locals, cookies }) => { +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. + void url.pathname; + const [header, footer, colors] = await Promise.all([ getGlobal(locals.pb, 'header', defaultHeader), getGlobal(locals.pb, 'footer', defaultFooter), @@ -35,5 +42,8 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => { const items: ItemRecord[] = shop?.items ?? []; const slots: SlotRecord[] = shop?.slots ?? []; - return { header, footer, colors, user: locals.user, basket, items, slots }; + // Booking times are shown in the studio's timezone, wherever the visitor is. + const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE; + + return { header, footer, colors, user: locals.user, basket, items, slots, timezone }; }; diff --git a/app-public/src/routes/checkout/return/+page.svelte b/app-public/src/routes/checkout/return/+page.svelte index 15f9406..1b090f7 100644 --- a/app-public/src/routes/checkout/return/+page.svelte +++ b/app-public/src/routes/checkout/return/+page.svelte @@ -1,21 +1,12 @@ diff --git a/packages/shared/src/calendar.ts b/packages/shared/src/calendar.ts index 0531adb..7c24cf8 100644 --- a/packages/shared/src/calendar.ts +++ b/packages/shared/src/calendar.ts @@ -48,6 +48,31 @@ export function dateInputToPocketBase(value: string, allDay = true, timeZone = ' return `${value.slice(0, 10)} 00:00:00.000Z`; } +/** + * Locale for every date, time and price shown to people: day-month-year and + * a 24-hour clock. Fixed (not the visitor's or server's default, which is + * en-US in the container) so the server render and the browser agree. + */ +export const DISPLAY_LOCALE = 'en-GB'; + +/** Fallback when no SITE_TIMEZONE reaches the page. */ +export const DEFAULT_TIMEZONE = 'Europe/Oslo'; + +export function formatPrice(amount: number) { + return new Intl.NumberFormat(DISPLAY_LOCALE, { style: 'currency', currency: 'EUR' }).format(amount); +} + +/** Format an instant in `timeZone` with the display locale. */ +export function formatInstant(value: string | null | undefined, timeZone: string, options: Intl.DateTimeFormatOptions) { + const date = parseInstant(value); + return date ? new Intl.DateTimeFormat(DISPLAY_LOCALE, { ...options, timeZone }).format(date) : ''; +} + +/** The calendar date (`YYYY-MM-DD`) of an instant in `timeZone`. */ +export function zonedDateKey(value: string | null | undefined, timeZone: string) { + return toZonedDatetimeInput(value, timeZone).slice(0, 10); +} + // ── Site-timezone helpers ────────────────────────────────────────────── // Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so // what the admin types is what customers book, and the server render (UTC @@ -114,14 +139,14 @@ export function toZonedDatetimeInput(value: string | null | undefined, timeZone: export function formatDateTime(value: string | null | undefined, timeZone: string) { const date = parseInstant(value); if (!date) return ''; - return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date); + return new Intl.DateTimeFormat(DISPLAY_LOCALE, { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date); } /** "10:00" in `timeZone`. */ export function formatTime(value: string | null | undefined, timeZone: string) { const date = parseInstant(value); if (!date) return ''; - return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date); + return new Intl.DateTimeFormat(DISPLAY_LOCALE, { timeZone, timeStyle: 'short' }).format(date); } export function parseEventDate(value?: string | null) { @@ -184,7 +209,7 @@ export function createCalendarMonth(monthDate: Date, reference = new Date(), wee return { date: first, - label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }), + label: first.toLocaleDateString(DISPLAY_LOCALE, { month: 'long', year: 'numeric' }), days }; } @@ -264,7 +289,7 @@ export function formatEventDateRange(event: CalendarEventRecord) { const start = parseEventDate(event.start); const end = parseEventDate(event.end); if (!start) return ''; - const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' }); + const formatter = new Intl.DateTimeFormat(DISPLAY_LOCALE, { month: 'short', day: 'numeric' }); if (!end || dateKey(start) === dateKey(end)) return formatter.format(start); return `${formatter.format(start)} – ${formatter.format(end)}`; } From 28773f2599f338dd4e24c3c6bddb4872852be5a3 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 09:32:56 +0000 Subject: [PATCH 2/4] Admin slots: a slot held in a basket reads 'In a basket', not 'Full' 'Full' is now only for a group session filled by paid bookings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- packages/shared/src/slots.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/slots.ts b/packages/shared/src/slots.ts index dc69b2c..311ec0b 100644 --- a/packages/shared/src/slots.ts +++ b/packages/shared/src/slots.ts @@ -5,7 +5,7 @@ // the site's timezone; they become UTC instants only at the very end, via // zonedInputToIso, so a run across a DST change still starts at 09:00. -import { toZonedDatetimeInput, zonedInputToIso } from './calendar'; +import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar'; /** 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 }; @@ -69,8 +69,13 @@ export const SLOT_STATE_LABELS: Record = { blocked: 'Blocked' }; +/** + * `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. + */ export function slotState(slot: Pick): SlotState { - if (slot.booked + slot.held >= slot.capacity) return 'full'; + if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked'; + if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held'; if (slot.booked) return 'booked'; if (slot.held) return 'held'; return slot.blockedBy ? 'blocked' : 'free'; @@ -143,7 +148,7 @@ export function addMonthsToKey(month: string, months: number) { /** Format a date key with fixed locale (SSR and browser agree), e.g. "Tuesday 3 November". */ export function formatDateKey(key: string, options: Intl.DateTimeFormatOptions) { const ms = keyToUtcMs(key); - return ms === null ? '' : new Intl.DateTimeFormat('en-GB', { ...options, timeZone: 'UTC' }).format(ms); + return ms === null ? '' : new Intl.DateTimeFormat(DISPLAY_LOCALE, { ...options, timeZone: 'UTC' }).format(ms); } /** `09:30` → 570, or null. */ From 021d06d3e44832f2a7204449ad14bf1529251bb5 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 09:32:56 +0000 Subject: [PATCH 3/4] Checkout: reservation countdown, 'keep it 10 more minutes', and a message when a hold runs out Basket changes that free or take places reload the page data, so places removed from the basket show up in the shop again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- README.md | 2 +- app-public/src/lib/server/shop.ts | 6 +- packages/shared/src/basket.svelte.ts | 44 +++++- .../shared/src/blocks/CheckoutBlock.svelte | 138 ++++++++++++++++-- packages/shared/src/types.ts | 4 + pocketbase/pb_hooks/shop/lib.js | 21 ++- 6 files changed, 187 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 15f1d2f..19a75e0 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ The shop/checkout blocks implement a basket-based booking flow: visitors add ser **Slot availability** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live): -- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line. +- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does. - One practitioner works every service, so a slot with **any** place taken blocks every other slot that overlaps it — whatever the service — counting each service's get-ready time (`items.bufferMinutes`) after it. The client can offer three massages at 10:00; once one is in a basket or booked, the other two disappear. A group session with one place booked blocks massages at that time too, while staying bookable itself until full. - `GET /api/shop/slots` lists the bookable future slots (public; feeds the Shop block). With `?detail=1` a signed-in admin gets every slot in a range with booked/held places and what blocks it (the `/slots` page). - Adding to a basket (`add_slot`, with `seats`) and changing a group line's places re-check capacity and blocking inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts index 245a58e..bc1acc5 100644 --- a/app-public/src/lib/server/shop.ts +++ b/app-public/src/lib/server/shop.ts @@ -73,7 +73,8 @@ export function mapBasket(payload: BasketPayload): Basket | null { itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, slotStart: slot?.start, slotEnd: slot?.end, - slotCapacity: slot?.capacity + slotCapacity: slot?.capacity, + heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined }; }); return { @@ -83,7 +84,8 @@ export function mapBasket(payload: BasketPayload): Basket | null { email: record.email || null, customerDetails: record.customerDetails || null, stripePaymentIntentId: record.stripePaymentIntentId || null, - lines: mappedLines + lines: mappedLines, + serverNow: Date.now() }; } diff --git a/packages/shared/src/basket.svelte.ts b/packages/shared/src/basket.svelte.ts index d87521e..6440820 100644 --- a/packages/shared/src/basket.svelte.ts +++ b/packages/shared/src/basket.svelte.ts @@ -1,4 +1,5 @@ import { getContext, setContext } from 'svelte'; +import { invalidateAll } from '$app/navigation'; import type { Basket, BasketLine } from './types'; const BASKET_KEY = 'basket'; @@ -8,12 +9,20 @@ export type BasketStore = ReturnType; export function createBasketStore(initial: Basket | null) { let lines = $state(initial?.lines ?? []); let status = $state(initial?.status ?? 'active'); + // Browser clock minus server clock, so hold countdowns survive a wrong clock. + let clockOffset = $state(clockOffsetOf(initial)); const total = $derived( lines.reduce((sum, line) => sum + (line.itemPrice ?? 0) * line.quantity, 0) ); const count = $derived(lines.reduce((sum, line) => sum + line.quantity, 0)); + /** When the first slot reservation in the basket lapses, in browser-clock ms (null: none). */ + const holdDeadline = $derived.by(() => { + const ends = lines.filter((l) => l.lineType === 'slot' && l.heldUntil).map((l) => Date.parse(l.heldUntil!)); + return ends.length ? Math.min(...ends) + clockOffset : null; + }); + async function callApi(body: Record): Promise { const res = await fetch('/api/basket', { method: 'POST', @@ -31,13 +40,27 @@ export function createBasketStore(initial: Basket | null) { function applyBasket(basket: Basket | null) { lines = basket?.lines ?? []; status = basket?.status ?? 'active'; + clockOffset = clockOffsetOf(basket); + } + + /** + * Apply a basket change that can free or take slot places, then reload + * page data so shop listings (places left, blocked times) match it. + */ + async function applySlotChange(basket: Basket | null) { + applyBasket(basket); + await invalidateAll(); } async function refresh() { const res = await fetch('/api/basket'); if (!res.ok) return; const data = await res.json(); + const slotLines = () => lines.filter((l) => l.lineType === 'slot').length; + const before = slotLines(); applyBasket(data.basket); + // Lapsed reservations were dropped: their places are free again. + if (slotLines() < before) await invalidateAll(); } /** Overwrite local state from server-provided layout data. */ @@ -50,15 +73,20 @@ export function createBasketStore(initial: Basket | null) { } async function addSlotLine(slotId: string) { - applyBasket(await callApi({ action: 'add_slot', slotId })); + await applySlotChange(await callApi({ action: 'add_slot', slotId })); } async function updateQuantity(lineId: string, quantity: number) { - applyBasket(await callApi({ action: 'update_quantity', lineId, quantity })); + await applySlotChange(await callApi({ action: 'update_quantity', lineId, quantity })); } async function removeLine(lineId: string) { - applyBasket(await callApi({ action: 'remove_line', lineId })); + await applySlotChange(await callApi({ action: 'remove_line', lineId })); + } + + /** Hold the basket's time slots for another 10 minutes. */ + async function renewHolds() { + await applySlotChange(await callApi({ action: 'renew_holds' })); } return { @@ -74,15 +102,23 @@ export function createBasketStore(initial: Basket | null) { get status() { return status; }, + get holdDeadline() { + return holdDeadline; + }, refresh, syncFrom, addItemLine, addSlotLine, updateQuantity, - removeLine + removeLine, + renewHolds }; } +function clockOffsetOf(basket: Basket | null) { + return basket?.serverNow ? Date.now() - basket.serverNow : 0; +} + export function setBasketContext(store: BasketStore) { setContext(BASKET_KEY, store); } diff --git a/packages/shared/src/blocks/CheckoutBlock.svelte b/packages/shared/src/blocks/CheckoutBlock.svelte index 1cd7437..d092da3 100644 --- a/packages/shared/src/blocks/CheckoutBlock.svelte +++ b/packages/shared/src/blocks/CheckoutBlock.svelte @@ -1,8 +1,11 @@ @@ -178,7 +234,7 @@ {/if}
- {priceFormatter.format(item.price)} + {formatPrice(item.price)} {#if isService && item.duration != null} {item.duration} min {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} @@ -245,8 +301,53 @@
{#if isService && ui?.pickerOpen && itemSlotsByDay} + {@const availableKeys = [...itemSlotsByDay.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)}
-

Select a date

+
+ +

Select a date

+ +
+ + {#if !anyShown && availableKeys.length} + +
+ + {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} +
{#each months as month (month.label)}
@@ -282,34 +383,64 @@ {#if ui.selectedDayKey} {@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []} -

Available times

+

+ Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })} +

{#each daySlots as slot (slot.id)} - {@const seatsInBasket = basket.lines.find((l) => l.slot === slot.id)?.quantity ?? 0} - {@const slotInBasket = seatsInBasket > 0} + {@const line = basket.lines.find((l) => l.slot === slot.id)} {@const isGroup = slot.capacity > 1} - + {@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`} + {#if isGroup && line} + +
+ {label} · {placesLeft(slot.free)} + + + + {#if ui.pendingSlotId === slot.id}{:else}{line.quantity}{/if} + {line.quantity === 1 ? 'place' : 'places'} in your basket + + + +
+ {:else} + + {/if} {/each}
- {:else} + {:else if anyShown}

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