Compare commits

...

4 commits

Author SHA1 Message Date
62025263c9 Shop picker: month arrows, jump to the first available date, +/- for group places
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 09:32:56 +00:00
021d06d3e4 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 09:32:56 +00:00
28773f2599 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 09:32:56 +00:00
214db95186 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
2026-10-24 09:32:56 +00:00
13 changed files with 414 additions and 93 deletions

View file

@ -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 `<input type="date">` 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

View file

@ -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.

View file

@ -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;
</script>
{#snippet basketIcon()}

View file

@ -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()
};
}

View file

@ -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 };
};

View file

@ -1,21 +1,12 @@
<script lang="ts">
import { onMount } from 'svelte';
import { formatInstant, formatPrice } from '$shared/calendar';
let { data } = $props();
// "Friday 15 January, 10:00" in the studio's timezone.
function formatSlotDate(iso?: string | null) {
if (!iso) return '';
return new Date(iso).toLocaleString(undefined, {
weekday: 'long',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
function formatPrice(amount: number) {
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
return formatInstant(iso, data.timezone, { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' });
}
</script>

View file

@ -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<typeof createBasketStore>;
export function createBasketStore(initial: Basket | null) {
let lines = $state<BasketLine[]>(initial?.lines ?? []);
let status = $state<Basket['status']>(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<string, unknown>): Promise<Basket | null> {
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);
}

View file

@ -1,8 +1,11 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { goto } from '$app/navigation';
import type { CheckoutBlockData } from '$shared/types';
import { page } from '$app/state';
import type { BasketLine, CheckoutBlockData } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar';
import { loadStripe } from '$shared/stripe-client';
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
@ -38,23 +41,79 @@
lastSig = sig;
});
const currency = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
const payLabel = $derived(
payState === 'confirming'
? 'Confirming…'
: payState === 'creating'
? 'Preparing payment…'
: `Pay ${currency.format(basket.total)}`
: `Pay ${formatPrice(basket.total)}`
);
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
/** "Fri 15 Jan, 10:00" in the studio's timezone. */
function formatSlotTime(iso: string) {
return new Date(iso).toLocaleString(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
return formatInstant(iso, timezone, { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}
// ── Reservation countdown ───────────────────────────────────────────
// Time slots are held for a while after being added (longer once payment
// starts). Show how long is left, offer more time near the end, and say
// so when a reservation runs out instead of the line silently vanishing.
/** Offer "keep my reservation" once less than this is left. */
const RENEW_OFFER_MS = 3 * 60 * 1000;
// null until mounted, so the server render shows no (soon wrong) countdown.
let now = $state<number | null>(null);
onMount(() => {
now = Date.now();
const timer = setInterval(() => (now = Date.now()), 1000);
return () => clearInterval(timer);
});
const holdLeftMs = $derived(now === null || basket.holdDeadline === null ? null : Math.max(0, basket.holdDeadline - now));
const slotLineCount = $derived(basket.lines.filter((l) => l.lineType === 'slot').length);
let renewing = $state(false);
/** Reservations that ran out while this page was open, e.g. "Group class, Fri 15 Jan, 10:00". */
let lapsed = $state<string[]>([]);
let nextLapseCheck = 0;
function formatCountdown(ms: number) {
const seconds = Math.ceil(ms / 1000);
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
}
function describeLine(line: BasketLine) {
return [line.itemName ?? 'A time slot', line.slotStart ? formatSlotTime(line.slotStart) : ''].filter(Boolean).join(', ');
}
// At zero, reload the basket: the server drops the lapsed line. Retry every
// few seconds in case its clock is slightly behind.
$effect(() => {
if (holdLeftMs !== 0 || now === null || now < nextLapseCheck) return;
nextLapseCheck = now + 5000;
void checkLapsed();
});
async function checkLapsed() {
const before = basket.lines.filter((l) => l.lineType === 'slot');
await basket.refresh();
const gone = before.filter((l) => !basket.lines.some((line) => line.id === l.id));
if (gone.length) lapsed = [...lapsed, ...gone.map(describeLine)];
}
async function renewHolds() {
if (renewing) return;
renewing = true;
errorMsg = '';
try {
await basket.renewHolds();
} catch (e) {
errorMsg = e instanceof Error ? e.message : 'Could not extend your reservation.';
} finally {
renewing = false;
}
}
function resetPayment() {
@ -115,6 +174,8 @@
);
}
const { clientSecret } = await res.json();
// Starting payment holds the slots longer; show the new countdown.
await basket.refresh();
stripe = await loadStripe();
if (!stripe) throw new Error('Payment system failed to load. Please refresh and try again.');
@ -209,14 +270,59 @@
<p class="mt-2 text-fg-body/70">{data.heading}</p>
{/if}
{#if lapsed.length}
<div class="mt-8 flex items-start justify-between gap-3 rounded-2xl border border-terracotta/40 bg-terracotta/10 px-5 py-4 text-sm text-charcoal" role="alert">
<div>
<p class="font-medium">
{lapsed.length === 1 ? 'Your reservation ran out' : 'Some reservations ran out'}, so {lapsed.length === 1 ? 'it was' : 'they were'} taken out of your basket:
</p>
<ul class="mt-1 list-disc pl-5">
{#each lapsed as description, i (i)}
<li>{description}</li>
{/each}
</ul>
<p class="mt-1 text-charcoal/70">You can pick the time again in the shop if it’s still free.</p>
</div>
<button type="button" class="shrink-0 font-bold" aria-label="Dismiss" onclick={() => (lapsed = [])}>✕</button>
</div>
{/if}
{#if basket.lines.length === 0}
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center">
<p class="font-serif text-xl">Your basket is empty</p>
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
</div>
{:else}
{#if holdLeftMs !== null && slotLineCount}
{@const ending = holdLeftMs < RENEW_OFFER_MS}
<div
class="mt-8 flex flex-wrap items-center justify-between gap-3 rounded-2xl border px-5 py-3 text-sm {ending
? 'border-terracotta/40 bg-terracotta/10'
: 'border-sage/30 bg-sage/10'}"
role="timer"
aria-live={ending ? 'polite' : 'off'}
>
<p>
{slotLineCount === 1 ? 'Your time is' : 'Your times are'} reserved for
<strong class="tabular-nums">{formatCountdown(holdLeftMs)}</strong>{ending
? ' — after that it goes back to the shop.'
: '.'}
</p>
{#if ending && payState !== 'confirming'}
<button
type="button"
class="rounded-full border border-charcoal/20 bg-white px-4 py-1.5 font-medium transition hover:bg-charcoal/5 disabled:opacity-60"
disabled={renewing}
onclick={renewHolds}
>
{renewing ? 'Extending…' : 'Keep it 10 more minutes'}
</button>
{/if}
</div>
{/if}
<!-- Basket lines -->
<ul class="mt-8 space-y-4">
<ul class="{holdLeftMs !== null && slotLineCount ? 'mt-4' : 'mt-8'} space-y-4">
{#each basket.lines as line (line.id)}
{@const pending = pendingLines.has(line.id)}
<li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
@ -237,7 +343,7 @@
{#if line.lineType === 'slot' && line.slotStart}
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
{/if}
<p class="text-sm text-fg-body/70">{currency.format(line.itemPrice ?? 0)}</p>
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice ?? 0)}</p>
</div>
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
@ -266,7 +372,7 @@
{/if}
<p class="w-20 shrink-0 text-right font-medium">
{currency.format((line.itemPrice ?? 0) * line.quantity)}
{formatPrice((line.itemPrice ?? 0) * line.quantity)}
</p>
<button
@ -286,7 +392,7 @@
<div class="mt-6 rounded-2xl border border-charcoal/10 bg-white p-5">
<div class="flex items-center justify-between">
<span class="text-fg-body/70">Subtotal</span>
<span class="font-serif text-xl font-bold">{currency.format(basket.total)}</span>
<span class="font-serif text-xl font-bold">{formatPrice(basket.total)}</span>
</div>
</div>
@ -368,7 +474,7 @@
</div>
{/if}
{#if basketChanged}
{#if basketChanged && !lapsed.length}
<p class="mt-4 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm">
Basket changed — please press Pay again.
</p>
@ -388,7 +494,7 @@
disabled={payState === 'confirming'}
onclick={confirmPayment}
>
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${currency.format(basket.total)}`}
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${formatPrice(basket.total)}`}
</button>
{/if}

View file

@ -1,8 +1,9 @@
<script lang="ts">
import { invalidateAll } from '$app/navigation';
import type { ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
import { page } from '$app/state';
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte';
import { getCurrentAndNextMonths } from '$shared/calendar';
import { DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey } from '$shared/calendar';
import { formatDateKey } from '$shared/slots';
let { data = {}, items = [], slots = [] } = $props<{
data: ShopBlockData;
@ -21,14 +22,16 @@
errorMsg = $state<string | null>(null);
justAdded = $state(false);
pendingSlotId = $state<string | null>(null);
/** Months from the current one to the first month shown in the picker. */
monthOffset = $state(0);
}
let cardStates = $state<Record<string, CardState>>({});
const months = getCurrentAndNextMonths();
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
/** The picker shows this many months side by side; the arrows move one month. */
const MONTHS_SHOWN = 2;
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
let visibleItems: ItemRecord[] = $derived.by(() => {
let result: ItemRecord[] = items;
@ -44,13 +47,23 @@
return result;
});
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
// 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 slots) {
const day = new Date(slot.start);
if (Number.isNaN(day.getTime())) continue;
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
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();
@ -70,6 +83,18 @@
let isList = $derived(data.layout === 'list');
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
function monthOffsetOf(key: string) {
const today = new Date();
const [year, month] = key.split('-').map(Number);
return year * 12 + (month - 1) - (today.getFullYear() * 12 + today.getMonth());
}
function pickerMonths(offset: number) {
const first = addMonths(startOfMonth(new Date()), offset);
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1));
}
// Lazily create card state for whatever items are rendered.
$effect(() => {
for (const item of visibleItems) {
@ -84,6 +109,15 @@
state.errorMsg = null;
state.justAdded = false;
state.selectedDayKey = null;
state.monthOffset = 0;
}
/** Show the month of the first available day and select it. */
function showFirstAvailable(itemId: string, key: string) {
const state = cardStates[itemId];
if (!state) return;
state.monthOffset = Math.max(0, monthOffsetOf(key));
state.selectedDayKey = key;
}
function errorMessage(e: unknown, fallback: string) {
@ -111,11 +145,10 @@
state.pendingSlotId = slotId;
state.errorMsg = null;
try {
// The store reloads the listing afterwards: a booking can block other
// times (one practitioner) or fill a group session.
await basket.addSlotLine(slotId);
state.justAdded = true;
// A booking can block other times (one practitioner) or fill a
// group session — reload the listing so the picker shows that.
await invalidateAll();
} catch (e) {
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
} finally {
@ -124,8 +157,31 @@
}
}
/** 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) {
const state = cardStates[itemId];
if (!state || state.adding) return;
state.adding = true;
state.pendingSlotId = line.slot;
state.errorMsg = null;
try {
const seats = line.quantity + delta;
if (seats < 1) await basket.removeLine(line.id);
else await basket.updateQuantity(line.id, seats);
} catch (e) {
state.errorMsg = errorMessage(e, 'Could not change the number of places.');
} finally {
state.adding = false;
state.pendingSlotId = null;
}
}
function formatTime(iso: string) {
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
return formatInstant(iso, timezone, { hour: '2-digit', minute: '2-digit' });
}
function placesLeft(free: number) {
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left';
}
</script>
@ -178,7 +234,7 @@
{/if}
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
<span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price)}</span>
{#if isService && item.duration != null}
<span class="text-xs text-charcoal/60">{item.duration} min</span>
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
@ -245,8 +301,53 @@
</div>
{#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)}
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
<div class="mb-3 flex items-center justify-between gap-2">
<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"
aria-label="Previous month"
disabled={ui.monthOffset <= 0}
onclick={() => ui.monthOffset--}
>
‹
</button>
<p class="text-sm font-medium text-charcoal/70">Select a date</p>
<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"
aria-label="Next month"
disabled={ui.monthOffset >= lastOffset}
onclick={() => ui.monthOffset++}
>
›
</button>
</div>
{#if !anyShown && availableKeys.length}
<!-- Nothing in the months on screen: say when the next date is, so
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">
<span>
{availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'}
<strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>.
</span>
<button
type="button"
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 {availableKeys[0] > shownTo ? 'first' : 'next'} available date →
</button>
</div>
{/if}
<div class="grid gap-6 sm:grid-cols-2">
{#each months as month (month.label)}
<div>
@ -282,34 +383,64 @@
{#if ui.selectedDayKey}
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
<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' })}
</p>
<div class="flex flex-wrap gap-2">
{#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}
<button
type="button"
disabled={(slotInBasket && !isGroup) || ui.adding}
title={isGroup && slotInBasket ? 'Add another place' : undefined}
onclick={() => addSlot(item.id, slot.id)}
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
? `border-transparent bg-sage/15 text-sage-dark ${isGroup ? 'hover:bg-sage/30' : 'cursor-not-allowed'}`
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
!slotInBasket
? 'cursor-wait'
: ''}"
>
{#if ui.pendingSlotId === slot.id}
<span class="loading loading-spinner loading-xs"></span>
{/if}
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{isGroup
? ` · ${slot.free} ${slot.free === 1 ? 'place' : 'places'} left`
: ''}{slotInBasket ? (isGroup ? ` · ${seatsInBasket} in basket` : ' · In basket') : ''}
</button>
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
{#if isGroup && line}
<!-- 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">
<span>{label} · {placesLeft(slot.free)}</span>
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
<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"
aria-label="One place fewer"
disabled={ui.adding}
onclick={() => changeSeats(item.id, line, -1)}
>
−
</button>
<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}
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span>
</span>
<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"
aria-label="One place more"
disabled={ui.adding || slot.free <= 0}
onclick={() => changeSeats(item.id, line, 1)}
>
+
</button>
</span>
</div>
{:else}
<button
type="button"
disabled={!!line || ui.adding}
onclick={() => addSlot(item.id, slot.id)}
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {line
? '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 &&
!line
? 'cursor-wait'
: ''}"
>
{#if ui.pendingSlotId === slot.id}
<span class="loading loading-spinner loading-xs"></span>
{/if}
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
</button>
{/if}
{/each}
</div>
{:else}
{:else if anyShown}
<p class="mt-4 text-sm text-charcoal/60">
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
</p>

View file

@ -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)}`;
}

View file

@ -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<SlotState, string> = {
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<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): 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. */

View file

@ -144,6 +144,8 @@ export type BasketLine = {
slotStart?: string;
slotEnd?: string;
slotCapacity?: number;
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
heldUntil?: string;
};
export type Basket = {
@ -154,6 +156,8 @@ export type Basket = {
customerDetails: CustomerDetails | null;
stripePaymentIntentId: string | null;
lines: BasketLine[];
/** Server clock (epoch ms) when this was read, so browsers with a wrong clock count holds down correctly. */
serverNow?: number;
};
export type CustomerDetails = {

View file

@ -275,8 +275,9 @@ function createBasket(app) {
/**
* Renew the hold on every slot line in a basket. Used at checkout start
* (30 min) and after a failed payment (10 min, so the customer can retry).
* A live hold is simply extended (its seats are already counted). A lapsed
* (30 min), after a failed payment (10 min, so the customer can retry) and
* when the customer asks for more time (`renew_holds`, 10 min). A live hold
* is extended, never shortened (its seats are already counted). A lapsed
* one that hasn't been swept yet is rescued only if its seats are still
* free and nothing has blocked the time since — otherwise it's left for
* the sweep, and checkout tells the customer the slot expired.
@ -285,9 +286,12 @@ function extendBasketHolds(app, basketId, durationMs) {
const now = Date.now();
const until = isoIn(durationMs);
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
if (toMs(line.getString('heldUntil')) > now) {
line.set('heldUntil', until);
app.save(line);
const heldUntil = toMs(line.getString('heldUntil'));
if (heldUntil > now) {
if (heldUntil < now + durationMs) {
line.set('heldUntil', until);
app.save(line);
}
continue;
}
try {
@ -379,6 +383,13 @@ function basketAction(app, body) {
break;
}
case 'renew_holds': {
// "Keep my reservation" at checkout. Holds that already lapsed were
// swept above; the customer is told and picks the time again.
extendBasketHolds(app, basket.id, SLOT_HOLD_MS);
break;
}
case 'remove_line': {
const line = lines.find((l) => l.id === String(body.lineId || ''));
if (!line) throw new NotFoundError('Line not found in your basket');