Compare commits

..

8 commits

Author SHA1 Message Date
650de78bac Merge pull request 'Services with several lengths; slots become time windows' (#6) from session/change-slots-behavior into main
Reviewed-on: #6
2026-10-25 22:16:34 +01:00
ce3866550a Windows: choose the start-time step (10–60 min, default 30)
A window on fixed steps now has gridMinutes; the admin picks it when
creating or generating windows, and copies keep it. Added to the
(unmerged, undeployed) time-windows migration and pb_schema.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 21:03:40 +00:00
6ab0b75ec3 Shop: pick the length after pressing Book
The card shows "from" the lowest price and the range of lengths; the
slider moves into the booking panel, above the date picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 20:56:05 +00:00
e1a8a54458 Docs: windows, durations and the new slot availability rules
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 20:12:46 +00:00
636b59c706 Admin: lengths and prices per service; windows and group sessions on /slots
Services get rows of length + price. /slots creates windows (date, hours,
services, start-times mode) and group sessions (service, length, start,
places); the day view shows free time and bookings. Generate/copy/clear
handle both kinds; windows may not overlap and can't shrink past a booking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 20:12:46 +00:00
eac99b2abe Shop: duration slider on services, times fetched per service and length
Service cards step through their lengths with a slider and the price
follows. The time picker loads bookable times for the chosen length and
the months on screen from GET /api/slots (a proxy to the shop hook in each
app), and reloads when the basket's bookings change. Checkout, emails and
the basket show each booking's own length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 20:12:46 +00:00
23df2ceced Shop hooks: a slot lookup by id returns all of that slot's bookings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 20:12:46 +00:00
b3ecc1722b Shop hooks: several durations per service, slots become time windows
A service now has `durations` ([{ minutes, price }]) instead of one
duration and price. A slot is either a `window` (a stretch of time with the
services that can be booked in it, start times every 30 min or only at the
edges of the free time) or a `session` (one service, fixed time, places —
the old group slot). Basket and order lines carry their own start and
minutes, so availability is computed from bookings alone.

The migration keeps paid bookings blocking their time (order lines get
minutes from their slot), then deletes the old slots — agreed: start fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
2026-10-25 19:59:00 +00:00
36 changed files with 2280 additions and 1208 deletions

View file

@ -29,14 +29,14 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ ├── pages/ # Page CRUD + block editor │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── calendar/ # Event CRUD (menu label: Events)
│ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── orders/ # Order list + booking-email status/resend
│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings │ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings
│ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
│ │ ├── backup/ # Export/import UI (calls api/export, api/import) │ │ ├── backup/ # Export/import UI (calls api/export, api/import)
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin) │ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
│ │ └── api/ # upload, export, import endpoints │ │ └── api/ # upload, export, import, slots (Shop block times in /preview) endpoints
│ ├── hooks.server.ts # Auth guard — all routes except /login │ ├── hooks.server.ts # Auth guard — all routes except /login
│ └── app.css # Tailwind + DaisyUI + custom theme │ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets ├── static/ # Static assets
@ -60,7 +60,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
│ │ ├── +layout.svelte # Root layout (always renders Header/Footer) │ │ ├── +layout.svelte # Root layout (always renders Header/Footer)
│ │ ├── +page.svelte # Home page (slug=home) │ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages │ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── api/ # basket, checkout, webhooks endpoints │ │ ├── api/ # basket, checkout, webhooks, slots (Shop block times) endpoints
│ │ └── checkout/return/ # Stripe return URL │ │ └── checkout/return/ # Stripe return URL
│ ├── hooks.server.ts # Creates PB client in locals (no auth guard) │ ├── hooks.server.ts # Creates PB client in locals (no auth guard)
│ └── app.css # Tailwind + DaisyUI + custom theme │ └── app.css # Tailwind + DaisyUI + custom theme
@ -119,6 +119,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### Shared Code ### Shared Code
- `packages/shared/src/types.ts` — all type definitions - `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/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` - `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 `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 - 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
@ -131,7 +132,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). - **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. - **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. - **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** (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*. - **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*.
- **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)*. - **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). - **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).
@ -188,4 +189,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. - `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`. - 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. - `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`; slots via `GET /api/shop/slots`); if a Shop block 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`). 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".

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): 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), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new slots), `active` bool - `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` — `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 - `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
- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text - `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`, `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`, `start` date and `minutes` number (a slot line's booked time), `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) - `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 (nullable, snapshot) - `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)
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool - `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. > **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,7 +138,8 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages/[slug]` — block editor with draft preview - `/pages/[slug]` — block editor with draft preview
- `/calendar` — events shown by Upcoming Calendar blocks - `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services and products shown in Shop blocks - `/items` — services and products shown in Shop blocks
- `/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. - `/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.
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons - `/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)*) - `/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) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
@ -150,12 +151,14 @@ 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`. **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** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live): **Slot availability** (`availability()` / `windowStartTimes()` / `checkBooking()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live):
- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line. 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. - 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 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. - One practitioner works every service, so no booking may overlap another — whatever the service, whatever the slot — including get-ready time.
- `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). - 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.
- 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. - 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.
Setup: Setup:

View file

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

View file

@ -33,7 +33,7 @@
<Modal bind:open title="Clear slots" wide> <Modal bind:open title="Clear slots" wide>
<form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1"> <form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1">
<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> <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>
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
@ -49,7 +49,7 @@
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Services</span> <span class="fieldset-legend">Services</span>
<select class="select w-full" name="item" bind:value={draft.item}> <select class="select w-full" name="item" bind:value={draft.item}>
<option value="">All services</option> <option value="">All slots</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each} {#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select> </select>
</label> </label>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,49 +1,68 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import type { ItemRecord, ItemType } from '$lib/types'; import { mapItemRecord } from '$shared/server/shop';
import type { ItemDuration, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$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) { function itemPayload(data: FormData) {
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; 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 rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').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 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 bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null; const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null;
return { return {
name: String(data.get('name') || '').trim(), payload: {
description: String(data.get('description') || '').trim(), name,
price: parseFloat(String(data.get('price') || '')), description: String(data.get('description') || '').trim(),
image: String(data.get('image') || '').trim(), price,
type, image: String(data.get('image') || '').trim(),
stock: Number.isNaN(stock) ? null : stock, type,
duration: Number.isNaN(duration) ? null : duration, stock: Number.isNaN(stock) ? null : stock,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, durations,
capacity: Number.isNaN(capacity) ? null : capacity, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
active: String(data.get('active')) === 'true' 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
}; };
} }
@ -52,34 +71,32 @@ export const load: PageServerLoad = async ({ locals }) => {
.collection('items') .collection('items')
.getFullList({ sort: 'name', expand: 'image' }) .getFullList({ sort: 'name', expand: 'image' })
.catch(() => []); .catch(() => []);
const items = records.map((record) => normalizeItem(record)); return { items: records.map(mapItemRecord) };
return { items };
}; };
export const actions: Actions = { export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const data = await request.formData(); const result = itemPayload(await request.formData());
const payload = itemPayload(data); if ('error' in result) return fail(400, { message: result.error });
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload));
const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload)); if (!created.ok) return created.failure;
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); const result = itemPayload(data);
const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload)); if ('error' in result) return fail(400, { message: result.error });
if (!result.ok) return result.failure; const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload));
if (!updated.ok) return updated.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
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)); 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));
if (!result.ok) return result.failure; if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }

View file

@ -3,6 +3,7 @@
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
@ -20,7 +21,8 @@
imageUrl: string; imageUrl: string;
type: ItemType; type: ItemType;
stock: string; stock: string;
duration: string; /** Service lengths and prices, as typed (one form row each). */
durations: { minutes: string; price: string }[];
bufferMinutes: string; bufferMinutes: string;
capacity: string; capacity: string;
active: boolean; active: boolean;
@ -32,7 +34,17 @@
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft { function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true }; 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';
} }
function createItem() { function createItem() {
@ -51,7 +63,7 @@
imageUrl: item.imageUrl, imageUrl: item.imageUrl,
type: item.type, type: item.type,
stock: item.stock == null ? '' : String(item.stock), stock: item.stock == null ? '' : String(item.stock),
duration: item.duration == null ? '' : String(item.duration), durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }],
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity), capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active active: item.active
@ -109,9 +121,9 @@
</div> </div>
</td> </td>
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td> <td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{money.format(item.price)}</td> <td>{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td> <td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</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>{item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min 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><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> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr> </tr>
@ -140,40 +152,59 @@
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea> <textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label> </label>
<div class="grid gap-x-4 md:grid-cols-2"> <label class="fieldset">
<label class="fieldset"> <span class="fieldset-legend">Type</span>
<span class="fieldset-legend">Price ({data.currency})</span> <select class="select w-full" name="type" bind:value={draft.type}>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} /> <option value="item">Product</option>
</label> <option value="item_with_time">Service (bookable)</option>
<label class="fieldset"> </select>
<span class="fieldset-legend">Type</span> </label>
<select class="select w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service (bookable)</option>
</select>
</label>
</div>
{#if draft.type === 'item'} {#if draft.type === 'item'}
<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>
{:else}
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Duration (minutes)</span> <span class="fieldset-legend">Price ({data.currency})</span>
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} /> <input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label> </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"> <label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span> <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} /> <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 — between generated slots, and before another service can start</span> <span class="label">Gap after each appointment, before the next one can start</span>
</label> </label>
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Places per slot</span> <span class="fieldset-legend">Places in a group session</span>
<input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} /> <input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} />
<span class="label">1 for one-to-one; more for a group session. New slots start with this.</span> <span class="label">Only for group sessions (Slots → group session). New sessions start with this.</span>
</label> </label>
</div> </div>
{/if} {/if}

View file

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

View file

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

View file

@ -3,14 +3,15 @@ import { loadShopData } from '$shared/server/shop';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
// The draft blocks come from sessionStorage (client-side), so load the data // The draft blocks come from sessionStorage (client-side), so load the data
// any block might need: shop items/slots and upcoming events. Failures leave // any block might need: shop items and upcoming events (Shop blocks fetch
// bookable times themselves). Failures leave
// the blocks empty rather than breaking the preview. // the blocks empty rather than breaking the preview.
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
const range = getUpcomingCalendarRange(); const range = getUpcomingCalendarRange();
const [shop, events] = await Promise.all([ const [shop, events] = await Promise.all([
loadShopData(locals.pb).catch((e) => { loadShopData(locals.pb).catch((e) => {
console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e); console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e);
return { items: [], slots: [] }; return { items: [] };
}), }),
locals.pb locals.pb
.collection('events') .collection('events')

View file

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

View file

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

View file

@ -4,33 +4,39 @@
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte'; import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte'; import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte';
import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte'; import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte';
import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots'; 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 type { BulkResult, 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 { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
let serviceFilter = $state(''); let serviceFilter = $state('');
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter)); let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.items.includes(serviceFilter)));
type Slot = (typeof slots)[number]; type Slot = (typeof slots)[number];
let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot]))); type Booking = (typeof data.bookings)[number];
// ── Month grid (date keys in the site timezone) ── // ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4; const MAX_CHIPS = 4;
const dayKeyOf = (iso: string) => toZonedDatetimeInput(iso, data.timezone).slice(0, 10);
let gridKeys = $derived(monthGridKeys(data.month)); let gridKeys = $derived(monthGridKeys(data.month));
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' })); let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1)); let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
let slotsByDay = $derived.by(() => { let slotsByDay = $derived.by(() => {
const byDay = new Map<string, Slot[]>(); const byDay = new Map<string, Slot[]>();
for (const slot of slots) { for (const slot of slots) byDay.set(dayKeyOf(slot.start), [...(byDay.get(dayKeyOf(slot.start)) ?? []), slot]);
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
}
return byDay; return byDay;
}); });
let monthSlots = $derived(slots.filter((slot) => toZonedDatetimeInput(slot.start, data.timezone).startsWith(data.month))); 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)));
// ── Modals ── // ── Modals ──
let showEditor = $state(false); let showEditor = $state(false);
@ -42,13 +48,14 @@
let copyFrom = $state(''); let copyFrom = $state('');
let clearRange = $state({ from: '', to: '' }); let clearRange = $state({ from: '', to: '' });
let daySlots = $derived(slotsByDay.get(dayKey) ?? []); 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); let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null);
function bulkMessage(result: BulkResult) { function bulkMessage(result: BulkResult) {
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`; const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
const verb = result.action === 'clear' ? 'Deleted' : 'Created'; const verb = result.action === 'clear' ? 'Deleted' : 'Created';
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : ''; const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (booked in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`; return `${verb} ${n(result.count)}.${failed}`;
} }
@ -67,15 +74,26 @@
blocked: 'badge-ghost' blocked: 'badge-ghost'
}; };
/** "2/8" for group slots, '' for one-to-one. */ 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. */
function places(slot: Slot) { function places(slot: Slot) {
return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : ''; return slot.kind === 'session' && (slot.capacity ?? 1) > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
} }
/** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */ /** What a window has left, e.g. "Free 10:15–12:00". */
function blockedReason(slot: Slot) { function freeLabel(slot: Slot) {
const blocker = slotsById.get(slot.blockedBy); if (!slot.free?.length) return 'No free time left';
return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking'; 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)})` : ''}`;
} }
function openDay(key: string) { function openDay(key: string) {
@ -95,10 +113,20 @@
showClear = true; showClear = true;
} }
// ── Single slot editor ── // ── Slot editor (a window or a group session) ──
type SlotDraft = { type SlotDraft = {
id: string; id: string;
kind: SlotKind;
// window
date: string;
from: string;
to: string;
items: string[];
startTimes: StartTimesMode;
gridMinutes: number;
// session
item: string; item: string;
minutes: string;
start: string; start: string;
capacity: string; capacity: string;
booked: number; booked: number;
@ -106,23 +134,52 @@
notes: string; notes: string;
}; };
let draft = $state<SlotDraft>(emptyDraft()); let draft = $state<SlotDraft>(emptyDraft('window'));
let editorError = $state(''); let editorError = $state('');
let action = $derived(draft.id ? '?/update' : '?/create'); 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); 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 selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => { let endLabel = $derived.by(() => {
if (!selectedItem || !draft.start) return ''; if (!draft.start || !draft.minutes) return '';
const startIso = zonedInputToIso(draft.start, data.timezone); const startIso = zonedInputToIso(draft.start, data.timezone);
if (!startIso) return ''; if (!startIso) return '';
const end = new Date(new Date(startIso).getTime() + (Number(selectedItem.duration) || 0) * 60_000); return `Ends at ${formatTime(new Date(new Date(startIso).getTime() + Number(draft.minutes) * 60_000).toISOString(), data.timezone)}`;
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
}); });
function emptyDraft(day = ''): SlotDraft { function emptyDraft(kind: SlotKind, day = ''): SlotDraft {
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone); const date = day || data.today;
return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' }; 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) : '';
} }
// Enhanced so the page keeps its ?month= after saving (a plain POST to // Enhanced so the page keeps its ?month= after saving (a plain POST to
@ -139,20 +196,29 @@
}; };
}; };
function createSlot(day = '') { function createSlot(kind: SlotKind, day = '') {
editorError = ''; editorError = '';
draft = emptyDraft(day); draft = emptyDraft(kind, day);
showDay = false; showDay = false;
showEditor = true; showEditor = true;
} }
function editSlot(slot: Slot) { function editSlot(slot: Slot) {
editorError = ''; editorError = '';
const start = toZonedDatetimeInput(slot.start, data.timezone);
draft = { draft = {
...emptyDraft(slot.kind),
id: slot.id, id: slot.id,
item: slot.item, date: start.slice(0, 10),
start: toZonedDatetimeInput(slot.start, data.timezone), from: start.slice(11, 16),
capacity: String(slot.capacity), 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 ?? ''),
booked: slot.booked, booked: slot.booked,
held: slot.held, held: slot.held,
notes: slot.notes notes: slot.notes
@ -165,13 +231,16 @@
<svelte:head><title>Slots | CMS</title></svelte:head> <svelte:head><title>Slots | CMS</title></svelte:head>
<div class="space-y-6"> <div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col gap-4">
<div> <div>
<h1 class="text-3xl font-bold">Slots</h1> <h1 class="text-3xl font-bold">Slots</h1>
<p class="text-base-content/60">Bookable time slots for your services. Times are in {data.timezone}.</p> <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>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button class="btn" type="button" onclick={() => createSlot()}>Create slot</button> <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={() => openCopy(data.today)}>Copy a week</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" 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> <button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button>
@ -218,12 +287,17 @@
<button <button
class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}" class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}"
type="button" type="button"
title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {state === 'blocked' ? blockedReason(slot) : SLOT_STATE_LABELS[state]}{places(slot) ? ` (${places(slot)})` : ''}" title="{range(slot.start, slot.end)} {slot.kind === 'window' ? 'window' : serviceNames(slot)} — {describe(slot, state)}"
onclick={() => editSlot(slot)} onclick={() => openDay(key)}
> >
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span> {#if slot.kind === 'window'}
<span class="hidden lg:inline">{slot.itemName}</span> <span class="font-semibold">{range(slot.start, slot.end)}</span>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if} {#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>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
{/if}
</button> </button>
{/each} {/each}
{#if daySlotList.length > MAX_CHIPS} {#if daySlotList.length > MAX_CHIPS}
@ -238,32 +312,29 @@
{#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)} {#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> <span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {STATE_CLASSES[state as SlotState]}"></span> {label}</span>
{/each} {/each}
<span>— a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.</span> <span>— a booking blocks every other one overlapping it, including get-ready time. Click a day for its bookings and free time.</span>
</div> </div>
</div> </div>
<!-- Collapsed by default: a generated month is hundreds of rows, and the calendar covers day-to-day use. --> <!-- Collapsed by default: a generated month is many rows, and the calendar covers day-to-day use. -->
<details class="collapse collapse-arrow rounded-box bg-base-100 shadow"> <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> <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"> <div class="collapse-content overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th>Service</th><th>Date</th><th>Places</th><th>Status</th><th></th></tr></thead> <thead><tr><th>When</th><th>Kind</th><th>Services</th><th>Booked</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each monthSlots as slot (slot.id)} {#each monthSlots as slot (slot.id)}
{@const state = slotState(slot)} {@const state = slotState(slot)}
<tr> <tr>
<td><span class="font-semibold">{slot.itemName}</span></td> <td>{formatDateTime(slot.start, data.timezone)}–{formatTime(slot.end, data.timezone)}</td>
<td>{formatDateTime(slot.start, data.timezone)}</td> <td>{slot.kind === 'window' ? 'Window' : 'Group session'}</td>
<td>{slot.booked + slot.held}/{slot.capacity}</td> <td>{serviceNames(slot)}</td>
<td> <td>{slot.kind === 'session' ? `${slot.booked + slot.held}/${slot.capacity}` : slot.booked + slot.held}</td>
<span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span> <td><span class="badge {BADGE_CLASSES[state]}" title={describe(slot, state)}>{SLOT_STATE_LABELS[state]}</span></td>
</td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button></td>
<td class="text-right">
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
</td>
</tr> </tr>
{:else} {:else}
<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> <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>
{/each} {/each}
</tbody> </tbody>
</table> </table>
@ -281,10 +352,14 @@
{#each daySlots as slot (slot.id)} {#each daySlots as slot (slot.id)}
{@const state = slotState(slot)} {@const state = slotState(slot)}
<li class="flex items-center gap-3 py-2"> <li class="flex items-center gap-3 py-2">
<span class="w-28 shrink-0 font-semibold">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span> <span class="w-28 shrink-0 font-semibold">{range(slot.start, slot.end)}</span>
<span class="min-w-0 flex-1"> <span class="min-w-0 flex-1">
<span class="block truncate">{slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''}</span> <span class="block truncate">
{#if state === 'blocked'}<span class="block truncate text-xs text-base-content/60">{blockedReason(slot)}</span>{/if} {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>
{#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if} {#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if}
</span> </span>
<span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span> <span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
@ -295,48 +370,143 @@
{:else} {:else}
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p> <p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
{/if} {/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="modal-action flex-wrap justify-between">
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button> <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} {#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if}
</div> </div>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot(dayKey)}>Add slot</button> <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>
</div> </div>
</Modal> </Modal>
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}> <Modal bind:open={showEditor} title={draft.id ? (draft.kind === 'window' ? 'Edit window' : 'Edit group session') : 'Add a slot'} wide>
<form method="POST" action={action} use:enhance={submitSlot} class="space-y-1"> <form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
<input type="hidden" name="id" value={draft.id} /> <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 editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if}
{#if taken} {#if !draft.id}
<div class="alert alert-warning mb-2 text-sm"> <SegmentedControl
{[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. label="Kind"
</div> 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}
<label class="fieldset"> {#if draft.kind === 'window'}
<span class="fieldset-legend">Service</span> {#if taken}
<select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}> <div class="alert alert-warning mb-2 text-sm">
<option value="" disabled>Select a service…</option> {[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.
{#each items as item (item.id)} </div>
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option> {/if}
{/each}
</select>
</label>
<label class="fieldset"> <div class="grid gap-x-4 md:grid-cols-3">
<span class="fieldset-legend">Start ({data.timezone})</span> <label class="fieldset">
<input class="input w-full" type="datetime-local" name="start" required disabled={taken > 0} bind:value={draft.start} /> <span class="fieldset-legend">Date</span>
{#if endLabel}<span class="label">{endLabel}</span>{/if} <input class="input w-full" type="date" name="date" required bind:value={draft.date} />
</label> </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>
<label class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Places</span> <span class="fieldset-legend">Services that can be booked in this window</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} /> <div class="grid gap-1 sm:grid-cols-2">
<span class="label">More than 1 for a group session.{draft.id ? '' : ' Empty = the service’s own.'}</span> {#each items as item (item.id)}
</label> <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)}>
<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}
</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} />
{#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>
</label>
</div>
{/if}
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Notes</span> <span class="fieldset-legend">Notes</span>
@ -351,7 +521,7 @@
{/if} {/if}
<div class="flex gap-2"> <div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> <button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save slot</button> <button class="btn btn-primary" type="submit">Save</button>
</div> </div>
</div> </div>
</form> </form>

View file

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

View file

@ -1,5 +1,5 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord, SlotRecord } from '$lib/types'; import type { ItemRecord } from '$lib/types';
import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; import { BASKET_COOKIE, getBasket } from '$lib/server/shop';
import { loadShopData } from '$shared/server/shop'; import { loadShopData } from '$shared/server/shop';
import { DEFAULT_TIMEZONE, shopCurrency } from '$shared/calendar'; 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 }) => { export const load: LayoutServerLoad = async ({ locals, cookies, url }) => {
// Reading the path makes this load run again on every navigation, so the // Reading the path makes this load run again on every navigation, so the
// slots and basket are fresh on each page — places free up or get taken // basket is fresh on each page (holds lapse while the visitor browses).
// (holds lapse, other customers book) while the visitor browses. // Shop blocks fetch bookable times themselves (GET /api/slots).
void url.pathname; void url.pathname;
const [header, footer, colors] = await Promise.all([ 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; if (!header.homePage) header.homePage = defaultHeader.homePage;
// Commerce data for the public site. The listing is public data (API // Commerce data for the public site. The listing is public data (API
// rules allow active items / available slots); the basket comes from the // rules allow active items); the basket comes from the shop API in
// shop API in PocketBase. Failures leave the shop empty, never break a page. // PocketBase. Failures leave the shop empty, never break a page.
const [shop, basket] = await Promise.all([ const [shop, basket] = await Promise.all([
loadShopData(locals.pb).catch((e) => { loadShopData(locals.pb).catch((e) => {
console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : 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) getBasket(cookies.get(BASKET_COOKIE)).catch(() => null)
]); ]);
const items: ItemRecord[] = shop?.items ?? []; const items: ItemRecord[] = shop?.items ?? [];
const slots: SlotRecord[] = shop?.slots ?? [];
// Booking times are shown in the studio's timezone, wherever the visitor is. // Booking times are shown in the studio's timezone, wherever the visitor is.
const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE; const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE;
// Prices are shown in the currency Stripe charges in. // Prices are shown in the currency Stripe charges in.
const currency = shopCurrency(env.STRIPE_CURRENCY); const currency = shopCurrency(env.STRIPE_CURRENCY);
return { header, footer, colors, user: locals.user, basket, items, slots, timezone, currency }; return { header, footer, colors, user: locals.user, basket, items, timezone, currency };
}; };

View file

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

View file

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

View file

@ -21,6 +21,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
action: body.action, action: body.action,
itemId: body.itemId, itemId: body.itemId,
slotId: body.slotId, slotId: body.slotId,
minutes: body.minutes,
start: body.start,
seats: body.seats,
lineId: body.lineId, lineId: body.lineId,
quantity: body.quantity, quantity: body.quantity,
basketId: cookies.get(BASKET_COOKIE) || '' basketId: cookies.get(BASKET_COOKIE) || ''

View file

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

View file

@ -72,8 +72,12 @@ export function createBasketStore(initial: Basket | null) {
applyBasket(await callApi({ action: 'add_item', itemId, quantity })); applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
} }
async function addSlotLine(slotId: string) { /**
await applySlotChange(await callApi({ action: 'add_slot', slotId })); * Book a time: in a window, `slotId` plus the service, length and start
* picked; for a group session, `slotId` alone (one place).
*/
async function addSlotLine(slotId: string, booking: { itemId: string; minutes: number; start: string } | null = null) {
await applySlotChange(await callApi({ action: 'add_slot', slotId, ...booking }));
} }
async function updateQuantity(lineId: string, quantity: number) { async function updateQuantity(lineId: string, quantity: number) {

View file

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

View file

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

View file

@ -1,14 +1,14 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types'; import type { BasketLine, BookableTime, ShopBlockData, ItemRecord } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar';
import { formatDateKey } from '$shared/slots'; import { formatDuration, lowestPrice } from '$shared/items';
import { addDaysToKey, formatDateKey } from '$shared/slots';
let { data = {}, items = [], slots = [] } = $props<{ let { data = {}, items = [] } = $props<{
data: ShopBlockData; data: ShopBlockData;
items?: ItemRecord[]; items?: ItemRecord[];
slots?: SlotRecord[];
}>(); }>();
const basket = getBasketContext(); const basket = getBasketContext();
@ -16,20 +16,33 @@
// Per-card interaction state. Instances are created per component instance // Per-card interaction state. Instances are created per component instance
// (never shared at module level); keyed by item id so each card is independent. // (never shared at module level); keyed by item id so each card is independent.
class CardState { class CardState {
/** Index into the service's durations (the slider). */
durationIndex = $state(0);
pickerOpen = $state(false); pickerOpen = $state(false);
selectedDayKey = $state<string | null>(null); selectedDayKey = $state<string | null>(null);
adding = $state(false); adding = $state(false);
errorMsg = $state<string | null>(null); errorMsg = $state<string | null>(null);
justAdded = $state(false); justAdded = $state(false);
pendingSlotId = $state<string | null>(null); /** `slot|start` of the time being added or changed. */
pendingKey = $state<string | null>(null);
/** Months from the current one to the first month shown in the picker. */ /** Months from the current one to the first month shown in the picker. */
monthOffset = $state(0); 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>>({}); let cardStates = $state<Record<string, CardState>>({});
/** The picker shows this many months side by side; the arrows move one month. */ /** The picker shows this many months side by side; the arrows move one month. */
const MONTHS_SHOWN = 2; 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 weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE); const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY); const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
@ -48,42 +61,16 @@
return result; return result;
}); });
// The listing leaves out full slots — including ones whose last places are
// in this visitor's own basket. Add those back (no places left) so the
// visitor still sees their times and can change or drop their places.
let shownSlots = $derived.by<SlotRecord[]>(() => {
const listed = new Set(slots.map((s: SlotRecord) => s.id));
const own = basket.lines
.filter((l) => l.lineType === 'slot' && l.slot && !listed.has(l.slot) && l.slotStart && Date.parse(l.slotStart) > Date.now())
.map((l) => ({ id: l.slot!, item: l.item, start: l.slotStart!, end: l.slotEnd ?? l.slotStart!, capacity: l.slotCapacity ?? 1, free: 0 }));
return own.length ? [...slots, ...own] : slots;
});
// item id -> day key ('YYYY-MM-DD', in the studio's timezone) -> slots on that day, sorted by start time
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
const map = new Map<string, Map<string, SlotRecord[]>>();
for (const slot of 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'); let isList = $derived(data.layout === 'list');
/** 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(',')
);
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */ /** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
function monthOffsetOf(key: string) { function monthOffsetOf(key: string) {
const today = new Date(); const today = new Date();
@ -96,6 +83,19 @@
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1)); 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. // Lazily create card state for whatever items are rendered.
$effect(() => { $effect(() => {
for (const item of visibleItems) { for (const item of visibleItems) {
@ -103,6 +103,78 @@
} }
}); });
// 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) { function togglePicker(itemId: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state) return; if (!state) return;
@ -113,11 +185,21 @@
state.monthOffset = 0; state.monthOffset = 0;
} }
/** Show the month of the first available day and select it. */ function selectDuration(itemId: string, index: number) {
function showFirstAvailable(itemId: string, key: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state) return; if (!state || state.durationIndex === index) return;
state.monthOffset = Math.max(0, monthOffsetOf(key)); 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)));
state.selectedDayKey = key; state.selectedDayKey = key;
} }
@ -139,31 +221,32 @@
} }
} }
async function addSlot(itemId: string, slotId: string) { async function addTime(item: ItemRecord, minutes: number, time: BookableTime) {
const state = cardStates[itemId]; const state = cardStates[item.id];
if (!state || state.adding) return; if (!state || state.adding) return;
state.adding = true; state.adding = true;
state.pendingSlotId = slotId; state.pendingKey = `${time.slot}|${time.start}`;
state.errorMsg = null; state.errorMsg = null;
try { try {
// The store reloads the listing afterwards: a booking can block other // The picker reloads afterwards (basketBookingsKey changes): this
// times (one practitioner) or fill a group session. // booking takes its time, plus get-ready time, out of the day.
await basket.addSlotLine(slotId); await basket.addSlotLine(time.slot, time.kind === 'window' ? { itemId: item.id, minutes, start: time.start } : null);
state.justAdded = true; state.justAdded = true;
} catch (e) { } catch (e) {
state.errorMsg = errorMessage(e, 'Could not book this time slot.'); state.errorMsg = errorMessage(e, 'Could not book this time.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingSlotId = null; state.pendingKey = null;
} }
} }
/** One place more or fewer in a group session already in the basket (0 removes it). */ /** One place more or fewer in a group session already in the basket (0 removes it). */
async function changeSeats(itemId: string, line: BasketLine, delta: number) { async function changeSeats(itemId: string, entry: DayEntry, delta: number) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state || state.adding) return; const line = entry.line;
if (!state || !line || state.adding) return;
state.adding = true; state.adding = true;
state.pendingSlotId = line.slot; state.pendingKey = `${entry.slot}|${entry.start}`;
state.errorMsg = null; state.errorMsg = null;
try { try {
const seats = line.quantity + delta; const seats = line.quantity + delta;
@ -173,7 +256,7 @@
state.errorMsg = errorMessage(e, 'Could not change the number of places.'); state.errorMsg = errorMessage(e, 'Could not change the number of places.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingSlotId = null; state.pendingKey = null;
} }
} }
@ -184,6 +267,8 @@
function placesLeft(free: number) { function placesLeft(free: number) {
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left'; 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> </script>
<section class="mx-auto max-w-6xl px-6 py-16"> <section class="mx-auto max-w-6xl px-6 py-16">
@ -202,13 +287,14 @@
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}> <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)} {#each visibleItems as item (item.id)}
{@const ui = cardStates[item.id]} {@const ui = cardStates[item.id]}
{@const itemSlotsByDay = slotsByDay.get(item.id)}
{@const isService = item.type === 'item_with_time'} {@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 soldOut = !isService && item.stock === 0}
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)} {@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
<article <article
class={isList class={isList
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6' ? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:flex-wrap sm:gap-6'
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'} : 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
> >
{#if item.imageUrl} {#if item.imageUrl}
@ -234,18 +320,28 @@
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p> <p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
{/if} {/if}
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3"> <div class="mt-auto pt-3">
<span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price, currency)}</span> {#if isService && item.durations.length > 1}
{#if isService && item.duration != null} <!-- Several lengths: the length is picked (slider) after pressing Book. -->
<span class="text-xs text-charcoal/60">{item.duration} min</span> <div class="flex flex-wrap items-center gap-x-3 gap-y-1">
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5} <span class="text-lg font-semibold text-sage-dark">from {formatPrice(lowestPrice(item.durations) ?? item.price, currency)}</span>
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta"> <span class="text-xs text-charcoal/60">{formatDuration(item.durations[0].minutes)} – {formatDuration(item.durations[item.durations.length - 1].minutes)}</span>
Only {item.stock} left </div>
</span> {:else}
{:else if soldOut} <div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta"> <span class="text-lg font-semibold text-sage-dark">{formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)}</span>
Sold out {#if duration}
</span> <span class="text-xs text-charcoal/60">{formatDuration(duration.minutes)}</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
</span>
{:else if soldOut}
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Sold out
</span>
{/if}
</div>
{/if} {/if}
</div> </div>
@ -272,13 +368,14 @@
type="button" 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 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' ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
: itemSlotsByDay?.size : bookable
? 'bg-sage text-primary-content hover:bg-sage-dark' ? 'bg-sage text-primary-content hover:bg-sage-dark'
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}" : 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen} disabled={!bookable && !ui?.pickerOpen}
aria-expanded={!!ui?.pickerOpen}
onclick={() => togglePicker(item.id)} onclick={() => togglePicker(item.id)}
> >
{itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} {bookable ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
</button> </button>
{:else} {:else}
<button <button
@ -301,14 +398,42 @@
</div> </div>
</div> </div>
{#if isService && ui?.pickerOpen && itemSlotsByDay} {#if isService && ui?.pickerOpen && duration}
{@const availableKeys = [...itemSlotsByDay.keys()].sort()} {@const byDay = entriesByDay(item, ui, duration.minutes)}
{@const availableKeys = [...byDay.keys()].sort()}
{@const months = pickerMonths(ui.monthOffset)} {@const months = pickerMonths(ui.monthOffset)}
{@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey} {@const shown = shownRange(ui.monthOffset)}
{@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey} {@const anyShown = availableKeys.some((key) => key >= shown.from && key <= shown.to)}
{@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'}> <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"> <div class="mb-3 flex items-center justify-between gap-2">
<button <button
type="button" type="button"
@ -319,33 +444,39 @@
> >
‹ ‹
</button> </button>
<p class="text-sm font-medium text-charcoal/70">Select a date</p> <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>
<button <button
type="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" 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" aria-label="Next month"
disabled={ui.monthOffset >= lastOffset} disabled={ui.monthOffset >= MAX_MONTH_OFFSET}
onclick={() => ui.monthOffset++} onclick={() => ui.monthOffset++}
> >
› ›
</button> </button>
</div> </div>
{#if !anyShown && availableKeys.length} {#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}
<!-- Nothing in the months on screen: say when the next date is, so <!-- Nothing in the months on screen: say when the next date is, so
nobody books January thinking it is this month. --> 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"> <div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal">
<span> {#if ui.next}
{availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'} <span>The next available date for {formatDuration(duration.minutes)} is <strong>{longDate(zonedDateKey(ui.next, timezone))}</strong>.</span>
<strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>. <button
</span> type="button"
<button class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark"
type="button" onclick={() => showDay(item.id, ui.next!)}
class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark" >
onclick={() => showFirstAvailable(item.id, availableKeys.find((key) => key > shownTo) ?? availableKeys[0])} Go to next available date →
> </button>
Go to {availableKeys[0] > shownTo ? 'first' : 'next'} available date → {:else}
</button> <span>No times are available for {formatDuration(duration.minutes)} in these months{item.durations.length > 1 ? ' — try another length' : ''}.</span>
{/if}
</div> </div>
{/if} {/if}
@ -358,7 +489,7 @@
<span class="py-1 text-xs text-charcoal/40">{letter}</span> <span class="py-1 text-xs text-charcoal/40">{letter}</span>
{/each} {/each}
{#each month.days as day (day.dateKey)} {#each month.days as day (day.dateKey)}
{@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)} {@const selectable = day.inMonth && byDay.has(day.dateKey)}
{@const selected = selectable && ui.selectedDayKey === day.dateKey} {@const selected = selectable && ui.selectedDayKey === day.dateKey}
<button <button
type="button" type="button"
@ -382,40 +513,40 @@
{/each} {/each}
</div> </div>
{#if ui.selectedDayKey} {#if ui.selectedDayKey && byDay.has(ui.selectedDayKey)}
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70"> <p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">
Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })} Available times · {longDate(ui.selectedDayKey)}
</p> </p>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
{#each daySlots as slot (slot.id)} {#each byDay.get(ui.selectedDayKey) ?? [] as entry (`${entry.slot}|${entry.start}`)}
{@const line = basket.lines.find((l) => l.slot === slot.id)} {@const isGroup = (entry.time?.capacity ?? entry.line?.slotCapacity ?? 1) > 1}
{@const isGroup = slot.capacity > 1} {@const free = entry.time?.free ?? 0}
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`} {@const pending = ui.pendingKey === `${entry.slot}|${entry.start}`}
{#if isGroup && line} {@const label = `${formatTime(entry.start)}–${formatTime(entry.end)}`}
{#if isGroup && entry.line}
<!-- Places in a group session already in the basket: − / + --> <!-- 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"> <div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark">
<span>{label} · {placesLeft(slot.free)}</span> <span>{label} · {placesLeft(free)}</span>
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5"> <span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
<button <button
type="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" 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" aria-label="One place fewer"
disabled={ui.adding} disabled={ui.adding}
onclick={() => changeSeats(item.id, line, -1)} onclick={() => changeSeats(item.id, entry, -1)}
> >
− −
</button> </button>
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite"> <span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
{#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if} {#if pending}<span class="loading loading-spinner loading-xs"></span>{:else}{entry.line.quantity}{/if}
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span> <span class="sr-only">{entry.line.quantity === 1 ? 'place' : 'places'} in your basket</span>
</span> </span>
<button <button
type="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" 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" aria-label="One place more"
disabled={ui.adding || slot.free <= 0} disabled={ui.adding || free <= 0}
onclick={() => changeSeats(item.id, line, 1)} onclick={() => changeSeats(item.id, entry, 1)}
> >
+ +
</button> </button>
@ -424,27 +555,25 @@
{:else} {:else}
<button <button
type="button" type="button"
disabled={!!line || ui.adding} disabled={!!entry.line || !entry.time || ui.adding}
onclick={() => addSlot(item.id, slot.id)} 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 {line class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {entry.line
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark' ? '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 && : 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
!line !entry.line
? 'cursor-wait' ? 'cursor-wait'
: ''}" : ''}"
> >
{#if ui.pendingSlotId === slot.id} {#if pending}
<span class="loading loading-spinner loading-xs"></span> <span class="loading loading-spinner loading-xs"></span>
{/if} {/if}
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''} {label}{isGroup ? ` · ${placesLeft(free)}` : ''}{entry.line ? ' · In basket' : ''}
</button> </button>
{/if} {/if}
{/each} {/each}
</div> </div>
{:else if anyShown} {:else if anyShown}
<p class="mt-4 text-sm text-charcoal/60"> <p class="mt-4 text-sm text-charcoal/60">Days with availability are highlighted.</p>
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
</p>
{/if} {/if}
{#if ui.justAdded} {#if ui.justAdded}

View file

@ -0,0 +1,29 @@
// Services and their durations — pure helpers shared by the admin editor,
// the Shop block and the checkout. Which duration costs what is decided
// (and charged) by the shop hooks in PocketBase; this only reads and shows it.
import type { ItemDuration } from './types';
/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
export function parseDurations(raw: unknown): ItemDuration[] {
const list = Array.isArray(raw) ? raw : [];
const seen = new Set<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,14 +148,12 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || ''))); const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || '')));
const lines: EmailLine[] = lineRecords.map((line) => { 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 start = line.start ? new Date(line.start).toISOString() : null;
const minutes = Number(line.minutes) || 0;
const slotEnd = line.expand?.slot?.end; const slotEnd = line.expand?.slot?.end;
const duration = Number(line.expand?.item?.duration) || 0; const end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null;
const end = slotEnd
? new Date(slotEnd).toISOString()
: start && duration
? new Date(new Date(start).getTime() + duration * 60_000).toISOString()
: null;
return { return {
name: String(line.name || 'Item'), name: String(line.name || 'Item'),
price: Number(line.price) || 0, price: Number(line.price) || 0,

View file

@ -1,39 +1,63 @@
import type PocketBase from 'pocketbase'; import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb'; import { getFileUrl } from '../pb';
import type { ItemRecord, SlotRecord } from '../types'; import { parseDurations } from '../items';
import type { BookableTime, ItemRecord } from '../types';
/** An `items` record (with `expand.image`) → `ItemRecord`. */
export function mapItemRecord(record: Record<string, any>): ItemRecord {
const media = record.expand?.image;
const type = record.type === 'item_with_time' ? 'item_with_time' : 'item';
return {
id: record.id,
name: String(record.name || ''),
description: String(record.description || ''),
price: Number(record.price) || 0,
image: String(record.image || ''),
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type,
stock: record.stock ?? null,
durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
};
}
/** /**
* Active items and bookable future slots, shaped for the Shop/Checkout * Active items, shaped for the Shop/Checkout blocks. Used by the public
* blocks. Used by the public layout and the admin draft preview so both * layout and the admin draft preview so both render the same shop. Works
* render the same shop. * with an anonymous client (active items and media are public). Bookable
* * times are fetched by the Shop block itself, per service and duration
* Works with an anonymous client: active items and media are public, and * (see `loadBookableTimes`). Errors propagate.
* 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[] }> { export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
const [itemRecords, { slots }] = await Promise.all([ const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }), return { items: records.map(mapItemRecord) };
pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null }) }
]);
export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string };
const items = itemRecords.map((record): ItemRecord => {
const media = record.expand?.image; /**
return { * Times a customer can book for one service and duration, from the shop
id: record.id, * hook (GET /api/shop/slots), which applies every availability rule. When
name: record.name, * none start in [from, to), `next` is the first one after (or null).
description: record.description || '', */
price: record.price, export function loadBookableTimes(pb: PocketBase, query: BookableTimesQuery) {
image: record.image || '', return pb.send<{ times: BookableTime[]; next: string | null }>('/api/shop/slots', { query, requestKey: null });
imageUrl: media ? getFileUrl('media', media.id, media.file) : '', }
type: record.type,
stock: record.stock ?? null, /**
duration: record.duration ?? null, * GET /api/slots in both apps (the Shop block's time picker): forwards
bufferMinutes: record.bufferMinutes ?? null, * ?item=&minutes=&from=&to= to the shop hook. A PocketBase error keeps its
capacity: record.capacity ?? null, * status and message; PocketBase being down is a 503.
active: record.active */
}; export async function bookableTimesResponse(pb: PocketBase, url: URL): Promise<Response> {
}); const param = (key: string) => url.searchParams.get(key) ?? '';
try {
return { items, slots }; 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 });
}
} }

View file

@ -6,6 +6,7 @@
// zonedInputToIso, so a run across a DST change still starts at 09:00. // zonedInputToIso, so a run across a DST change still starts at 09:00.
import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar'; 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. */ /** 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 }; export type TimeWindow = { from: string; to: string };
@ -43,22 +44,64 @@ export type BulkResult = {
}; };
/** /**
* A slot with its places and blocking, as the shop hook reports it to the * A booked or held time, as the shop hook reports it to the admin: paid
* admin (GET /api/shop/slots?detail=1). Places are taken by paid orders * order lines (`booked`) and basket lines whose hold hasn't lapsed
* (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy` * (`held`). The practitioner is busy until `readyAt` (end + get-ready time).
* is the overlapping slot whose booking/hold blocks this one. */
export type SlotBooking = PlannedSlot & {
slot: string;
item: string;
itemName: string;
readyAt: string;
quantity: number;
status: 'booked' | 'held';
};
/**
* A slot with what's booked in it (GET /api/shop/slots?detail=1). A window
* counts its bookings in `booked`/`held` and lists its `free` stretches; a
* group session has places and may be blocked by an overlapping booking.
*/ */
export type SlotDetail = PlannedSlot & { export type SlotDetail = PlannedSlot & {
id: string; id: string;
item: string; kind: SlotKind;
itemName: string; items: string[];
capacity: number; itemNames: string[];
notes: string; notes: string;
booked: number; booked: number;
held: number; held: number;
blockedBy: string; // window
startTimes?: StartTimesMode;
/** `grid` windows: minutes between start times. */
gridMinutes?: number;
free?: PlannedSlot[];
// session
minutes?: number;
capacity?: number;
blockedBy?: SlotBooking | null;
}; };
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 type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
export const SLOT_STATE_LABELS: Record<SlotState, string> = { export const SLOT_STATE_LABELS: Record<SlotState, string> = {
@ -70,12 +113,18 @@ export const SLOT_STATE_LABELS: Record<SlotState, string> = {
}; };
/** /**
* `full` only when paid bookings fill a group; a slot whose last places are * A window is `full` once no free time is left. A session is `full` only
* in baskets reads `held`, since it frees up again if those holds lapse. * when paid bookings fill a group; one whose last places are in baskets
* reads `held`, since it frees up again if those holds lapse.
*/ */
export function slotState(slot: Pick<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): SlotState { export function slotState(slot: Pick<SlotDetail, 'kind' | 'booked' | 'held' | 'capacity' | 'blockedBy' | 'free'>): SlotState {
if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked'; if (slot.kind === 'window') {
if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held'; if ((slot.booked || slot.held) && !slot.free?.length) return slot.booked ? 'full' : 'held';
return slot.booked ? 'booked' : slot.held ? 'held' : 'free';
}
const capacity = slot.capacity ?? 1;
if (slot.booked >= capacity) return capacity > 1 ? 'full' : 'booked';
if (slot.held && slot.booked + slot.held >= capacity) return 'held';
if (slot.booked) return 'booked'; if (slot.booked) return 'booked';
if (slot.held) return 'held'; if (slot.held) return 'held';
return slot.blockedBy ? 'blocked' : 'free'; return slot.blockedBy ? 'blocked' : 'free';
@ -191,7 +240,22 @@ export type GeneratePlanInput = {
timeZone: string; timeZone: string;
}; };
/** Every slot the generator would create, before skipping overlaps/past ones. */ /** Each chosen day's opening hours as windows (dates in `timeZone`), before skipping overlaps/past ones. */
export function planWindows(input: Omit<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. */
export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] { export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] {
const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes); const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes);
const days = new Set(input.weekdays); const days = new Set(input.weekdays);

View file

@ -119,31 +119,42 @@ export const defaultPrivacy: PrivacyGlobal = {
export type ItemType = 'item' | 'item_with_time'; 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 = { export type ItemRecord = {
id: string; id: string;
name: string; name: string;
description: string; description: string;
/** A product's price; for a service, its lowest duration price (kept in sync by the admin). */
price: number; price: number;
image: string; // media record id image: string; // media record id
imageUrl: string; // resolved URL (populated by server load) imageUrl: string; // resolved URL (populated by server load)
type: ItemType; type: ItemType;
stock: number | null; stock: number | null;
duration: number | null; // minutes, for item_with_time durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots bufferMinutes: number | null; // get-ready time after each appointment
capacity: number | null; // places per slot (default for new slots; >1 = group session) capacity: number | null; // places in a new group session (>1 = group)
active: boolean; active: boolean;
}; };
/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */
export type SlotKind = 'window' | 'session';
/** Where bookings may start in a window: every 30 minutes, or only at the start/end of the free time. */
export type StartTimesMode = 'grid' | 'edges';
/** /**
* A bookable slot as the shop lists it (GET /api/shop/slots): only slots * A time a customer can book, as the shop lists it (GET /api/shop/slots for
* with places left that no overlapping booking blocks. * one service and duration): a start time in a window, or a group session
* with places left.
*/ */
export type SlotRecord = { export type BookableTime = {
id: string; slot: string; // slot id (window or session)
item: string; // item id kind: SlotKind;
start: string; start: string;
end: string; end: string;
capacity: number; // places in total capacity: number; // places in total (1 in a window)
free: number; // places still bookable free: number; // places still bookable
}; };
@ -156,12 +167,16 @@ export type BasketLine = {
slot: string | null; slot: string | null;
quantity: number; quantity: number;
lineType: 'item' | 'slot'; lineType: 'item' | 'slot';
/** Slot lines: the booked time and length. */
start?: string;
end?: string;
minutes?: number;
// Expanded fields (populated server-side) // Expanded fields (populated server-side)
itemName?: string; itemName?: string;
itemPrice?: number; /** Price of one unit (a product, or the service at this length); null if no longer offered. */
itemPrice?: number | null;
itemImageUrl?: string; itemImageUrl?: string;
slotStart?: string; slotKind?: SlotKind;
slotEnd?: string;
slotCapacity?: number; slotCapacity?: number;
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */ /** Slot lines: when the reservation lapses and the line is dropped (ISO). */
heldUntil?: string; heldUntil?: string;
@ -211,6 +226,8 @@ export type OrderLine = {
name: string; name: string;
price: number; price: number;
start: string | null; start: string | null;
/** Slot lines: the booked length. */
minutes: number | null;
}; };
// ── Block data types ────────────────────────────────────────────────── // ── Block data types ──────────────────────────────────────────────────

File diff suppressed because it is too large Load diff

View file

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

View file

@ -62,150 +62,350 @@ function pbDate(ms) {
const DAY_MS = 24 * 60 * 60 * 1000; 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 ─────────────────────────────────────────────────── // ── Slot availability ───────────────────────────────────────────────────
// //
// Nothing about bookings is stored on a slot. Its seats are taken by paid // Nothing about bookings is stored on a slot. Bookings are paid order lines
// order lines and by basket lines whose hold (`heldUntil`) hasn't lapsed; // and basket lines whose hold (`heldUntil`) hasn't lapsed; each has its own
// it has `capacity` seats (1 for a one-to-one massage, more for a group). // `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.
// //
// One practitioner works all services, so a slot with any seat taken // A slot is either
// BLOCKS every other slot it overlaps — whatever the service — including // - a `window` (09:00–12:00 with the services that can be booked in it):
// each service's get-ready time after it. The client can offer three // a booking may start wherever its length plus get-ready time is free.
// massages at 10:00; once one is booked (or in a basket), the others go. // `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.
/** /**
* Occupancy and blocking for the slots starting in [rangeStart, rangeEnd) (epoch ms). * Bookings starting in [rangeStart - 1 day, rangeEnd + 1 day), sorted by
* `options.excludeLineId` leaves one basket line's seats out (used when * start: `{ lineId, slot, item, itemName, start, end, readyAt, quantity,
* changing that line's quantity). Must run inside a transaction when the * status: 'booked' | 'held' }`. `options.excludeLineId` leaves one basket
* result decides a write: PocketBase runs transactions one at a time, so * line out (when re-checking that line itself).
* the check and the write can't interleave with another customer's.
*/ */
function slotStates(app, rangeStart, rangeEnd, options) { function busyTimes(app, rangeStart, rangeEnd, item, options) {
const opts = 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 range = { from: pbDate(rangeStart - DAY_MS), to: pbDate(rangeEnd + DAY_MS) };
const records = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start'); const busy = [];
if (!records.length) return []; const add = (line, status) => {
const start = toMs(line.getString('start'));
const items = {}; if (Number.isNaN(start)) return;
const byId = {}; const service = item(line.getString('item'));
const states = records.map((record) => { const end = start + line.getInt('minutes') * MINUTE_MS;
const itemId = record.getString('item'); busy.push({
if (!(itemId in items)) items[itemId] = findOrNull(app, 'items', itemId); lineId: line.id,
const item = items[itemId]; slot: line.getString('slot'),
const start = toMs(record.getString('start')); item: line.getString('item'),
const storedEnd = toMs(record.getString('end')); itemName: service ? service.getString('name') : '',
const end = Number.isNaN(storedEnd) ? start + (item ? item.getInt('duration') : 0) * 60000 : storedEnd;
const state = {
id: record.id,
item: itemId,
itemName: item ? item.getString('name') : '',
bookable: !!item && item.getBool('active') && item.getString('type') === 'item_with_time',
start, start,
end, end,
readyAt: end + Math.max(0, item ? item.getInt('bufferMinutes') : 0) * 60000, readyAt: end + bufferMs(service),
capacity: Math.max(1, record.getInt('capacity')), quantity: line.getInt('quantity'),
notes: record.getString('notes'), status
booked: 0, });
held: 0, };
blockedBy: '' const inRange = 'start >= {:from} && start < {:to}';
}; for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + inRange, range)) add(line, 'booked');
byId[record.id] = state; const held = Object.assign({ now: pbDate(Date.now()) }, range);
return state; for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + inRange, held)) {
}); if (line.id !== opts.excludeLineId) add(line, 'held');
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');
} }
const heldParams = Object.assign({ now: pbDate(Date.now()) }, range); return busy.sort((a, b) => a.start - b.start);
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);
} }
/** One slot's state (see slotStates), or null if it doesn't exist. */ function overlapsBusy(busy, start, until) {
function slotState(app, slotId, options) { return busy.find((b) => b.start < until && start < b.readyAt) || null;
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;
}
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();
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)
}));
} }
/** /**
* Every slot in a range (or one slot by id) with its seats and blocking — * Slots starting in [rangeStart, rangeEnd) (epoch ms) with what's booked
* for the signed-in admin. `query`: from/to (ISO), optional item, or id. * 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 start = toMs(record.getString('start'));
const end = toMs(record.getString('end'));
const slot = {
id: record.id,
kind: record.getString('kind') === 'session' ? 'session' : 'window',
items,
itemNames: items.map((id) => (item(id) ? item(id).getString('name') : '')),
start,
end,
notes: record.getString('notes')
};
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;
});
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);
}
if (cursor < window.end) free.push({ start: cursor, end: window.end });
return free;
}
/** 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);
}
/**
* 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) {
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);
}
/**
* 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.
*/ */
function slotDetails(app, query) { function slotDetails(app, query) {
let states; let slots;
let busy;
let from;
let to;
if (query.id) { if (query.id) {
const state = slotState(app, String(query.id)); const record = findOrNull(app, 'slots', String(query.id));
states = state ? [state] : []; if (!record) return { slots: [], bookings: [] };
from = toMs(record.getString('start'));
to = from + 1;
({ slots, busy } = availability(app, from, to));
} else { } else {
const from = toMs(query.from); from = toMs(query.from);
const to = toMs(query.to); to = toMs(query.to);
if (Number.isNaN(from) || Number.isNaN(to) || to <= from) throw new BadRequestError('from and to are required'); 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'); if (to - from > 400 * DAY_MS) throw new BadRequestError('Range too long');
states = slotStates(app, from, to); ({ slots, busy } = availability(app, from, to));
if (query.item) states = states.filter((s) => s.item === query.item); if (query.item) slots = slots.filter((s) => s.items.indexOf(String(query.item)) >= 0);
} }
return states.map((s) => ({ const iso = (ms) => new Date(ms).toISOString();
id: s.id, 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 });
item: s.item, return {
itemName: s.itemName, slots: slots.map((s) => {
start: new Date(s.start).toISOString(), 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 };
end: new Date(s.end).toISOString(), if (s.kind === 'window') {
capacity: s.capacity, detail.startTimes = s.startTimes;
notes: s.notes, detail.gridMinutes = s.gridMinutes;
booked: s.booked, detail.free = freeTimes(s, busy).map((f) => ({ start: iso(f.start), end: iso(f.end) }));
held: s.held, } else {
blockedBy: s.blockedBy 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)
};
} }
/** /** Check a session can take `seats` more places; returns an ApiError to throw, or null. */
* Check a slot can take `seats` more seats; returns an ApiError to throw, function seatProblem(session, seats) {
* or null. Call inside the transaction that then writes the hold. 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');
function seatProblem(state, seats) { if (session.blockedBy) return conflict('This time is no longer available — please pick another');
if (!state || !state.bookable) return new NotFoundError('Slot not found'); const free = freeSeats(session);
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) { 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 conflict(free <= 0 ? 'This time is fully booked — please pick another' : `Only ${free} place${free === 1 ? '' : 's'} left at this time`);
} }
return null; 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 * Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing
* is written) or nothing to commit. Unexpected failures become `fallback`. * is written) or nothing to commit. Unexpected failures become `fallback`.
@ -259,12 +459,26 @@ function basketLines(app, basketId) {
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: 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. */ /**
* 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`.
*/
function basketPayload(app, basket) { function basketPayload(app, basket) {
if (!basket) return null; if (!basket) return null;
const lines = basketLines(app, basket.id); const lines = basketLines(app, basket.id);
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null); for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
return { record: plain(basket), lines: lines.map(plain) }; 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;
})
};
} }
function createBasket(app) { function createBasket(app) {
@ -277,10 +491,10 @@ function createBasket(app) {
* Renew the hold on every slot line in a basket. Used at checkout start * 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 * (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 * when the customer asks for more time (`renew_holds`, 10 min). A live hold
* is extended, never shortened (its seats are already counted). A lapsed * is extended, never shortened (it's already counted). A lapsed one that
* one that hasn't been swept yet is rescued only if its seats are still * hasn't been swept yet is rescued only if its time could still be booked
* free and nothing has blocked the time since — otherwise it's left for * now — otherwise it's left for the sweep, and checkout tells the customer
* the sweep, and checkout tells the customer the slot expired. * the time expired.
*/ */
function extendBasketHolds(app, basketId, durationMs) { function extendBasketHolds(app, basketId, durationMs) {
const now = Date.now(); const now = Date.now();
@ -297,7 +511,7 @@ function extendBasketHolds(app, basketId, durationMs) {
try { try {
app.runInTransaction((tx) => { app.runInTransaction((tx) => {
const fresh = tx.findRecordById('basket_lines', line.id); const fresh = tx.findRecordById('basket_lines', line.id);
if (seatProblem(slotState(tx, fresh.getString('slot')), fresh.getInt('quantity'))) return; if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return;
fresh.set('heldUntil', until); fresh.set('heldUntil', until);
tx.save(fresh); tx.save(fresh);
}); });
@ -343,15 +557,35 @@ function basketAction(app, body) {
} }
case 'add_slot': { case 'add_slot': {
// Adding a slot that's already in the basket adds seats to that line. // A window booking: `slotId` (the window), `itemId`, `minutes` and
const slotId = String(body.slotId || ''); // `start` (one of the listed times). A group session: `slotId` and
const seats = Math.max(1, Math.floor(Number(body.seats)) || 1); // `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)
};
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => { guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
const problem = seatProblem(slotState(tx, slotId), seats); const check = checkBooking(tx, request);
if (problem) return problem; if (check.error) return check.error;
const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0]; const booking = check.booking;
const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' }); const existing =
line.set('quantity', line.getInt('quantity') + seats); 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));
line.set('heldUntil', isoIn(SLOT_HOLD_MS)); line.set('heldUntil', isoIn(SLOT_HOLD_MS));
tx.save(line); tx.save(line);
}); });
@ -364,11 +598,13 @@ function basketAction(app, body) {
const quantity = Number(body.quantity); const quantity = Number(body.quantity);
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer'); if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
if (line.getString('lineType') === 'slot') { if (line.getString('lineType') === 'slot') {
// Seats for a group session: re-check capacity without this line's current seats. // Places in a group session: re-check capacity without this line's current places.
guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => { guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => {
const fresh = tx.findRecordById('basket_lines', line.id); const fresh = tx.findRecordById('basket_lines', line.id);
const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity); const slot = findOrNull(tx, 'slots', fresh.getString('slot'));
if (problem) return problem; 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;
fresh.set('quantity', quantity); fresh.set('quantity', quantity);
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS)); fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
tx.save(fresh); tx.save(fresh);
@ -489,7 +725,9 @@ function startCheckout(app, body) {
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`); throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
} }
} }
totalCents += Math.round(item.getFloat('price') * 100) * quantity; 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;
summary.push(`${quantity}× ${item.getString('name')}`); summary.push(`${quantity}× ${item.getString('name')}`);
} }
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive'); if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
@ -602,12 +840,11 @@ function createOrderFromIntent(app, intent) {
}); });
tx.save(order); tx.save(order);
// Snapshot lines and decrement stock. A slot's seats move from the // Snapshot lines and decrement stock. A booked time moves from the
// basket line (a hold) to the order line (a booking) in this same // basket line (a hold) to the order line (a booking) in this same
// transaction, so availability never sees them free in between. // transaction, so availability never sees it free in between.
for (const line of lines) { for (const line of lines) {
const item = findOrNull(tx, 'items', line.getString('item')); const item = findOrNull(tx, 'items', line.getString('item'));
const slot = findOrNull(tx, 'slots', line.getString('slot'));
tx.save( tx.save(
newRecord(tx, 'order_lines', { newRecord(tx, 'order_lines', {
order: order.id, order: order.id,
@ -616,8 +853,9 @@ function createOrderFromIntent(app, intent) {
quantity: line.getInt('quantity'), quantity: line.getInt('quantity'),
lineType: line.getString('lineType'), lineType: line.getString('lineType'),
name: item ? item.getString('name') : 'Unknown item', name: item ? item.getString('name') : 'Unknown item',
price: item ? item.getFloat('price') : 0, price: (item && unitPrice(item, line.getInt('minutes'))) || 0,
start: slot ? slot.getString('start') : '' start: line.getString('start'),
minutes: line.getInt('minutes')
}) })
); );
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') { if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
@ -715,7 +953,7 @@ function recordEmailStatus(app, secretHeader, body) {
} }
module.exports = { module.exports = {
bookableSlots, bookableTimes,
slotDetails, slotDetails,
sweepExpiredHolds, sweepExpiredHolds,
loadActiveBasket, loadActiveBasket,

View file

@ -0,0 +1,166 @@
/// <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);
}
}
);