Compare commits

..

No commits in common. "650de78bac7113056bb9b1c5b4ff52d027e34b41" and "19b8bb121f23f42c3185006444a323c37b48b84c" have entirely different histories.

36 changed files with 1199 additions and 2271 deletions

View file

@ -29,14 +29,14 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events)
│ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── orders/ # Order list + booking-email status/resend
│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings
│ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
│ │ ├── backup/ # Export/import UI (calls api/export, api/import)
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
│ │ └── api/ # upload, export, import, slots (Shop block times in /preview) endpoints
│ │ └── api/ # upload, export, import endpoints
│ ├── hooks.server.ts # Auth guard — all routes except /login
│ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets
@ -60,7 +60,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
│ │ ├── +layout.svelte # Root layout (always renders Header/Footer)
│ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── api/ # basket, checkout, webhooks, slots (Shop block times) endpoints
│ │ ├── api/ # basket, checkout, webhooks endpoints
│ │ └── checkout/return/ # Stripe return URL
│ ├── hooks.server.ts # Creates PB client in locals (no auth guard)
│ └── app.css # Tailwind + DaisyUI + custom theme
@ -119,7 +119,6 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### Shared Code
- `packages/shared/src/types.ts` — all type definitions
- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block)
- `packages/shared/src/items.ts` — service durations (`parseDurations`, `formatDuration`, `lowestPrice`); which length costs what is charged by the shop hooks
- `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts`
- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'`
- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work
@ -132,7 +131,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them).
- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting.
- **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules.
- **Slot availability** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*.
- **Slot availability** (places + blocking by overlapping bookings, incl. get-ready time) is computed only by `slotStates()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots`, `?detail=1` for the admin). Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*.
- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email` and (during checkout) `baskets`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*.
- **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only).
@ -189,4 +188,4 @@ cd app-public && npm run build
- `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency.
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`). The Shop block fetches bookable times itself, per service and length, from `GET /api/slots` in each app (a proxy to `GET /api/shop/slots`); if it has nothing to show it says "Nothing is available".
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`; slots via `GET /api/shop/slots`); if a Shop block has nothing to show it says "Nothing is available".

View file

@ -112,12 +112,12 @@ If schema import fails because of a PocketBase version mismatch, create these co
Commerce collections (see the Stripe section above for context):
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `active` bool
- `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new slots), `active` bool
- `slots` — `item` relation→items, `start` date, `end` date, `capacity` number (places; >1 = group session), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold)
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `heldUntil` date (a slot line's hold)
- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty)
- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date and `minutes` number (nullable, the booked time)
- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot)
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool
> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Field config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`, number `min`/`max`/`onlyInt`) belongs at the field top level — 0.23 silently ignores anything nested under `options`, so the older number/text fields that still use `options` get no min/max on a fresh install. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass.
@ -138,8 +138,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages/[slug]` — block editor with draft preview
- `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services and products shown in Shop blocks
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). Windows may not overlap each other, nor sessions of the same service; bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.
- `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them.
- `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions.
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons
- `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*)
- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
@ -151,14 +150,12 @@ The shop/checkout blocks implement a basket-based booking flow: visitors add ser
**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that tidies expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
**Slot availability** (`availability()` / `windowStartTimes()` / `checkBooking()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live):
**Slot availability** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live):
- A **booking** is a paid order line or a basket line whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts), each with its own `start` and `minutes`. It keeps the practitioner busy until its service's get-ready time (`items.bufferMinutes`) is over. 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 no booking may overlap another — whatever the service, whatever the slot — including get-ready time.
- A **window** offers its services at any of their lengths. A booking must start and end inside it (its get-ready time may run past the end) and fit before the next booking. `startTimes = grid`: every `gridMinutes` (chosen per window: 10, 15, 20, 30, 45 or 60; default 30) from the window's start. `edges`: only right at the start or the end of each free stretch — a 09:00–12:00 window offers a 1-hour massage at 09:00 or 11:00; once 09:00 is booked (+15 min get-ready) it offers 10:15 or 11:00 — so time is taken from the ends and no gaps are left.
- A **group session** has `capacity` places for one service at one length; places are counted from its bookings. With any place taken its whole time is busy (windows lose that time); it stays bookable until full, and can't be booked while another booking overlaps it.
- `GET /api/shop/slots?item=&minutes=&from=&to=` lists the times a customer can book for one service and length (public; the Shop block fetches it through each app's `GET /api/slots` for the months on screen), plus `next` — the first bookable time after the range — when there are none in it. With `?detail=1` a signed-in admin gets every slot in a range with its bookings, free stretches and what blocks it (the `/slots` page).
- Adding to a basket (`add_slot`: `slotId` plus `itemId`, `minutes`, `start` for a window, or `seats` for a session) and changing a group line's places re-check everything inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. The price is the service's price for the booked length, read again at checkout.
- 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.
Setup:

View file

@ -26,9 +26,9 @@
<p class="font-semibold">Nothing to {deleting ? 'delete' : 'create'}.</p>
{/if}
<ul class="mt-1 list-inside list-disc text-base-content/70 empty:hidden">
{#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap another window, or a session of the same service.</li>{/if}
{#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.</li>{/if}
{#if preview.skippedPast}<li>{plural(preview.skippedPast, 'slot')} skipped — in the past.</li>{/if}
{#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — something in it is booked, or in a customer’s basket right now.</li>{/if}
{#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.</li>{/if}
</ul>
</div>
{/if}

View file

@ -33,7 +33,7 @@
<Modal bind:open title="Clear slots" wide>
<form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1">
<p class="text-sm text-base-content/70">Delete the windows and group sessions in a date range that have nothing booked. Slots with a booking, or with a time in a customer’s basket right now, are always kept.</p>
<p class="text-sm text-base-content/70">Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.</p>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
@ -49,7 +49,7 @@
<label class="fieldset">
<span class="fieldset-legend">Services</span>
<select class="select w-full" name="item" bind:value={draft.item}>
<option value="">All slots</option>
<option value="">All services</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>

View file

@ -58,7 +58,7 @@
<label class="fieldset">
<span class="fieldset-legend">Services</span>
<select class="select w-full" name="item" bind:value={draft.item}>
<option value="">All slots</option>
<option value="">All services</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>

View file

@ -2,14 +2,11 @@
import { untrack } from 'svelte';
import { enhance } from '$app/forms';
import Modal from '$lib/admin/Modal.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import { DEFAULT_GRID_MINUTES, GRID_STEP_OPTIONS, START_TIMES_LABELS, WEEKDAYS, startTimesHint, addDaysToKey, startTimesInWindows, timeToMinutes, type TimeWindow } from '$lib/slots';
import type { ItemDuration, SlotKind, StartTimesMode } from '$lib/types';
import { formatDuration } from '$shared/items';
import { WEEKDAYS, addDaysToKey, startTimesInWindows, type TimeWindow } from '$lib/slots';
import BulkActions from './BulkActions.svelte';
import { bulkForm } from './bulkForm.svelte';
type Service = { id: string; name: string; durations: ItemDuration[]; bufferMinutes: number; capacity: number };
type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number };
let {
open = $bindable(false),
@ -20,21 +17,14 @@
// Kept between openings, so a second run starts from the last settings.
let draft = $state({
kind: 'window' as SlotKind,
item: '',
fromDate: '',
toDate: '',
weekdays: [1, 2, 3, 4, 5],
windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[],
notes: '',
// windows
items: [] as string[],
startTimes: 'grid' as StartTimesMode,
gridMinutes: DEFAULT_GRID_MINUTES,
// group sessions
item: '',
minutes: '',
bufferMinutes: '',
capacity: ''
capacity: '',
notes: ''
});
const bulk = bulkForm(
@ -43,14 +33,11 @@
);
let service = $derived(items.find((item) => item.id === draft.item));
let sessionTimes = $derived(
service && draft.minutes ? startTimesInWindows(draft.windows, Number(draft.minutes), Number(draft.bufferMinutes) || 0) : []
);
let windowHours = $derived(
draft.windows.reduce((sum, w) => sum + Math.max(0, (timeToMinutes(w.to) ?? 0) - (timeToMinutes(w.from) ?? 0)), 0) / 60
let startTimes = $derived(
service ? startTimesInWindows(draft.windows, service.duration, Number(draft.bufferMinutes) || 0) : []
);
// Each opening starts without a stale preview; the first one also fills in dates and services.
// Each opening starts without a stale preview; the first one also fills in dates.
$effect(() => {
if (!open) return;
untrack(() => {
@ -58,9 +45,6 @@
if (!draft.fromDate) {
draft.fromDate = today;
draft.toDate = addDaysToKey(today, 27);
// One-to-one services by default; group classes get sessions.
const oneToOne = items.filter((item) => item.capacity <= 1).map((item) => item.id);
draft.items = oneToOne.length ? oneToOne : items.map((item) => item.id);
}
});
});
@ -69,7 +53,6 @@
draft.item = id;
// The service's own get-ready time and places are the defaults; both can be overridden here.
const item = items.find((item) => item.id === id);
draft.minutes = item?.durations[0] ? String(item.durations[0].minutes) : '';
draft.bufferMinutes = String(item?.bufferMinutes ?? 0);
draft.capacity = String(item?.capacity ?? 1);
}
@ -82,15 +65,15 @@
<Modal bind:open title="Generate slots" wide>
<form method="POST" action="?/generate" use:enhance={bulk.submit} class="space-y-1">
<input type="hidden" name="kind" value={draft.kind} />
<SegmentedControl
label="Create"
class="mb-2"
options={['window', 'session']}
value={draft.kind}
formatLabel={(v) => (v === 'window' ? 'Windows' : 'Group sessions')}
onChange={(v) => (draft.kind = v as SlotKind)}
/>
<label class="fieldset">
<span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}>
<option value="" disabled>Select a service…</option>
{#each items as item (item.id)}
<option value={item.id}>{item.name} ({item.duration} min)</option>
{/each}
</select>
</label>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
@ -113,7 +96,7 @@
</div>
<div class="fieldset">
<span class="fieldset-legend">{draft.kind === 'window' ? 'Windows each day' : 'Hours for sessions'} ({timezone})</span>
<span class="fieldset-legend">Opening hours ({timezone})</span>
<div class="space-y-2">
{#each draft.windows as window, i}
<div class="flex items-center gap-2">
@ -129,79 +112,28 @@
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addWindow}>+ Add hours (e.g. after a lunch break)</button>
</div>
{#if draft.kind === 'window'}
<div class="fieldset">
<span class="fieldset-legend">Services that can be booked</span>
<div class="grid gap-1 sm:grid-cols-2">
{#each items as item (item.id)}
<label class="label cursor-pointer gap-2 text-base-content">
<input class="checkbox checkbox-sm" type="checkbox" name="items" value={item.id} bind:group={draft.items} />
{item.name}
</label>
{/each}
</div>
</div>
<div class="fieldset">
<input type="hidden" name="startTimes" value={draft.startTimes} />
<SegmentedControl
label="Start times"
options={['grid', 'edges']}
value={draft.startTimes}
formatLabel={(v) => START_TIMES_LABELS[v as StartTimesMode]}
onChange={(v) => (draft.startTimes = v as StartTimesMode)}
/>
{#if draft.startTimes === 'grid'}
<label class="mt-2 flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-medium">Step</span>
<select class="select select-sm w-40" name="gridMinutes" bind:value={draft.gridMinutes}>
{#each GRID_STEP_OPTIONS as step (step)}<option value={step}>Every {step} min</option>{/each}
</select>
</label>
{/if}
<span class="label whitespace-normal">{startTimesHint(draft.startTimes, draft.gridMinutes)}</span>
</div>
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
{draft.windows.length} window{draft.windows.length === 1 ? '' : 's'} per chosen day, {windowHours} hours in total.
</p>
{:else}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}>
<option value="" disabled>Select a service…</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Length</span>
<select class="select w-full" name="minutes" required disabled={!service} bind:value={draft.minutes}>
{#each service?.durations ?? [] as duration (duration.minutes)}
<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>
{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span>
<input class="input w-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each session. Defaults to the service’s own.</span>
<span class="label">Gap after each appointment. Defaults to the service’s own.</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Places per session</span>
<span class="fieldset-legend">Places per slot</span>
<input class="input w-32" type="number" min="1" max="500" step="1" name="capacity" bind:value={draft.capacity} />
<span class="label">Defaults to the service’s own.</span>
<span class="label">More than 1 for a group session. Defaults to the service’s own.</span>
</label>
</div>
{#if service && draft.minutes}
{#if service}
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
{#if sessionTimes.length}
<span class="font-semibold">{sessionTimes.length} per day:</span> {sessionTimes.join(', ')}
{#if startTimes.length}
<span class="font-semibold">{startTimes.length} per day:</span> {startTimes.join(', ')}
{:else}
No {formatDuration(Number(draft.minutes))} session fits in these hours.
No {service.duration}-minute appointment fits in these hours.
{/if}
</p>
{/if}
{/if}
<label class="fieldset">
<span class="fieldset-legend">Notes <span class="font-normal text-base-content/50">(optional, added to every slot)</span></span>

View file

@ -1,7 +1,7 @@
// Server helpers for the /slots page. Planning is pure and lives in
// $shared/slots; this file does the PocketBase reads/writes around it.
import type { SlotBooking, SlotDetail } from '$lib/slots';
import type { SlotDetail } from '$lib/slots';
import type { createPocketBase } from '$lib/pb';
type Pb = ReturnType<typeof createPocketBase>;
@ -10,23 +10,21 @@ type Pb = ReturnType<typeof createPocketBase>;
const WRITE_CONCURRENCY = 5;
/**
* Slots with what's booked in them, from the shop hook — the same
* Slots with their places and blocking, from the shop hook — the same
* availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js).
* Either slots starting in `[from, to)` (optionally those offering one
* service) or one slot by id; `bookings` are all booked/held times starting
* in that range (for one slot: around its start).
* Either slots starting in `[from, to)` (optionally one service) or one slot by id.
*/
export async function loadSlotDetails(pb: Pb, query: { from: string; to: string; item?: string } | { id: string }) {
return pb.send<{ slots: SlotDetail[]; bookings: SlotBooking[] }>('/api/shop/slots', {
const { slots } = await pb.send<{ slots: SlotDetail[] }>('/api/shop/slots', {
query: { detail: 1, ...query },
requestKey: null
});
return slots;
}
/** One slot's details and its own bookings, or null if it doesn't exist (any other failure throws). */
/** One slot's details, or null if it doesn't exist (any other failure throws). */
export async function loadSlotDetail(pb: Pb, id: string) {
const { slots, bookings } = await loadSlotDetails(pb, { id });
return slots[0] ? { ...slots[0], bookings: bookings.filter((b) => b.slot === id) } : null;
return (await loadSlotDetails(pb, { id }))[0] ?? null;
}
export const seatsTaken = (slot: Pick<SlotDetail, 'booked' | 'held'>) => slot.booked + slot.held;

View file

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

View file

@ -1,6 +1,5 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { emailTemplateMeta, isEmailTemplateKey } from '$lib/email';
import { parseDurations } from '$shared/items';
import { isEmailConfigured, loadEmailSettings, loadEmailTemplate, sendTestEmail } from '$lib/server/email';
import type { EmailBlock } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
@ -21,10 +20,7 @@ async function findSampleService(pb: App.Locals['pb']) {
return pb
.collection('items')
.getFirstListItem("type = 'item_with_time' && active = true", { sort: 'name' })
.then((item) => {
const duration = parseDurations(item.durations)[0];
return { name: String(item.name), price: duration?.price ?? (Number(item.price) || 0), duration: duration?.minutes ?? null };
})
.then((item) => ({ name: String(item.name), price: Number(item.price) || 0, duration: Number(item.duration) || null }))
.catch(() => undefined);
}

View file

@ -1,68 +1,49 @@
import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import { mapItemRecord } from '$shared/server/shop';
import type { ItemDuration, ItemType } from '$lib/types';
import type { ItemRecord, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
/** Longest bookable length, in minutes (a booking must fit in one day's window). */
const MAX_DURATION_MINUTES = 12 * 60;
/** A service's lengths and prices from the form's `durationMinutes`/`durationPrice` rows (empty rows are skipped). */
function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
const minutes = data.getAll('durationMinutes').map((v) => String(v).trim());
const prices = data.getAll('durationPrice').map((v) => String(v).trim());
const durations: ItemDuration[] = [];
for (let i = 0; i < minutes.length; i++) {
if (minutes[i] === '' && (prices[i] ?? '') === '') continue;
const length = Number(minutes[i]);
const price = Number(prices[i]);
if (!Number.isInteger(length) || length < 5 || length > MAX_DURATION_MINUTES) return { error: `Each length must be a whole number of minutes from 5 to ${MAX_DURATION_MINUTES}.` };
if (prices[i] === '' || !Number.isFinite(price) || price < 0) return { error: `Give the ${length}-minute length a price (0 or more).` };
if (durations.some((d) => d.minutes === length)) return { error: `${length} minutes is listed twice.` };
durations.push({ minutes: length, price });
}
if (!durations.length) return { error: 'Add at least one length with its price.' };
return durations.sort((a, b) => a.minutes - b.minutes);
}
function itemPayload(data: FormData) {
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
const name = String(data.get('name') || '').trim();
if (!name) return { error: 'Name is required.' };
const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').trim();
let price: number;
let durations: ItemDuration[] = [];
if (type === 'item_with_time') {
const parsed = parseDurationRows(data);
if ('error' in parsed) return parsed;
durations = parsed;
// Kept as the lowest duration price: what "from …" and old readers show.
price = Math.min(...durations.map((d) => d.price));
} else {
price = parseFloat(String(data.get('price') || ''));
if (Number.isNaN(price) || price < 0) return { error: 'A valid price is required.' };
}
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null;
return {
payload: {
name,
name: String(data.get('name') || '').trim(),
description: String(data.get('description') || '').trim(),
price,
price: parseFloat(String(data.get('price') || '')),
image: String(data.get('image') || '').trim(),
type,
stock: Number.isNaN(stock) ? null : stock,
durations,
duration: Number.isNaN(duration) ? null : duration,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
capacity: Number.isNaN(capacity) ? null : capacity,
active: String(data.get('active')) === 'true'
}
};
}
function normalizeItem(record: Record<string, any>): ItemRecord {
const media = record.expand?.image;
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: record.type === 'item_with_time' ? 'item_with_time' : 'item',
stock: record.stock ?? null,
duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
};
}
@ -71,32 +52,34 @@ export const load: PageServerLoad = async ({ locals }) => {
.collection('items')
.getFullList({ sort: 'name', expand: 'image' })
.catch(() => []);
return { items: records.map(mapItemRecord) };
const items = records.map((record) => normalizeItem(record));
return { items };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const result = itemPayload(await request.formData());
if ('error' in result) return fail(400, { message: result.error });
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload));
if (!created.ok) return created.failure;
const data = await request.formData();
const payload = itemPayload(data);
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload));
if (!result.ok) return result.failure;
return { ok: true };
},
update: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' });
const result = itemPayload(data);
if ('error' in result) return fail(400, { message: result.error });
const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload));
if (!updated.ok) return updated.failure;
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload));
if (!result.ok) return result.failure;
return { ok: true };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' });
const result = await attempt('Could not delete the item — if it has past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
const result = await attempt('Could not delete the item — if it has slots or past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
if (!result.ok) return result.failure;
return { ok: true };
}

View file

@ -3,7 +3,6 @@
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
import type { ItemRecord, ItemType } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props();
let items = $derived(data.items || []);
@ -21,8 +20,7 @@
imageUrl: string;
type: ItemType;
stock: string;
/** Service lengths and prices, as typed (one form row each). */
durations: { minutes: string; price: string }[];
duration: string;
bufferMinutes: string;
capacity: string;
active: boolean;
@ -34,17 +32,7 @@
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true };
}
function addDuration() {
const last = Number(draft.durations.at(-1)?.minutes) || 0;
draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' });
}
/** "1 hour / 2 hours" for the table. */
function durationList(item: ItemRecord) {
return item.durations.map((d) => formatDuration(d.minutes)).join(' / ') || 'no lengths set';
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true };
}
function createItem() {
@ -63,7 +51,7 @@
imageUrl: item.imageUrl,
type: item.type,
stock: item.stock == null ? '' : String(item.stock),
durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }],
duration: item.duration == null ? '' : String(item.duration),
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active
@ -121,9 +109,9 @@
</div>
</td>
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}</td>
<td>{money.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
<td>{item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td>
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td>
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr>
@ -152,6 +140,11 @@
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Price ({data.currency})</span>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Type</span>
<select class="select w-full" name="type" bind:value={draft.type}>
@ -159,52 +152,28 @@
<option value="item_with_time">Service (bookable)</option>
</select>
</label>
</div>
{#if draft.type === 'item'}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Price ({data.currency})</span>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Stock</span>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
</div>
{:else}
<div class="fieldset">
<span class="fieldset-legend">Lengths and prices</span>
<div class="space-y-2">
{#each draft.durations as row, i}
<div class="flex flex-wrap items-center gap-2">
<label class="input w-36">
<input type="number" min="5" max="720" step="5" name="durationMinutes" required aria-label="Length in minutes" bind:value={row.minutes} />
<span class="label">min</span>
</label>
<label class="input w-40">
<input type="number" min="0" step="0.01" name="durationPrice" required aria-label="Price for this length" bind:value={row.price} />
<span class="label">{data.currency}</span>
</label>
{#if Number(row.minutes) >= 5}<span class="text-sm text-base-content/60">{formatDuration(Number(row.minutes))}</span>{/if}
{#if draft.durations.length > 1}
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove this length" onclick={() => draft.durations.splice(i, 1)}>✕</button>
{/if}
</div>
{/each}
</div>
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addDuration}>+ Add a length</button>
<span class="label">Customers pick a length with a slider in the shop; the price follows it.</span>
</div>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Duration (minutes)</span>
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span>
<input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each appointment, before the next one can start</span>
<span class="label">Gap after each appointment — between generated slots, and before another service can start</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Places in a group session</span>
<span class="fieldset-legend">Places per slot</span>
<input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} />
<span class="label">Only for group sessions (Slots → group session). New sessions start with this.</span>
<span class="label">1 for one-to-one; more for a group session. New slots start with this.</span>
</label>
</div>
{/if}

View file

@ -39,8 +39,7 @@ export const load: PageServerLoad = async ({ locals }) => {
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : '',
minutes: Number(line.minutes) || 0
start: line.start ? String(line.start) : ''
}))
}));

View file

@ -1,7 +1,6 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { formatDateTime } from '$lib/calendar';
import { formatDuration } from '$shared/items';
let { data, form } = $props();
let orders = $derived(data.orders || []);
@ -73,7 +72,7 @@
<li>
{line.quantity}× {line.name} — {money.format(line.price)}
{#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</span>
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}</span>
{/if}
</li>
{/each}

View file

@ -3,15 +3,14 @@ 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 and upcoming events (Shop blocks fetch
// bookable times themselves). Failures leave
// any block might need: shop items/slots and upcoming events. 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: [] };
return { items: [], slots: [] };
}),
locals.pb
.collection('events')

View file

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

View file

@ -5,8 +5,6 @@ import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots';
import {
DEFAULT_GRID_MINUTES,
GRID_STEP_OPTIONS,
MAX_BULK_SLOTS,
addDaysToKey,
dateKeysBetween,
@ -16,7 +14,6 @@ import {
monthGridKeys,
overlapsAny,
planGeneratedSlots,
planWindows,
shiftByDays,
timeToMinutes,
type BulkResult,
@ -24,25 +21,16 @@ import {
type SlotDetail,
type TimeWindow
} from '$lib/slots';
import type { SlotKind, StartTimesMode } from '$lib/types';
import { parseDurations } from '$shared/items';
import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>;
/** What a slot record is saved with. */
type SlotFields = {
kind: SlotKind;
items: string[];
start: string;
end: string;
startTimes: StartTimesMode | '';
gridMinutes: number | null;
capacity: number | null;
notes: string;
};
type SlotPayload =
| { payload: { item: string; start: string; end: string; capacity: number; notes: string } }
| { error: string };
type Service = { id: string; name: string; durations: { minutes: number; price: number }[]; bufferMinutes: number; capacity: number };
/** A slot to create: planned times plus what it copies (service, places, notes). */
type Candidate = PlannedSlot & { item: string; capacity: number; notes: string };
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10);
@ -53,96 +41,47 @@ const MAX_RANGE_DAYS = 366;
const MAX_COPY_WEEKS = 12;
const MAX_CAPACITY = 500;
/** Active bookable services, with what the slot forms need. */
async function loadServices(pb: Pb): Promise<Service[]> {
const records = await pb.collection('items').getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' });
return records.map((record) => ({
id: record.id,
name: String(record.name || ''),
durations: parseDurations(record.durations),
bufferMinutes: Number(record.bufferMinutes) || 0,
capacity: Math.max(1, Number(record.capacity) || 1)
}));
}
/**
* Places from the form: a whole number 1–500, or `fallback` (the service's
* own capacity) when the field is left empty.
* Places from the form: a whole number 1–500, or the service's own
* capacity (default 1) when the field is left empty.
*/
function parseCapacity(data: FormData, fallback: number): number | { error: string } {
function parseCapacity(data: FormData, item: Record<string, any>): number | { error: string } {
const raw = String(data.get('capacity') ?? '').trim();
if (raw === '') return fallback;
if (raw === '') return Math.max(1, Number(item.capacity) || 1);
const capacity = Number(raw);
if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) return { error: `Places must be a whole number from 1 to ${MAX_CAPACITY}.` };
return capacity;
}
/** A window's start-times mode and, for `grid`, its step (one of GRID_STEP_OPTIONS). */
function parseStartTimes(data: FormData): { startTimes: StartTimesMode; gridMinutes: number | null } {
if (String(data.get('startTimes')) === 'edges') return { startTimes: 'edges', gridMinutes: null };
const step = Number(data.get('gridMinutes'));
return { startTimes: 'grid', gridMinutes: GRID_STEP_OPTIONS.includes(step) ? step : DEFAULT_GRID_MINUTES };
}
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const itemId = String(data.get('item') || '').trim();
const startValue = String(data.get('start') || '').trim();
const notes = String(data.get('notes') || '').trim();
/** The services ticked in a window form, all of them active services. */
function chosenServices(data: FormData, services: Service[]): string[] | { error: string } {
const ids = [...new Set(data.getAll('items').map(String))];
if (!ids.length) return { error: 'Choose at least one service that can be booked in this window.' };
if (ids.some((id) => !services.some((s) => s.id === id))) return { error: 'A chosen service was not found or is inactive.' };
return ids;
}
if (!itemId || !startValue) return { error: 'Service and start are required.' };
/** A window from the form: a date, from/to times (site timezone) and its services. */
function windowFields(data: FormData, services: Service[]): SlotFields | { error: string } {
const date = String(data.get('date') || '');
const from = String(data.get('from') || '');
const to = String(data.get('to') || '');
if (!isDateKey(date) || timeToMinutes(from) === null || timeToMinutes(to) === null) return { error: 'Choose a date and the start and end times.' };
if (timeToMinutes(to)! <= timeToMinutes(from)!) return { error: 'The window must end after it starts.' };
const items = chosenServices(data, services);
if ('error' in items) return items;
const start = zonedInputToIso(`${date}T${from}`, siteTimezone());
const end = zonedInputToIso(`${date}T${to}`, siteTimezone());
if (!start || !end) return { error: 'Invalid date or time.' };
return { kind: 'window', items, start, end, ...parseStartTimes(data), capacity: null, notes: String(data.get('notes') || '').trim() };
}
/** A group session from the form: one service at one of its lengths, a start and places. */
function sessionFields(data: FormData, services: Service[]): SlotFields | { error: string } {
const service = services.find((s) => s.id === String(data.get('item') || ''));
if (!service) return { error: 'Choose a service.' };
const minutes = Number(data.get('minutes'));
if (!service.durations.some((d) => d.minutes === minutes)) return { error: `Choose one of the lengths “${service.name}” is offered for.` };
// The form sends a wall-clock time in the site's timezone.
const start = zonedInputToIso(String(data.get('start') || ''), siteTimezone());
if (!start) return { error: 'Choose a start time.' };
const capacity = parseCapacity(data, service.capacity);
const startIso = zonedInputToIso(startValue, siteTimezone());
if (!startIso) return { error: 'Invalid start time.' };
const start = new Date(startIso);
let item: Record<string, any>;
try {
item = await pb.collection('items').getOne(itemId);
} catch {
return { error: 'Selected service was not found.' };
}
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' };
const capacity = parseCapacity(data, item);
if (typeof capacity !== 'number') return capacity;
const end = new Date(instantMs(start) + minutes * 60_000).toISOString();
return { kind: 'session', items: [service.id], start, end, startTimes: '', gridMinutes: null, capacity, notes: String(data.get('notes') || '').trim() };
}
/**
* Slots that may not overlap: windows with any other window (one
* practitioner, one opening time), a group session with another session of
* the same service. A session may overlap a window — whichever is booked
* first blocks the other (see the README's Slot availability).
*/
function clashKey(slot: Pick<SlotFields, 'kind' | 'items'>) {
return slot.kind === 'window' ? 'window' : `session:${slot.items[0] ?? ''}`;
}
const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000);
/** A slot that `fields` would overlap (ignoring `exceptId`), or null — or undefined if PocketBase can't be read. */
async function clashingSlot(pb: Pb, fields: SlotFields, exceptId = '') {
const key = toZonedDatetimeInput(fields.start, siteTimezone()).slice(0, 10);
const existing = await slotsForDays(pb, addDaysToKey(key, -1), addDaysToKey(key, 1));
if (!existing) return undefined;
return existing.slots.find((slot) => slot.id !== exceptId && clashKey(slot) === clashKey(fields) && overlapsAny(fields, [slot])) ?? null;
}
function clashMessage(slot: SlotDetail) {
const time = `${toZonedDatetimeInput(slot.start, siteTimezone()).replace('T', ' ')}–${toZonedDatetimeInput(slot.end, siteTimezone()).slice(11)}`;
return slot.kind === 'window' ? `This overlaps the window ${time}. Change that one instead.` : `This overlaps another ${slot.itemNames[0] ?? ''} session (${time}).`;
// Bookings are never stored on the slot: places are counted from orders
// and basket holds by the shop hook, which also works out blocking.
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), capacity, notes } };
}
/** Validated `from`/`to` date keys from a bulk form, or an error message. */
@ -163,16 +102,23 @@ function slotsForDays(pb: Pb, fromKey: string, toKey: string, item = '') {
});
}
async function bookableService(pb: Pb, itemId: string) {
if (!itemId) return null;
const item = await pb.collection('items').getOne(itemId).catch(() => null);
return item && item.type === 'item_with_time' ? item : null;
}
/**
* Drop candidates that start in the past or overlap a slot they may not
* overlap (existing, or accepted earlier in this run — see clashKey).
* Drop candidates that start in the past or overlap a slot of the same
* service (existing, or accepted earlier in this run). Different services
* may share a time: whichever is booked first blocks the others.
*/
function filterCandidates(candidates: SlotFields[], existing: SlotDetail[]) {
function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) {
const now = Date.now();
const taken = new Map<string, PlannedSlot[]>();
for (const slot of existing) taken.set(clashKey(slot), [...(taken.get(clashKey(slot)) ?? []), slot]);
for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]);
const accepted: SlotFields[] = [];
const accepted: Candidate[] = [];
let skippedPast = 0;
let skippedOverlap = 0;
for (const candidate of candidates) {
@ -180,13 +126,13 @@ function filterCandidates(candidates: SlotFields[], existing: SlotDetail[]) {
skippedPast++;
continue;
}
const ranges = taken.get(clashKey(candidate)) ?? [];
const ranges = taken.get(candidate.item) ?? [];
if (overlapsAny(candidate, ranges)) {
skippedOverlap++;
continue;
}
ranges.push(candidate);
taken.set(clashKey(candidate), ranges);
taken.set(candidate.item, ranges);
accepted.push(candidate);
}
accepted.sort((a, b) => instantMs(a.start) - instantMs(b.start));
@ -212,51 +158,42 @@ async function previewOrCreate(pb: Pb, action: 'generate' | 'copy', intent: stri
};
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: accepted.length });
const created = await runInBatches(accepted, 'create', (slot) => pb.collection('slots').create(slot));
const created = await runInBatches(accepted, 'create', (slot) =>
pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, capacity: slot.capacity, notes: slot.notes })
);
return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created });
}
/** Weekdays and opening hours from a generate form, or an error. */
function weekdaysAndHours(data: FormData): { weekdays: number[]; windows: TimeWindow[] } | { error: string } {
const weekdays = data.getAll('weekday').map(Number).filter((day) => day >= 0 && day <= 6);
if (!weekdays.length) return { error: 'Choose at least one weekday.' };
const froms = data.getAll('windowFrom').map(String);
const tos = data.getAll('windowTo').map(String);
const windows: TimeWindow[] = froms.map((from, i) => ({ from, to: tos[i] ?? '' }));
if (!windows.length) return { error: 'Add at least one time window.' };
for (const window of windows) {
const from = timeToMinutes(window.from);
const to = timeToMinutes(window.to);
if (from === null || to === null) return { error: 'Every time window needs a start and an end time.' };
if (to <= from) return { error: `The hours ${window.from}–${window.to} end before they start.` };
}
return { weekdays, windows };
}
export const load: PageServerLoad = async ({ locals, url }) => {
const today = todayKey();
const monthParam = url.searchParams.get('month') || '';
const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7);
const items = await loadServices(locals.pb).catch(() => []);
const itemRecords = await locals.pb
.collection('items')
.getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' })
.catch(() => []);
const items = itemRecords.map((record) => ({
id: record.id,
name: String(record.name || ''),
duration: Number(record.duration) || 0,
bufferMinutes: Number(record.bufferMinutes) || 0,
capacity: Math.max(1, Number(record.capacity) || 1)
}));
// Only the slots shown in the month grid (which spans whole weeks).
const grid = monthGridKeys(month);
const details = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]);
const slots = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]);
return { items, slots: details?.slots ?? [], bookings: details?.bookings ?? [], slotsError: details === null, month, today };
return { items, slots: slots ?? [], slotsError: slots === null, month, today };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const services = await loadServices(locals.pb).catch(() => []);
const fields = String(data.get('kind')) === 'session' ? sessionFields(data, services) : windowFields(data, services);
if ('error' in fields) return fail(400, { message: fields.error });
const clash = await clashingSlot(locals.pb, fields);
if (clash === undefined) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
if (clash) return fail(400, { message: clashMessage(clash) });
const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(fields));
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload));
if (!created.ok) return created.failure;
return { ok: true };
},
@ -266,31 +203,23 @@ export const actions: Actions = {
if (!id) return fail(400, { message: 'Slot id is required.' });
// Re-read the slot: the page may be stale, and customers may have
// booked or held times since.
// booked or held places since. Once any place is taken, the service
// and time are fixed; places can't go below what's taken.
const current = await loadSlotDetail(locals.pb, id).catch(() => undefined);
if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' });
if (!current) return fail(404, { message: 'This slot no longer exists.' });
const services = await loadServices(locals.pb).catch(() => []);
const taken = seatsTaken(current);
let patch: Partial<SlotFields>;
if (current.kind === 'session' && taken > 0) {
// Customers booked this time and service: only places and notes can change.
const capacity = parseCapacity(data, current.capacity ?? 1);
const taken = seatsTaken(current);
let patch: Record<string, string | number>;
if (taken > 0) {
const capacity = parseCapacity(data, { capacity: current.capacity });
if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` });
patch = { capacity, notes: String(data.get('notes') || '').trim() };
} else {
const fields = current.kind === 'session' ? sessionFields(data, services) : windowFields(data, services);
if ('error' in fields) return fail(400, { message: fields.error });
// A window keeps the times already booked in it: it can grow or
// change services, but not shrink past a booking.
const outside = current.bookings.find((b) => instantMs(b.start) < instantMs(fields.start) || instantMs(b.end) > instantMs(fields.end));
if (outside) return fail(400, { message: 'A booking in this window would fall outside the new times — the window must still cover every booked time.' });
const clash = await clashingSlot(locals.pb, fields, id);
if (clash === undefined) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
if (clash) return fail(400, { message: clashMessage(clash) });
patch = fields;
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
patch = result.payload;
}
const updated = await attempt('Could not save the slot.', () => locals.pb.collection('slots').update(id, patch));
if (!updated.ok) return updated.failure;
@ -303,55 +232,56 @@ export const actions: Actions = {
const current = await loadSlotDetail(locals.pb, id).catch(() => undefined);
if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' });
if (current?.booked) return fail(400, { message: 'This slot has bookings and can’t be deleted.' });
if (current?.held) return fail(400, { message: 'A time in this slot is in a customer’s basket right now — try again in a few minutes.' });
if (current?.held) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' });
const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
if (!deleted.ok) return deleted.failure;
return { ok: true };
},
/**
* Fill a date range: windows (the opening hours on the chosen weekdays,
* with the chosen services) or group sessions (one service, spaced by
* its length + get-ready time within the hours).
*/
/** Fill a date range with slots: chosen weekdays, time windows, get-ready gap. */
generate: async ({ request, locals }) => {
const data = await request.formData();
const intent = String(data.get('intent') || 'preview');
const range = dateRange(data);
if ('error' in range) return fail(400, { message: range.error });
const days = weekdaysAndHours(data);
if ('error' in days) return fail(400, { message: days.error });
const services = await loadServices(locals.pb).catch(() => null);
if (!services) return fail(400, { message: 'Could not read the services — is the database reachable?' });
const notes = String(data.get('notes') || '').trim();
let candidates: SlotFields[];
if (String(data.get('kind')) === 'session') {
const service = services.find((s) => s.id === String(data.get('item') || ''));
if (!service) return fail(400, { message: 'Choose a service.' });
const minutes = Number(data.get('minutes'));
if (!service.durations.some((d) => d.minutes === minutes)) return fail(400, { message: `Choose one of the lengths “${service.name}” is offered for.` });
const capacity = parseCapacity(data, service.capacity);
const item = await bookableService(locals.pb, String(data.get('item') || ''));
if (!item) return fail(400, { message: 'Choose a bookable service.' });
const duration = Number(item.duration) || 0;
if (duration <= 0) return fail(400, { message: `“${item.name}” has no duration — set one under Services & products.` });
const capacity = parseCapacity(data, item);
if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const bufferMinutes = rawBuffer === '' ? service.bufferMinutes : parseInt(rawBuffer, 10);
if (Number.isNaN(bufferMinutes) || bufferMinutes < 0) return fail(400, { message: 'Get-ready time must be 0 or more minutes.' });
const planned = planGeneratedSlots({ ...range, ...days, durationMinutes: minutes, bufferMinutes, timeZone: siteTimezone() });
candidates = planned.map((slot) => ({ ...slot, kind: 'session', items: [service.id], startTimes: '', gridMinutes: null, capacity, notes }));
} else {
const items = chosenServices(data, services);
if ('error' in items) return fail(400, { message: items.error });
const startTimes = parseStartTimes(data);
candidates = planWindows({ ...range, ...days, timeZone: siteTimezone() }).map((slot) => ({ ...slot, kind: 'window', items, ...startTimes, capacity: null, notes }));
}
if (!candidates.length) return fail(400, { message: 'Nothing fits those days and times.' });
const existing = await slotsForDays(locals.pb, addDaysToKey(range.fromDate, -1), addDaysToKey(range.toDate, 1));
const weekdays = data.getAll('weekday').map(Number).filter((day) => day >= 0 && day <= 6);
if (!weekdays.length) return fail(400, { message: 'Choose at least one weekday.' });
const froms = data.getAll('windowFrom').map(String);
const tos = data.getAll('windowTo').map(String);
const windows: TimeWindow[] = froms.map((from, i) => ({ from, to: tos[i] ?? '' }));
if (!windows.length) return fail(400, { message: 'Add at least one time window.' });
for (const window of windows) {
const from = timeToMinutes(window.from);
const to = timeToMinutes(window.to);
if (from === null || to === null) return fail(400, { message: 'Every time window needs a start and an end time.' });
if (to - from < duration) return fail(400, { message: `The window ${window.from}–${window.to} is shorter than one ${duration}-minute appointment.` });
}
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const bufferMinutes = rawBuffer === '' ? Number(item.bufferMinutes) || 0 : parseInt(rawBuffer, 10);
if (Number.isNaN(bufferMinutes) || bufferMinutes < 0) return fail(400, { message: 'Get-ready time must be 0 or more minutes.' });
const planned = planGeneratedSlots({ ...range, weekdays, windows, durationMinutes: duration, bufferMinutes, timeZone: siteTimezone() });
if (!planned.length) return fail(400, { message: 'No slots fit those days and times.' });
const existing = await slotsForDays(locals.pb, range.fromDate, range.toDate, item.id);
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
return previewOrCreate(locals.pb, 'generate', intent, filterCandidates(candidates, existing.slots));
const notes = String(data.get('notes') || '').trim();
const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id, capacity, notes })), existing);
return previewOrCreate(locals.pb, 'generate', intent, result);
},
/** Repeat one week's slots (all, or those offering one service) for the following weeks. */
/** Repeat one week's slots (all services, or one) for the following weeks. */
copy: async ({ request, locals }) => {
const data = await request.formData();
const intent = String(data.get('intent') || 'preview');
@ -362,25 +292,25 @@ export const actions: Actions = {
const itemId = String(data.get('item') || '');
const source = await slotsForDays(locals.pb, sourceWeek, addDaysToKey(sourceWeek, 6), itemId);
const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 6), addDaysToKey(sourceWeek, 7 * (weeks + 1)));
const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 7), addDaysToKey(sourceWeek, 7 * (weeks + 1) - 1), itemId);
if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' });
if (!source.slots.length) return fail(400, { message: 'That week has no slots to copy.' });
if (!source.length) return fail(400, { message: 'That week has no slots to copy.' });
// Copies are new, empty slots: same kind, services, places, start times and notes.
const candidates: SlotFields[] = [];
// Copies are new, empty slots: same service, places and notes.
const candidates: Candidate[] = [];
for (let week = 1; week <= weeks; week++) {
for (const slot of source.slots) {
for (const slot of source) {
const start = shiftByDays(slot.start, 7 * week, siteTimezone());
const end = shiftByDays(slot.end, 7 * week, siteTimezone());
if (!start || !end) continue;
candidates.push({ kind: slot.kind, items: slot.items, start, end, startTimes: slot.startTimes ?? '', gridMinutes: slot.gridMinutes ?? null, capacity: slot.capacity ?? null, notes: slot.notes });
if (!start) continue;
const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString();
candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes });
}
}
return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing.slots));
return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing));
},
/** Delete the slots in a date range that have nothing booked or held. */
/** Delete the slots in a date range that have no places taken. */
clear: async ({ request, locals }) => {
const data = await request.formData();
const intent = String(data.get('intent') || 'preview');
@ -388,20 +318,20 @@ export const actions: Actions = {
if ('error' in range) return fail(400, { message: range.error });
const itemId = String(data.get('item') || '');
const details = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId);
if (!details) return fail(400, { message: 'Could not read slots — is the database reachable?' });
const slots = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId);
if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' });
const removable = details.slots.filter((slot) => seatsTaken(slot) === 0);
const removable = slots.filter((slot) => seatsTaken(slot) === 0);
const summary = {
action: 'clear' as const,
kept: details.slots.length - removable.length,
kept: slots.length - removable.length,
firstStart: removable[0]?.start ?? '',
lastStart: removable.at(-1)?.start ?? ''
};
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length });
// Re-check each slot just before deleting it: a customer may have put
// a time in it into their basket since the list was read.
// it in their basket since the list was read.
const deleted = await runInBatches(removable, 'delete', async (slot) => {
const fresh = await loadSlotDetail(locals.pb, slot.id);
if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview');

View file

@ -4,39 +4,33 @@
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte';
import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte';
import { DEFAULT_GRID_MINUTES, GRID_STEP_OPTIONS, SLOT_STATE_LABELS, START_TIMES_LABELS, WEEKDAYS, startTimesHint, startTimesLabel, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
import type { BulkResult, SlotState } from '$lib/slots';
import type { SlotKind, StartTimesMode } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props();
let items = $derived(data.items || []);
let serviceFilter = $state('');
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.items.includes(serviceFilter)));
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter));
type Slot = (typeof slots)[number];
type Booking = (typeof data.bookings)[number];
let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot])));
// ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4;
const dayKeyOf = (iso: string) => toZonedDatetimeInput(iso, data.timezone).slice(0, 10);
let gridKeys = $derived(monthGridKeys(data.month));
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
let slotsByDay = $derived.by(() => {
const byDay = new Map<string, Slot[]>();
for (const slot of slots) byDay.set(dayKeyOf(slot.start), [...(byDay.get(dayKeyOf(slot.start)) ?? []), slot]);
for (const slot of slots) {
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
}
return byDay;
});
let bookingsByDay = $derived.by(() => {
const byDay = new Map<string, Booking[]>();
for (const booking of data.bookings || []) byDay.set(dayKeyOf(booking.start), [...(byDay.get(dayKeyOf(booking.start)) ?? []), booking]);
return byDay;
});
let monthSlots = $derived(slots.filter((slot) => dayKeyOf(slot.start).startsWith(data.month)));
let monthSlots = $derived(slots.filter((slot) => toZonedDatetimeInput(slot.start, data.timezone).startsWith(data.month)));
// ── Modals ──
let showEditor = $state(false);
@ -48,14 +42,13 @@
let copyFrom = $state('');
let clearRange = $state({ from: '', to: '' });
let daySlots = $derived(slotsByDay.get(dayKey) ?? []);
let dayBookings = $derived(bookingsByDay.get(dayKey) ?? []);
let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null);
function bulkMessage(result: BulkResult) {
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
const verb = result.action === 'clear' ? 'Deleted' : 'Created';
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (booked in the meantime)' : 'saved'}.` : '';
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`;
}
@ -74,26 +67,15 @@
blocked: 'badge-ghost'
};
const range = (start: string, end: string) => `${formatTime(start, data.timezone)}–${formatTime(end, data.timezone)}`;
/** "Massage, Facial" — or the one service of a session. */
const serviceNames = (slot: Slot) => slot.itemNames.filter(Boolean).join(', ') || 'No services';
/** "2/8" for group sessions, '' otherwise. */
/** "2/8" for group slots, '' for one-to-one. */
function places(slot: Slot) {
return slot.kind === 'session' && (slot.capacity ?? 1) > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
}
/** What a window has left, e.g. "Free 10:15–12:00". */
function freeLabel(slot: Slot) {
if (!slot.free?.length) return 'No free time left';
return `Free ${slot.free.map((f) => range(f.start, f.end)).join(', ')}`;
}
function describe(slot: Slot, state: SlotState) {
if (slot.kind === 'window') return `${serviceNames(slot)} — ${freeLabel(slot)}`;
if (state === 'blocked' && slot.blockedBy) return `Blocked by ${range(slot.blockedBy.start, slot.blockedBy.end)} ${slot.blockedBy.itemName}`;
return `${SLOT_STATE_LABELS[state]}${places(slot) ? ` (${places(slot)})` : ''}`;
/** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */
function blockedReason(slot: Slot) {
const blocker = slotsById.get(slot.blockedBy);
return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking';
}
function openDay(key: string) {
@ -113,20 +95,10 @@
showClear = true;
}
// ── Slot editor (a window or a group session) ──
// ── Single slot editor ──
type SlotDraft = {
id: string;
kind: SlotKind;
// window
date: string;
from: string;
to: string;
items: string[];
startTimes: StartTimesMode;
gridMinutes: number;
// session
item: string;
minutes: string;
start: string;
capacity: string;
booked: number;
@ -134,52 +106,23 @@
notes: string;
};
let draft = $state<SlotDraft>(emptyDraft('window'));
let draft = $state<SlotDraft>(emptyDraft());
let editorError = $state('');
let action = $derived(draft.id ? '?/update' : '?/create');
// Once any place is taken, the service and time are fixed (customers booked them).
let taken = $derived(draft.booked + draft.held);
// Once a place in a session is taken, its service and time are fixed (customers booked them).
let sessionLocked = $derived(draft.kind === 'session' && taken > 0);
let selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => {
if (!draft.start || !draft.minutes) return '';
if (!selectedItem || !draft.start) return '';
const startIso = zonedInputToIso(draft.start, data.timezone);
if (!startIso) return '';
return `Ends at ${formatTime(new Date(new Date(startIso).getTime() + Number(draft.minutes) * 60_000).toISOString(), data.timezone)}`;
const end = new Date(new Date(startIso).getTime() + (Number(selectedItem.duration) || 0) * 60_000);
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
});
function emptyDraft(kind: SlotKind, day = ''): SlotDraft {
const date = day || data.today;
const service = items.find((item) => item.id === serviceFilter);
return {
id: '',
kind,
date,
from: '09:00',
to: '12:00',
items: serviceFilter ? [serviceFilter] : oneToOneServices(items),
startTimes: 'grid',
gridMinutes: DEFAULT_GRID_MINUTES,
item: serviceFilter,
minutes: service?.durations[0] ? String(service.durations[0].minutes) : '',
start: `${date}T09:00`,
capacity: '',
booked: 0,
held: 0,
notes: ''
};
}
/** What a new window offers by default: the one-to-one services (group classes get sessions), or all if there are none. */
function oneToOneServices(list: typeof items) {
const ids = list.filter((item) => item.capacity <= 1).map((item) => item.id);
return ids.length ? ids : list.map((item) => item.id);
}
function selectSessionService(id: string) {
draft.item = id;
const service = items.find((item) => item.id === id);
if (!service?.durations.some((d) => String(d.minutes) === draft.minutes)) draft.minutes = service?.durations[0] ? String(service.durations[0].minutes) : '';
function emptyDraft(day = ''): SlotDraft {
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' };
}
// Enhanced so the page keeps its ?month= after saving (a plain POST to
@ -196,29 +139,20 @@
};
};
function createSlot(kind: SlotKind, day = '') {
function createSlot(day = '') {
editorError = '';
draft = emptyDraft(kind, day);
draft = emptyDraft(day);
showDay = false;
showEditor = true;
}
function editSlot(slot: Slot) {
editorError = '';
const start = toZonedDatetimeInput(slot.start, data.timezone);
draft = {
...emptyDraft(slot.kind),
id: slot.id,
date: start.slice(0, 10),
from: start.slice(11, 16),
to: toZonedDatetimeInput(slot.end, data.timezone).slice(11, 16),
items: [...slot.items],
startTimes: slot.startTimes ?? 'grid',
gridMinutes: slot.gridMinutes ?? DEFAULT_GRID_MINUTES,
item: slot.items[0] ?? '',
minutes: String(slot.minutes ?? ''),
start,
capacity: String(slot.capacity ?? ''),
item: slot.item,
start: toZonedDatetimeInput(slot.start, data.timezone),
capacity: String(slot.capacity),
booked: slot.booked,
held: slot.held,
notes: slot.notes
@ -231,16 +165,13 @@
<svelte:head><title>Slots | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col gap-4">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Slots</h1>
<p class="max-w-4xl text-base-content/60">
When you can be booked. A <strong>window</strong> (e.g. 09:00–12:00) takes bookings of the services you choose, at any of their lengths; each booking takes its time plus get-ready time out of the window. A <strong>group session</strong> is one service at a fixed time with places. Times are in {data.timezone}.
</p>
<p class="text-base-content/60">Bookable time slots for your services. Times are in {data.timezone}.</p>
</div>
<div class="flex flex-wrap gap-2">
<button class="btn" type="button" disabled={!items.length} onclick={() => createSlot('window')}>Add window</button>
<button class="btn" type="button" disabled={!items.length} onclick={() => createSlot('session')}>Add group session</button>
<button class="btn" type="button" onclick={() => createSlot()}>Create slot</button>
<button class="btn" type="button" onclick={() => openCopy(data.today)}>Copy a week</button>
<button class="btn" type="button" onclick={() => openClear(data.today > `${data.month}-01` ? data.today : `${data.month}-01`, monthEnd)}>Clear slots</button>
<button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button>
@ -287,17 +218,12 @@
<button
class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}"
type="button"
title="{range(slot.start, slot.end)} {slot.kind === 'window' ? 'window' : serviceNames(slot)} — {describe(slot, state)}"
onclick={() => openDay(key)}
title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {state === 'blocked' ? blockedReason(slot) : SLOT_STATE_LABELS[state]}{places(slot) ? ` (${places(slot)})` : ''}"
onclick={() => editSlot(slot)}
>
{#if slot.kind === 'window'}
<span class="font-semibold">{range(slot.start, slot.end)}</span>
{#if slot.booked + slot.held}<span class="hidden md:inline">· {slot.booked + slot.held} booked</span>{/if}
{:else}
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
<span class="hidden lg:inline">{serviceNames(slot)}</span>
<span class="hidden lg:inline">{slot.itemName}</span>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
{/if}
</button>
{/each}
{#if daySlotList.length > MAX_CHIPS}
@ -312,29 +238,32 @@
{#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)}
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {STATE_CLASSES[state as SlotState]}"></span> {label}</span>
{/each}
<span>— a booking blocks every other one overlapping it, including get-ready time. Click a day for its bookings and free time.</span>
<span>— a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.</span>
</div>
</div>
<!-- Collapsed by default: a generated month is many rows, and the calendar covers day-to-day use. -->
<!-- Collapsed by default: a generated month is hundreds of rows, and the calendar covers day-to-day use. -->
<details class="collapse collapse-arrow rounded-box bg-base-100 shadow">
<summary class="collapse-title text-2xl font-bold">All slots in {monthLabel} <span class="text-base font-normal text-base-content/60">({monthSlots.length})</span></summary>
<div class="collapse-content overflow-x-auto">
<table class="table">
<thead><tr><th>When</th><th>Kind</th><th>Services</th><th>Booked</th><th>Status</th><th></th></tr></thead>
<thead><tr><th>Service</th><th>Date</th><th>Places</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each monthSlots as slot (slot.id)}
{@const state = slotState(slot)}
<tr>
<td>{formatDateTime(slot.start, data.timezone)}–{formatTime(slot.end, data.timezone)}</td>
<td>{slot.kind === 'window' ? 'Window' : 'Group session'}</td>
<td>{serviceNames(slot)}</td>
<td>{slot.kind === 'session' ? `${slot.booked + slot.held}/${slot.capacity}` : slot.booked + slot.held}</td>
<td><span class="badge {BADGE_CLASSES[state]}" title={describe(slot, state)}>{SLOT_STATE_LABELS[state]}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button></td>
<td><span class="font-semibold">{slot.itemName}</span></td>
<td>{formatDateTime(slot.start, data.timezone)}</td>
<td>{slot.booked + slot.held}/{slot.capacity}</td>
<td>
<span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span>
</td>
<td class="text-right">
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
</td>
</tr>
{:else}
<tr><td colspan="6" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr>
<tr><td colspan="5" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr>
{/each}
</tbody>
</table>
@ -352,14 +281,10 @@
{#each daySlots as slot (slot.id)}
{@const state = slotState(slot)}
<li class="flex items-center gap-3 py-2">
<span class="w-28 shrink-0 font-semibold">{range(slot.start, slot.end)}</span>
<span class="w-28 shrink-0 font-semibold">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span>
<span class="min-w-0 flex-1">
<span class="block truncate">
{slot.kind === 'window' ? 'Window' : 'Group session'} · {serviceNames(slot)}{places(slot) ? ` · ${places(slot)} places` : ''}
</span>
<span class="block truncate text-xs text-base-content/60">
{#if slot.kind === 'window'}{freeLabel(slot)} · {startTimesLabel(slot.startTimes ?? 'grid', slot.gridMinutes)}{:else if state === 'blocked'}{describe(slot, state)}{:else}{formatDuration(slot.minutes ?? 0)}{/if}
</span>
<span class="block truncate">{slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''}</span>
{#if state === 'blocked'}<span class="block truncate text-xs text-base-content/60">{blockedReason(slot)}</span>{/if}
{#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if}
</span>
<span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
@ -370,143 +295,48 @@
{:else}
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
{/if}
{#if dayBookings.length}
<h3 class="mt-4 font-semibold">Bookings</h3>
<ul class="mt-1 divide-y divide-base-300 text-sm">
{#each dayBookings as booking (`${booking.slot}|${booking.start}|${booking.status}|${booking.item}`)}
<li class="flex items-center gap-3 py-1.5">
<span class="w-28 shrink-0 font-semibold">{range(booking.start, booking.end)}</span>
<span class="min-w-0 flex-1 truncate">
{booking.itemName}{booking.quantity > 1 ? ` · ${booking.quantity} places` : ''}
{#if booking.readyAt !== booking.end}<span class="text-base-content/60"> · ready again {formatTime(booking.readyAt, data.timezone)}</span>{/if}
</span>
<span class="badge badge-sm {booking.status === 'booked' ? 'badge-info badge-soft' : 'badge-warning'}">{booking.status === 'booked' ? 'Booked' : 'In a basket'}</span>
</li>
{/each}
</ul>
<p class="mt-1 text-xs text-base-content/60">Customer details are under Orders.</p>
{/if}
<div class="modal-action flex-wrap justify-between">
<div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button>
{#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if}
</div>
<div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" disabled={!items.length} onclick={() => createSlot('session', dayKey)}>Add group session</button>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot('window', dayKey)}>Add window</button>
</div>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot(dayKey)}>Add slot</button>
</div>
</Modal>
<Modal bind:open={showEditor} title={draft.id ? (draft.kind === 'window' ? 'Edit window' : 'Edit group session') : 'Add a slot'} wide>
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}>
<form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="kind" value={draft.kind} />
{#if editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if}
{#if !draft.id}
<SegmentedControl
label="Kind"
class="mb-2"
options={['window', 'session']}
value={draft.kind}
formatLabel={(v) => (v === 'window' ? 'Window' : 'Group session')}
onChange={(v) => (draft.kind = v as SlotKind)}
/>
{/if}
{#if draft.kind === 'window'}
{#if taken}
<div class="alert alert-warning mb-2 text-sm">
{[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — the window can grow or change services, but must still cover every booked time.
</div>
{/if}
<div class="grid gap-x-4 md:grid-cols-3">
<label class="fieldset">
<span class="fieldset-legend">Date</span>
<input class="input w-full" type="date" name="date" required bind:value={draft.date} />
</label>
<label class="fieldset">
<span class="fieldset-legend">From ({data.timezone})</span>
<input class="input w-full" type="time" name="from" required bind:value={draft.from} />
</label>
<label class="fieldset">
<span class="fieldset-legend">To</span>
<input class="input w-full" type="time" name="to" required bind:value={draft.to} />
</label>
</div>
<div class="fieldset">
<span class="fieldset-legend">Services that can be booked in this window</span>
<div class="grid gap-1 sm:grid-cols-2">
{#each items as item (item.id)}
<label class="label cursor-pointer gap-2 text-base-content">
<input class="checkbox checkbox-sm" type="checkbox" name="items" value={item.id} bind:group={draft.items} />
{item.name}
<span class="text-xs text-base-content/50">{item.durations.map((d) => formatDuration(d.minutes)).join(' / ')}</span>
</label>
{/each}
</div>
</div>
<div class="fieldset">
<input type="hidden" name="startTimes" value={draft.startTimes} />
<SegmentedControl
label="Start times"
options={['grid', 'edges']}
value={draft.startTimes}
formatLabel={(v) => START_TIMES_LABELS[v as StartTimesMode]}
onChange={(v) => (draft.startTimes = v as StartTimesMode)}
/>
{#if draft.startTimes === 'grid'}
<label class="mt-2 flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-medium">Step</span>
<select class="select select-sm w-40" name="gridMinutes" bind:value={draft.gridMinutes}>
{#each GRID_STEP_OPTIONS as step (step)}<option value={step}>Every {step} min</option>{/each}
</select>
</label>
{/if}
<span class="label whitespace-normal">{startTimesHint(draft.startTimes, draft.gridMinutes)}</span>
</div>
{:else}
{#if sessionLocked}
<div class="alert alert-warning mb-2 text-sm">
{[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — only the places and notes can be changed.
</div>
{/if}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required disabled={sessionLocked} value={draft.item} onchange={(e) => selectSessionService(e.currentTarget.value)}>
<select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}>
<option value="" disabled>Select a service…</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Length</span>
<select class="select w-full" name="minutes" required disabled={sessionLocked || !selectedItem} bind:value={draft.minutes}>
{#each selectedItem?.durations ?? [] as duration (duration.minutes)}
<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>
{#each items as item (item.id)}
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Start ({data.timezone})</span>
<input class="input w-full" type="datetime-local" name="start" required disabled={sessionLocked} bind:value={draft.start} />
<input class="input w-full" type="datetime-local" name="start" required disabled={taken > 0} bind:value={draft.start} />
{#if endLabel}<span class="label">{endLabel}</span>{/if}
</label>
<label class="fieldset">
<span class="fieldset-legend">Places</span>
<input class="input w-32" type="number" min={Math.max(1, taken)} max="500" step="1" name="capacity" placeholder={String(selectedItem?.capacity ?? 1)} bind:value={draft.capacity} />
<span class="label">{draft.id ? 'How many people can book it.' : 'Empty = the service’s own.'}</span>
<span class="label">More than 1 for a group session.{draft.id ? '' : ' Empty = the service’s own.'}</span>
</label>
</div>
{/if}
<label class="fieldset">
<span class="fieldset-legend">Notes</span>
@ -521,7 +351,7 @@
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-primary" type="submit">Save slot</button>
</div>
</div>
</form>

View file

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

View file

@ -1,5 +1,5 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord } 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, 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
// basket is fresh on each page (holds lapse while the visitor browses).
// Shop blocks fetch bookable times themselves (GET /api/slots).
// 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([
@ -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); the basket comes from the shop API in
// PocketBase. Failures leave the shop empty, never break a page.
// rules allow active items / available slots); 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, timezone, currency };
return { header, footer, colors, user: locals.user, basket, items, slots, timezone, currency };
};

View file

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

View file

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

View file

@ -21,9 +21,6 @@ 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) || ''

View file

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

View file

@ -72,12 +72,8 @@ export function createBasketStore(initial: Basket | null) {
applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
}
/**
* 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 addSlotLine(slotId: string) {
await applySlotChange(await callApi({ action: 'add_slot', slotId }));
}
async function updateQuantity(lineId: string, quantity: number) {

View file

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

View file

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

View file

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

View file

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

View file

@ -148,12 +148,14 @@ 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 end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null;
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;
return {
name: String(line.name || 'Item'),
price: Number(line.price) || 0,

View file

@ -1,63 +1,39 @@
import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb';
import { parseDurations } from '../items';
import type { BookableTime, ItemRecord } from '../types';
import type { ItemRecord, SlotRecord } from '../types';
/** An `items` record (with `expand.image`) → `ItemRecord`. */
export function mapItemRecord(record: Record<string, any>): ItemRecord {
/**
* 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.
*/
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;
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 || ''),
name: record.name,
description: record.description || '',
price: record.price,
image: record.image || '',
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type,
type: record.type,
stock: record.stock ?? null,
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
active: record.active
};
}
});
/**
* 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[] }> {
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<Response> {
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 });
}
return { items, slots };
}

View file

@ -6,7 +6,6 @@
// 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 };
@ -44,64 +43,22 @@ export type BulkResult = {
};
/**
* 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.
* 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.
*/
export type SlotDetail = PlannedSlot & {
id: string;
kind: SlotKind;
items: string[];
itemNames: string[];
item: string;
itemName: string;
capacity: number;
notes: string;
booked: number;
held: number;
// window
startTimes?: StartTimesMode;
/** `grid` windows: minutes between start times. */
gridMinutes?: number;
free?: PlannedSlot[];
// session
minutes?: number;
capacity?: number;
blockedBy?: SlotBooking | null;
blockedBy: string;
};
export const START_TIMES_LABELS: Record<StartTimesMode, string> = {
grid: 'Fixed steps',
edges: 'Next free time'
};
/** Step choices for `grid` windows, in minutes; 30 is the default. */
export const GRID_STEP_OPTIONS = [10, 15, 20, 30, 45, 60];
export const DEFAULT_GRID_MINUTES = 30;
/** What a window's start-times setting means, for the admin forms and day view. */
export function startTimesHint(mode: StartTimesMode, gridMinutes = DEFAULT_GRID_MINUTES) {
return mode === 'grid'
? `Customers can start every ${gridMinutes} minutes from the window’s start, wherever their booking fits.`
: '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.';
}
/** "Every 15 min" / "Next free time". */
export function startTimesLabel(mode: StartTimesMode, gridMinutes = DEFAULT_GRID_MINUTES) {
return mode === 'grid' ? `Every ${gridMinutes} min` : START_TIMES_LABELS.edges;
}
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
export const SLOT_STATE_LABELS: Record<SlotState, string> = {
@ -113,18 +70,12 @@ export const SLOT_STATE_LABELS: Record<SlotState, string> = {
};
/**
* 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.
* `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, 'kind' | 'booked' | 'held' | 'capacity' | 'blockedBy' | 'free'>): 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';
export function slotState(slot: Pick<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): SlotState {
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';
@ -240,22 +191,7 @@ export type GeneratePlanInput = {
timeZone: string;
};
/** Each chosen day's opening hours as windows (dates in `timeZone`), before skipping overlaps/past ones. */
export function planWindows(input: Omit<GeneratePlanInput, 'durationMinutes' | 'bufferMinutes'>): PlannedSlot[] {
const days = new Set(input.weekdays);
const slots: PlannedSlot[] = [];
for (const key of dateKeysBetween(input.fromDate, input.toDate)) {
if (!days.has(weekdayOfKey(key))) continue;
for (const window of input.windows) {
const start = zonedInputToIso(`${key}T${window.from}`, input.timeZone);
const end = zonedInputToIso(`${key}T${window.to}`, input.timeZone);
if (start && end && end > start) slots.push({ start, end });
}
}
return slots;
}
/** Every group session the generator would create, before skipping overlaps/past ones. */
/** Every slot 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);

View file

@ -119,42 +119,31 @@ 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;
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)
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)
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 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.
* A bookable slot as the shop lists it (GET /api/shop/slots): only slots
* with places left that no overlapping booking blocks.
*/
export type BookableTime = {
slot: string; // slot id (window or session)
kind: SlotKind;
export type SlotRecord = {
id: string;
item: string; // item id
start: string;
end: string;
capacity: number; // places in total (1 in a window)
capacity: number; // places in total
free: number; // places still bookable
};
@ -167,16 +156,12 @@ 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;
/** Price of one unit (a product, or the service at this length); null if no longer offered. */
itemPrice?: number | null;
itemPrice?: number;
itemImageUrl?: string;
slotKind?: SlotKind;
slotStart?: string;
slotEnd?: string;
slotCapacity?: number;
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
heldUntil?: string;
@ -226,8 +211,6 @@ export type OrderLine = {
name: string;
price: number;
start: string | null;
/** Slot lines: the booked length. */
minutes: number | null;
};
// ── Block data types ──────────────────────────────────────────────────

View file

@ -330,7 +330,7 @@
{ "id": "rel_itemimage01", "name": "image", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_media00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] },
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
{ "id": "json_itemdurations", "name": "durations", "type": "json", "system": false, "required": false, "presentable": false, "hidden": false, "maxSize": 20000 },
{ "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
{ "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true },
{ "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
@ -353,10 +353,7 @@
"deleteRule": "@request.auth.id != ''",
"fields": [
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
{ "id": "sel_slotkind001", "name": "kind", "type": "select", "system": false, "required": true, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["window", "session"] },
{ "id": "rel_slotitems01", "name": "items", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 50 },
{ "id": "sel_slotstarts1", "name": "startTimes", "type": "select", "system": false, "required": false, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["grid", "edges"] },
{ "id": "num_slotgridmin1", "name": "gridMinutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 5, "max": 240, "onlyInt": true },
{ "id": "rel_slotitem001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "date_slotstart0", "name": "start", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "date_slotend000", "name": "end", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "num_slotcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
@ -365,7 +362,7 @@
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
],
"indexes": [
"CREATE INDEX `idx_slots_start` ON `slots` (`start`)"
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)"
],
"autodate": true,
"options": {}
@ -414,15 +411,12 @@
{ "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
{ "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] },
{ "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
{ "id": "date_blstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
{ "id": "num_blminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
],
"indexes": [
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)",
"CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)"
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)"
],
"autodate": true,
"options": {}
@ -479,14 +473,12 @@
{ "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
{ "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
{ "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "num_olminutes001", "name": "minutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 0, "max": null, "onlyInt": true },
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
],
"indexes": [
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)",
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)",
"CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)"
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)"
],
"autodate": true,
"options": {}

View file

@ -3,17 +3,16 @@
/// treats its input as untrusted. The basket id acts as the customer's
/// bearer token, exactly like the cookie it comes from.
// Slot availability (windows, group sessions, blocking — see lib.js).
// Anyone gets the bookable times for one service and duration
// (?item=&minutes=&from=&to=); a signed-in admin can ask for `detail`.
// Slot availability (seats + cross-service blocking, see lib.js). Anyone
// gets the bookable future slots; a signed-in admin can ask for `detail`.
routerAdd('GET', '/api/shop/slots', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
const query = e.request.url.query();
if (query.get('detail')) {
if (!e.auth) throw new UnauthorizedError('Sign in to see slot details');
return e.json(200, shop.slotDetails($app, { from: query.get('from'), to: query.get('to'), item: query.get('item'), id: query.get('id') }));
return e.json(200, { slots: shop.slotDetails($app, { from: query.get('from'), to: query.get('to'), item: query.get('item'), id: query.get('id') }) });
}
return e.json(200, shop.bookableTimes($app, { item: query.get('item'), minutes: query.get('minutes'), from: query.get('from'), to: query.get('to') }));
return e.json(200, { slots: shop.bookableSlots($app) });
});
routerAdd('GET', '/api/shop/basket/{id}', (e) => {

View file

@ -62,350 +62,150 @@ function pbDate(ms) {
const DAY_MS = 24 * 60 * 60 * 1000;
const MINUTE_MS = 60 * 1000;
/** Window start times in `grid` mode are `gridMinutes` apart, from the window's start; this when unset. */
const DEFAULT_GRID_MINUTES = 30;
/** In `edges` mode, a free stretch that has already begun starts at the next quarter hour. */
const EDGE_ROUND_MS = 15 * MINUTE_MS;
/** A JSON field's value (PocketBase hands JSVM raw bytes), or `fallback`. */
function jsonValue(value, fallback) {
try {
const parsed = JSON.parse(toString(value) || 'null');
return parsed == null ? fallback : parsed;
} catch (_) {
return fallback;
}
}
// ── Services: durations and prices ──────────────────────────────────────
function isService(item) {
return !!item && item.getString('type') === 'item_with_time';
}
/** A service's durations, `[{ minutes, price }]` by length; invalid entries are left out. */
function itemDurations(item) {
const list = jsonValue(item.get('durations'), []);
return (Array.isArray(list) ? list : [])
.map((d) => ({ minutes: Math.floor(Number(d && d.minutes)), price: Number(d && d.price) }))
.filter((d) => d.minutes > 0 && d.price >= 0 && Number.isFinite(d.price))
.sort((a, b) => a.minutes - b.minutes);
}
/** Price of one unit: a product's price, or a service's price for `minutes` (null when not offered). */
function unitPrice(item, minutes) {
if (!isService(item)) return item.getFloat('price');
const duration = itemDurations(item).find((d) => d.minutes === minutes);
return duration ? duration.price : null;
}
function bookableService(item, minutes) {
return isService(item) && item.getBool('active') && unitPrice(item, minutes) !== null;
}
function bufferMs(item) {
return Math.max(0, item ? item.getInt('bufferMinutes') : 0) * MINUTE_MS;
}
/** Items by id, read once per call. */
function itemLookup(app) {
const cache = {};
return (id) => {
if (!(id in cache)) cache[id] = findOrNull(app, 'items', id);
return cache[id];
};
}
// ── Slot availability ───────────────────────────────────────────────────
//
// Nothing about bookings is stored on a slot. Bookings are paid order lines
// and basket lines whose hold (`heldUntil`) hasn't lapsed; each has its own
// `start` and `minutes`, and keeps the practitioner busy until its service's
// get-ready time is over (`readyAt`). One practitioner works every service,
// so any booking blocks every other one it overlaps.
// Nothing about bookings is stored on a slot. Its seats are taken by paid
// order lines and by basket lines whose hold (`heldUntil`) hasn't lapsed;
// it has `capacity` seats (1 for a one-to-one massage, more for a group).
//
// A slot is either
// - a `window` (09:00–12:00 with the services that can be booked in it):
// a booking may start wherever its length plus get-ready time is free.
// `startTimes` = `grid`: every `gridMinutes` (default 30) from the window's start;
// `edges`: only right at the start or end of a free stretch, so the
// window shrinks from either end and no unusable gaps are left. A
// booking must end inside the window; its get-ready time may run past.
// - a `session`: one service at a fixed time with `capacity` places (a
// group class). Any place taken makes its whole time busy; it can't be
// booked while something else overlaps it.
// One practitioner works all services, so a slot with any seat taken
// BLOCKS every other slot it overlaps — whatever the service — including
// each service's get-ready time after it. The client can offer three
// massages at 10:00; once one is booked (or in a basket), the others go.
/**
* Bookings starting in [rangeStart - 1 day, rangeEnd + 1 day), sorted by
* start: `{ lineId, slot, item, itemName, start, end, readyAt, quantity,
* status: 'booked' | 'held' }`. `options.excludeLineId` leaves one basket
* line out (when re-checking that line itself).
* Occupancy and blocking for the slots starting in [rangeStart, rangeEnd) (epoch ms).
* `options.excludeLineId` leaves one basket line's seats out (used when
* changing that line's quantity). Must run inside a transaction when the
* result decides a write: PocketBase runs transactions one at a time, so
* the check and the write can't interleave with another customer's.
*/
function busyTimes(app, rangeStart, rangeEnd, item, options) {
function slotStates(app, rangeStart, rangeEnd, options) {
const opts = options || {};
// Slots just outside the range can still block ones inside it.
const range = { from: pbDate(rangeStart - DAY_MS), to: pbDate(rangeEnd + DAY_MS) };
const busy = [];
const add = (line, status) => {
const start = toMs(line.getString('start'));
if (Number.isNaN(start)) return;
const service = item(line.getString('item'));
const end = start + line.getInt('minutes') * MINUTE_MS;
busy.push({
lineId: line.id,
slot: line.getString('slot'),
item: line.getString('item'),
itemName: service ? service.getString('name') : '',
start,
end,
readyAt: end + bufferMs(service),
quantity: line.getInt('quantity'),
status
});
};
const inRange = 'start >= {:from} && start < {:to}';
for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + inRange, range)) add(line, 'booked');
const held = Object.assign({ now: pbDate(Date.now()) }, range);
for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + inRange, held)) {
if (line.id !== opts.excludeLineId) add(line, 'held');
}
return busy.sort((a, b) => a.start - b.start);
}
const records = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start');
if (!records.length) return [];
function overlapsBusy(busy, start, until) {
return busy.find((b) => b.start < until && start < b.readyAt) || null;
}
/**
* Slots starting in [rangeStart, rangeEnd) (epoch ms) with what's booked
* in and around them. Returns `{ slots, busy }`. Must run inside a
* transaction when the result decides a write: PocketBase runs
* transactions one at a time, so the check and the write can't interleave
* with another customer's.
*/
function availability(app, rangeStart, rangeEnd, options) {
const item = itemLookup(app);
const busy = busyTimes(app, rangeStart, rangeEnd, item, options);
const range = { from: pbDate(rangeStart), to: pbDate(rangeEnd) };
const slots = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start').map((record) => {
const items = record.getStringSlice('items');
const items = {};
const byId = {};
const states = records.map((record) => {
const itemId = record.getString('item');
if (!(itemId in items)) items[itemId] = findOrNull(app, 'items', itemId);
const item = items[itemId];
const start = toMs(record.getString('start'));
const end = toMs(record.getString('end'));
const slot = {
const storedEnd = toMs(record.getString('end'));
const end = Number.isNaN(storedEnd) ? start + (item ? item.getInt('duration') : 0) * 60000 : storedEnd;
const state = {
id: record.id,
kind: record.getString('kind') === 'session' ? 'session' : 'window',
items,
itemNames: items.map((id) => (item(id) ? item(id).getString('name') : '')),
item: itemId,
itemName: item ? item.getString('name') : '',
bookable: !!item && item.getBool('active') && item.getString('type') === 'item_with_time',
start,
end,
notes: record.getString('notes')
readyAt: end + Math.max(0, item ? item.getInt('bufferMinutes') : 0) * 60000,
capacity: Math.max(1, record.getInt('capacity')),
notes: record.getString('notes'),
booked: 0,
held: 0,
blockedBy: ''
};
const own = busy.filter((b) => b.slot === record.id);
const count = (status) => own.filter((b) => b.status === status).reduce((sum, b) => sum + b.quantity, 0);
slot.booked = count('booked');
slot.held = count('held');
if (slot.kind === 'window') {
slot.startTimes = record.getString('startTimes') === 'edges' ? 'edges' : 'grid';
slot.gridMinutes = Math.max(5, record.getInt('gridMinutes') || DEFAULT_GRID_MINUTES);
return slot;
}
const service = item(items[0]);
slot.minutes = Math.round((end - start) / MINUTE_MS);
slot.readyAt = end + bufferMs(service);
slot.capacity = Math.max(1, record.getInt('capacity'));
slot.bookable = bookableService(service, slot.minutes);
slot.blockedBy = overlapsBusy(busy.filter((b) => b.slot !== record.id), start, slot.readyAt);
return slot;
byId[record.id] = state;
return state;
});
return { slots, busy };
}
function freeSeats(session) {
return session.capacity - session.booked - session.held;
}
/** The free stretches of a window, `[{ start, end }]`: its time minus every booking's time and get-ready time. */
function freeTimes(window, busy) {
const free = [];
let cursor = window.start;
for (const b of busy) {
if (b.readyAt <= window.start || b.start >= window.end) continue;
if (b.start > cursor) free.push({ start: cursor, end: b.start });
cursor = Math.max(cursor, b.readyAt);
const lineRange = 'slot.start >= {:from} && slot.start < {:to}';
for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + lineRange, range)) {
const state = byId[line.getString('slot')];
if (state) state.booked += line.getInt('quantity');
}
if (cursor < window.end) free.push({ start: cursor, end: window.end });
return free;
const heldParams = Object.assign({ now: pbDate(Date.now()) }, range);
for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + lineRange, heldParams)) {
const state = byId[line.getString('slot')];
if (state && line.id !== opts.excludeLineId) state.held += line.getInt('quantity');
}
const occupied = states.filter((s) => s.booked + s.held > 0);
for (const state of states) {
const blocker = occupied.find((o) => o.id !== state.id && state.start < o.readyAt && o.start < state.readyAt);
if (blocker) state.blockedBy = blocker.id;
}
return states.filter((s) => s.start >= rangeStart && s.start < rangeEnd);
}
/** Where `item` for `minutes` can start in `window` now (epoch ms, ascending). */
function windowStartTimes(window, item, minutes, busy, now) {
if (!item || window.items.indexOf(item.id) < 0 || !bookableService(item, minutes)) return [];
const length = minutes * MINUTE_MS;
const until = length + bufferMs(item);
const fits = (start) => start > now && start >= window.start && start + length <= window.end && !overlapsBusy(busy, start, start + until);
const candidates = [];
if (window.startTimes === 'edges') {
for (const stretch of freeTimes(window, busy)) {
// The latest start keeps this booking's get-ready time clear of the next booking.
const next = busy.find((b) => b.start >= stretch.end);
candidates.push(Math.max(stretch.start, Math.ceil(now / EDGE_ROUND_MS) * EDGE_ROUND_MS));
candidates.push(Math.min(window.end - length, (next ? next.start : Infinity) - until));
}
} else {
for (let start = window.start; start + length <= window.end; start += window.gridMinutes * MINUTE_MS) candidates.push(start);
}
return candidates.filter((start, i) => candidates.indexOf(start) === i && fits(start)).sort((a, b) => a - b);
/** One slot's state (see slotStates), or null if it doesn't exist. */
function slotState(app, slotId, options) {
const record = findOrNull(app, 'slots', slotId);
if (!record) return null;
const start = toMs(record.getString('start'));
return slotStates(app, start, start + 1, options).find((s) => s.id === slotId) || null;
}
/**
* Bookable times for one service and duration starting in [from, to):
* window start times and group sessions with places left.
*/
function timesFor(app, item, minutes, from, to) {
function freeSeats(state) {
return state.capacity - state.booked - state.held;
}
/** Future slots a customer can book right now — the public shop listing. */
function bookableSlots(app) {
const now = Date.now();
const { slots, busy } = availability(app, from, to);
const times = [];
for (const slot of slots) {
if (slot.kind === 'window') {
for (const start of windowStartTimes(slot, item, minutes, busy, now)) {
times.push({ slot: slot.id, kind: 'window', start, end: start + minutes * MINUTE_MS, capacity: 1, free: 1 });
}
} else if (slot.items[0] === item.id && slot.minutes === minutes && slot.bookable && !slot.blockedBy && slot.start > now && freeSeats(slot) > 0) {
times.push({ slot: slot.id, kind: 'session', start: slot.start, end: slot.end, capacity: slot.capacity, free: freeSeats(slot) });
}
}
return times.sort((a, b) => a.start - b.start);
return slotStates(app, now, now + 366 * DAY_MS)
.filter((s) => s.bookable && !s.blockedBy && freeSeats(s) > 0)
.map((s) => ({
id: s.id,
item: s.item,
start: new Date(s.start).toISOString(),
end: new Date(s.end).toISOString(),
capacity: s.capacity,
free: freeSeats(s)
}));
}
/**
* The public shop listing (GET /api/shop/slots): times a customer can book
* now for `item` at `minutes`, starting in [from, to). When there are none,
* `next` is the first bookable time after `to` (within a year), so the shop
* can point to it.
*/
function bookableTimes(app, query) {
const empty = { times: [], next: null };
const item = findOrNull(app, 'items', String(query.item || ''));
const minutes = Math.floor(Number(query.minutes));
if (!bookableService(item, minutes)) return empty;
const now = Date.now();
const from = Math.max(now, toMs(query.from));
const to = toMs(query.to);
if (Number.isNaN(from) || Number.isNaN(to)) throw new BadRequestError('from and to are required');
if (to - from > 100 * DAY_MS) throw new BadRequestError('Range too long');
const iso = (ms) => new Date(ms).toISOString();
const listed = (t) => ({ slot: t.slot, kind: t.kind, start: iso(t.start), end: iso(t.end), capacity: t.capacity, free: t.free });
const times = to > from ? timesFor(app, item, minutes, from, to) : [];
if (times.length) return { times: times.map(listed), next: null };
for (let start = Math.max(from, to); start < now + 366 * DAY_MS; start += 31 * DAY_MS) {
const later = timesFor(app, item, minutes, start, start + 31 * DAY_MS);
if (later.length) return { times: [], next: iso(later[0].start) };
}
return empty;
}
/**
* Every slot in a range (or one slot by id) with its bookings — for the
* signed-in admin. `query`: from/to (ISO), optional item, or id.
* `bookings`: every booked/held time starting in the range, or for one
* slot, that slot's own.
* Every slot in a range (or one slot by id) with its seats and blocking —
* for the signed-in admin. `query`: from/to (ISO), optional item, or id.
*/
function slotDetails(app, query) {
let slots;
let busy;
let from;
let to;
let states;
if (query.id) {
const record = findOrNull(app, 'slots', String(query.id));
if (!record) return { slots: [], bookings: [] };
from = toMs(record.getString('start'));
to = from + 1;
({ slots, busy } = availability(app, from, to));
const state = slotState(app, String(query.id));
states = state ? [state] : [];
} else {
from = toMs(query.from);
to = toMs(query.to);
const from = toMs(query.from);
const to = toMs(query.to);
if (Number.isNaN(from) || Number.isNaN(to) || to <= from) throw new BadRequestError('from and to are required');
if (to - from > 400 * DAY_MS) throw new BadRequestError('Range too long');
({ slots, busy } = availability(app, from, to));
if (query.item) slots = slots.filter((s) => s.items.indexOf(String(query.item)) >= 0);
states = slotStates(app, from, to);
if (query.item) states = states.filter((s) => s.item === query.item);
}
const iso = (ms) => new Date(ms).toISOString();
const booking = (b) => ({ slot: b.slot, item: b.item, itemName: b.itemName, start: iso(b.start), end: iso(b.end), readyAt: iso(b.readyAt), quantity: b.quantity, status: b.status });
return {
slots: slots.map((s) => {
const detail = { id: s.id, kind: s.kind, items: s.items, itemNames: s.itemNames, start: iso(s.start), end: iso(s.end), notes: s.notes, booked: s.booked, held: s.held };
if (s.kind === 'window') {
detail.startTimes = s.startTimes;
detail.gridMinutes = s.gridMinutes;
detail.free = freeTimes(s, busy).map((f) => ({ start: iso(f.start), end: iso(f.end) }));
} else {
detail.minutes = s.minutes;
detail.capacity = s.capacity;
detail.blockedBy = s.blockedBy ? booking(s.blockedBy) : null;
}
return detail;
}),
bookings: busy.filter((b) => (query.id ? b.slot === String(query.id) : b.start >= from && b.start < to)).map(booking)
};
return states.map((s) => ({
id: s.id,
item: s.item,
itemName: s.itemName,
start: new Date(s.start).toISOString(),
end: new Date(s.end).toISOString(),
capacity: s.capacity,
notes: s.notes,
booked: s.booked,
held: s.held,
blockedBy: s.blockedBy
}));
}
/** Check a session can take `seats` more places; returns an ApiError to throw, or null. */
function seatProblem(session, seats) {
if (!session.bookable) return new NotFoundError('This session is no longer offered');
if (session.start <= Date.now()) return conflict('This time has already passed — please pick another');
if (session.blockedBy) return conflict('This time is no longer available — please pick another');
const free = freeSeats(session);
/**
* Check a slot can take `seats` more seats; returns an ApiError to throw,
* or null. Call inside the transaction that then writes the hold.
*/
function seatProblem(state, seats) {
if (!state || !state.bookable) return new NotFoundError('Slot not found');
if (state.start <= Date.now()) return conflict('This time has already passed — please pick another');
if (state.blockedBy) return conflict('This time is no longer available — please pick another');
const free = freeSeats(state);
if (seats > free) {
return conflict(free <= 0 ? 'This time is fully booked — please pick another' : `Only ${free} place${free === 1 ? '' : 's'} left at this time`);
}
return null;
}
/**
* Check a booking request — `{ slotId, itemId, minutes, start (ms), seats }`
* — against availability. Returns `{ error }` (an ApiError to throw) or
* `{ booking: { slot, kind, item, start, minutes } }` (for a session, its
* own service and time; itemId/minutes/start are ignored). Call inside the
* transaction that then writes the hold.
*/
function checkBooking(app, request, options) {
const record = findOrNull(app, 'slots', String(request.slotId || ''));
if (!record) return { error: new NotFoundError('This time is no longer offered — please pick another') };
const slotStart = toMs(record.getString('start'));
const { slots, busy } = availability(app, slotStart, slotStart + 1, options);
const slot = slots.find((s) => s.id === record.id);
if (!slot) return { error: new NotFoundError('This time is no longer offered — please pick another') };
if (slot.kind === 'session') {
const problem = seatProblem(slot, request.seats);
if (problem) return { error: problem };
return { booking: { slot: slot.id, kind: 'session', item: slot.items[0], start: slot.start, minutes: slot.minutes } };
}
const now = Date.now();
const item = findOrNull(app, 'items', String(request.itemId || ''));
const minutes = Math.floor(Number(request.minutes));
if (!bookableService(item, minutes)) return { error: new NotFoundError('This service is not offered at this length any more') };
if (!(request.start > now)) return { error: conflict('This time has already passed — please pick another') };
if (windowStartTimes(slot, item, minutes, busy, now).indexOf(request.start) < 0) {
return { error: conflict('This time is no longer available — please pick another') };
}
return { booking: { slot: slot.id, kind: 'window', item: item.id, start: request.start, minutes } };
}
/** What a basket line asks for, in checkBooking's terms. */
function lineRequest(line) {
return {
slotId: line.getString('slot'),
itemId: line.getString('item'),
minutes: line.getInt('minutes'),
start: toMs(line.getString('start')),
seats: line.getInt('quantity')
};
}
/**
* Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing
* is written) or nothing to commit. Unexpected failures become `fallback`.
@ -459,26 +259,12 @@ function basketLines(app, basketId) {
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: basketId });
}
/**
* The basket as returned to the public app, which maps it to the `Basket`
* type. Each line also gets `unitPrice` (null: the service is no longer
* offered at that length) and, for a booking, `end`.
*/
/** The basket as returned to the public app, which maps it to the `Basket` type. */
function basketPayload(app, basket) {
if (!basket) return null;
const lines = basketLines(app, basket.id);
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
return {
record: plain(basket),
lines: lines.map((line) => {
const json = plain(line);
const item = line.expandedOne('item');
json.unitPrice = item ? unitPrice(item, line.getInt('minutes')) : null;
const start = toMs(line.getString('start'));
if (!Number.isNaN(start)) json.end = new Date(start + line.getInt('minutes') * MINUTE_MS).toISOString();
return json;
})
};
return { record: plain(basket), lines: lines.map(plain) };
}
function createBasket(app) {
@ -491,10 +277,10 @@ function createBasket(app) {
* Renew the hold on every slot line in a basket. Used at checkout start
* (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 (it's already counted). A lapsed one that
* hasn't been swept yet is rescued only if its time could still be booked
* now — otherwise it's left for the sweep, and checkout tells the customer
* the time expired.
* 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.
*/
function extendBasketHolds(app, basketId, durationMs) {
const now = Date.now();
@ -511,7 +297,7 @@ function extendBasketHolds(app, basketId, durationMs) {
try {
app.runInTransaction((tx) => {
const fresh = tx.findRecordById('basket_lines', line.id);
if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return;
if (seatProblem(slotState(tx, fresh.getString('slot')), fresh.getInt('quantity'))) return;
fresh.set('heldUntil', until);
tx.save(fresh);
});
@ -557,35 +343,15 @@ function basketAction(app, body) {
}
case 'add_slot': {
// A window booking: `slotId` (the window), `itemId`, `minutes` and
// `start` (one of the listed times). A group session: `slotId` and
// `seats`; adding a session already in the basket adds places to
// that line.
const request = {
slotId: String(body.slotId || ''),
itemId: String(body.itemId || ''),
minutes: Math.floor(Number(body.minutes)),
start: toMs(body.start),
seats: Math.max(1, Math.floor(Number(body.seats)) || 1)
};
// Adding a slot that's already in the basket adds seats to that line.
const slotId = String(body.slotId || '');
const seats = Math.max(1, Math.floor(Number(body.seats)) || 1);
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
const check = checkBooking(tx, request);
if (check.error) return check.error;
const booking = check.booking;
const existing =
booking.kind === 'session' ? findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: booking.slot })[0] : null;
const line =
existing ||
newRecord(tx, 'basket_lines', {
basket: basket.id,
item: booking.item,
slot: booking.slot,
start: new Date(booking.start).toISOString(),
minutes: booking.minutes,
quantity: 0,
lineType: 'slot'
});
line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1));
const problem = seatProblem(slotState(tx, slotId), seats);
if (problem) return problem;
const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0];
const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' });
line.set('quantity', line.getInt('quantity') + seats);
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
tx.save(line);
});
@ -598,13 +364,11 @@ function basketAction(app, body) {
const quantity = Number(body.quantity);
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
if (line.getString('lineType') === 'slot') {
// Places in a group session: re-check capacity without this line's current places.
// Seats for a group session: re-check capacity without this line's current seats.
guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => {
const fresh = tx.findRecordById('basket_lines', line.id);
const slot = findOrNull(tx, 'slots', fresh.getString('slot'));
if (!slot || slot.getString('kind') !== 'session') return new BadRequestError('Only group sessions have more than one place');
const check = checkBooking(tx, Object.assign(lineRequest(fresh), { seats: quantity }), { excludeLineId: fresh.id });
if (check.error) return check.error;
const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity);
if (problem) return problem;
fresh.set('quantity', quantity);
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
tx.save(fresh);
@ -725,9 +489,7 @@ function startCheckout(app, body) {
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
}
}
const price = unitPrice(item, line.getInt('minutes'));
if (price === null) throw conflict(`"${item.getString('name')}" is no longer offered for ${line.getInt('minutes')} minutes — please pick it again`);
totalCents += Math.round(price * 100) * quantity;
totalCents += Math.round(item.getFloat('price') * 100) * quantity;
summary.push(`${quantity}× ${item.getString('name')}`);
}
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
@ -840,11 +602,12 @@ function createOrderFromIntent(app, intent) {
});
tx.save(order);
// Snapshot lines and decrement stock. A booked time moves from the
// Snapshot lines and decrement stock. A slot's seats move from the
// basket line (a hold) to the order line (a booking) in this same
// transaction, so availability never sees it free in between.
// transaction, so availability never sees them free in between.
for (const line of lines) {
const item = findOrNull(tx, 'items', line.getString('item'));
const slot = findOrNull(tx, 'slots', line.getString('slot'));
tx.save(
newRecord(tx, 'order_lines', {
order: order.id,
@ -853,9 +616,8 @@ function createOrderFromIntent(app, intent) {
quantity: line.getInt('quantity'),
lineType: line.getString('lineType'),
name: item ? item.getString('name') : 'Unknown item',
price: (item && unitPrice(item, line.getInt('minutes'))) || 0,
start: line.getString('start'),
minutes: line.getInt('minutes')
price: item ? item.getFloat('price') : 0,
start: slot ? slot.getString('start') : ''
})
);
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
@ -953,7 +715,7 @@ function recordEmailStatus(app, secretHeader, body) {
}
module.exports = {
bookableTimes,
bookableSlots,
slotDetails,
sweepExpiredHolds,
loadActiveBasket,

View file

@ -1,166 +0,0 @@
/// <reference path="../pb_data/types.d.ts" />
// Services get several durations; slots become availability windows.
//
// Before: a service had one `duration` and `price`, and a slot was one
// service at one fixed time. After:
//
// - items.durations: [{ minutes, price }] — a service can be booked for any
// of these (items.price stays: the product price, and for a service the
// lowest duration price, kept in sync by the admin). items.duration goes.
// - slots.kind: `window` — a stretch of time (09:00–12:00) in which any of
// its `items` can be booked, for any of their durations; each booking
// takes its time plus get-ready time out of the window. `startTimes`
// says where bookings may start: `grid` (every `gridMinutes`, default 30) or `edges` (only
// right at the start or end of the free time, so no gaps are left).
// `session` — a fixed time for one service with `capacity` places (a
// group class), as slots were before.
// - basket_lines / order_lines: `start` and `minutes` — the booked time
// (order_lines already had `start`). A booking no longer needs its slot
// to count: availability reads these.
//
// Existing slots are deleted (agreed: start fresh). Before that, every
// order line gets `minutes` from its slot, so paid bookings keep blocking
// their time; basket holds on slots are dropped (customers pick again).
// Past orders keep their own name/price/start snapshot.
function find(app, name) {
try {
return app.findCollectionByNameOrId(name);
} catch (e) {
return null; // fresh install: pb_schema.json (already in this shape) is imported later
}
}
function minutesBetween(start, end) {
const ms = Date.parse(String(end).replace(' ', 'T')) - Date.parse(String(start).replace(' ', 'T'));
return ms > 0 ? Math.round(ms / 60000) : 0;
}
migrate(
(app) => {
const items = find(app, 'items');
const slots = find(app, 'slots');
const basketLines = find(app, 'basket_lines');
const orderLines = find(app, 'order_lines');
// 1. Durations (one per service from its old duration + price).
if (items && !items.fields.getByName('durations')) {
items.fields.add(new JSONField({ id: 'json_itemdurations', name: 'durations', maxSize: 20000 }));
app.save(items);
for (const item of app.findAllRecords('items')) {
if (item.getString('type') !== 'item_with_time') continue;
item.set('durations', [{ minutes: item.getInt('duration') || 60, price: item.getFloat('price') }]);
try {
app.saveNoValidate(item);
} catch (e) {
console.log(`[migration] could not set durations on item ${item.id}: ${e}`);
}
}
}
if (items && items.fields.getByName('duration')) {
items.fields.removeByName('duration');
app.save(items);
}
// 2. Booked times on the lines.
if (basketLines && !basketLines.fields.getByName('minutes')) {
basketLines.fields.add(new DateField({ id: 'date_blstart0001', name: 'start' }));
basketLines.fields.add(new NumberField({ id: 'num_blminutes001', name: 'minutes', min: 0, onlyInt: true }));
basketLines.indexes = [...basketLines.indexes, 'CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)'];
app.save(basketLines);
}
if (orderLines && !orderLines.fields.getByName('minutes')) {
orderLines.fields.add(new NumberField({ id: 'num_olminutes001', name: 'minutes', min: 0, onlyInt: true }));
orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)'];
app.save(orderLines);
}
// 3. Start fresh: keep what paid bookings need, then drop the old slots.
if (slots && slots.fields.getByName('item')) {
if (orderLines) {
for (const line of app.findRecordsByFilter('order_lines', "slot != ''", '', 0, 0)) {
try {
const slot = app.findRecordById('slots', line.getString('slot'));
if (!line.getString('start')) line.set('start', slot.getString('start'));
line.set('minutes', minutesBetween(slot.getString('start'), slot.getString('end')));
line.set('slot', '');
app.saveNoValidate(line);
} catch (e) {
console.log(`[migration] could not keep the booked time of order line ${line.id}: ${e}`);
}
}
}
if (basketLines) {
for (const line of app.findRecordsByFilter('basket_lines', "lineType = 'slot'", '', 0, 0)) {
try {
app.delete(line);
} catch (e) {
console.log(`[migration] could not drop basket line ${line.id}: ${e}`);
}
}
}
for (const slot of app.findAllRecords('slots')) {
try {
app.delete(slot);
} catch (e) {
console.log(`[migration] could not delete slot ${slot.id}: ${e}`);
}
}
slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_item_start')), 'CREATE INDEX `idx_slots_start` ON `slots` (`start`)'];
slots.fields.removeByName('item');
slots.fields.add(new SelectField({ id: 'sel_slotkind001', name: 'kind', values: ['window', 'session'], maxSelect: 1, required: true }));
slots.fields.add(new RelationField({ id: 'rel_slotitems01', name: 'items', collectionId: items ? items.id : 'pbc_items00001', maxSelect: 50, cascadeDelete: false }));
slots.fields.add(new SelectField({ id: 'sel_slotstarts1', name: 'startTimes', values: ['grid', 'edges'], maxSelect: 1 }));
slots.fields.add(new NumberField({ id: 'num_slotgridmin1', name: 'gridMinutes', min: 5, max: 240, onlyInt: true }));
app.save(slots);
}
},
(app) => {
// Revert the schema only. Windows can't become one-service slots, so
// slots are deleted again; restore a backup to get the old ones back.
const items = find(app, 'items');
const slots = find(app, 'slots');
if (items && !items.fields.getByName('duration')) {
items.fields.add(new NumberField({ id: 'num_itemdur0001', name: 'duration', min: 1 }));
app.save(items);
for (const item of app.findAllRecords('items')) {
let durations = [];
try {
durations = JSON.parse(toString(item.get('durations')) || '[]') || [];
} catch (_) {}
if (!durations.length) continue;
item.set('duration', durations[0].minutes);
app.saveNoValidate(item);
}
}
if (items && items.fields.getByName('durations')) {
items.fields.removeByName('durations');
app.save(items);
}
if (slots && !slots.fields.getByName('item')) {
for (const line of app.findRecordsByFilter('basket_lines', "lineType = 'slot'", '', 0, 0)) app.delete(line);
for (const slot of app.findAllRecords('slots')) app.delete(slot);
for (const name of ['kind', 'items', 'startTimes', 'gridMinutes']) {
if (slots.fields.getByName(name)) slots.fields.removeByName(name);
}
slots.fields.add(new RelationField({ id: 'rel_slotitem001', name: 'item', required: true, collectionId: items ? items.id : 'pbc_items00001', maxSelect: 1, cascadeDelete: true }));
slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_start')), 'CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)'];
app.save(slots);
}
const basketLines = find(app, 'basket_lines');
if (basketLines && basketLines.fields.getByName('minutes')) {
basketLines.fields.removeByName('start');
basketLines.fields.removeByName('minutes');
basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_start'));
app.save(basketLines);
}
const orderLines = find(app, 'order_lines');
if (orderLines && orderLines.fields.getByName('minutes')) {
orderLines.fields.removeByName('minutes');
orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_start'));
app.save(orderLines);
}
}
);