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