diff --git a/AGENTS.md b/AGENTS.md index d9281ce..12a2b43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb, app-admin/ # SvelteKit admin app (serves admin.) ├── src/ │ ├── lib/ -│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers) +│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers, slots/ bulk modals) │ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) │ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia │ │ ├── types.ts # Re-exports from $shared @@ -22,14 +22,14 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared -│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts) +│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts) │ ├── routes/ │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) │ │ ├── login/ # Admin login │ │ ├── pages/ # Page CRUD + block editor │ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── items/ # Service/product CRUD (menu label: Services & products) -│ │ ├── slots/ # Bookable time slot CRUD +│ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) @@ -118,6 +118,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type ### Shared Code - `packages/shared/src/types.ts` — all type definitions - `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) +- `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts` - Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` - Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work @@ -129,6 +130,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them). - **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. - **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. +- **Slot availability** (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*. - **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). ### Styling @@ -140,6 +142,7 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel). - Server actions wrap PocketBase writes in `attempt()` from `$lib/server/actions` so failures show as an error banner, not a 500. - Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`. +- **Dates, times and prices shown to people** use `DISPLAY_LOCALE` (`en-GB`: day-month-year, 24-hour clock) and the helpers in `$shared/calendar` (`formatInstant`, `formatPrice`, `formatDateTime`) — never `toLocale*(undefined)`, which renders US formats on the server. Booking times on the public site are shown in `SITE_TIMEZONE` too (layout data `timezone`, read by blocks via `page.data.timezone`). Native `` fields follow the visitor's browser language and can't be changed from the page. - **Dates/times in admin**: entered and displayed in `SITE_TIMEZONE` (layout data `timezone`), via `toZonedDatetimeInput`, `zonedInputToIso`, `formatDateTime` in `$shared/calendar`. Never `new Date(localInput)` on the server — the container runs in UTC. - **Prose**: `.prose-wellness` class for rich text content styling @@ -182,4 +185,4 @@ cd app-public && npm run build - `SITE_TIMEZONE` — IANA timezone for booking times in emails (default `Europe/Oslo`). - Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. - `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials. -- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`); 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`; slots via `GET /api/shop/slots`); if a Shop block has nothing to show it says "Nothing is available". diff --git a/README.md b/README.md index 60e87fe..19a75e0 100644 --- a/README.md +++ b/README.md @@ -112,15 +112,15 @@ If schema import fails because of a PocketBase version mismatch, create these co Commerce collections (see the Stripe section above for context): -- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `active` bool -- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text +- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new slots), `active` bool +- `slots` — `item` relation→items, `start` date, `end` date, `capacity` number (places; >1 = group session), `notes` text. Nothing about bookings is stored here — see *Slot availability* below - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text -- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot` +- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `heldUntil` date (a slot line's hold) - `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text - `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot) - `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool -> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Relation and select fields carry their config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`) at the field top level, not nested under `options`. 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. ## Authentication @@ -138,7 +138,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - `/pages/[slug]` — block editor with draft preview - `/calendar` — events shown by Upcoming Calendar blocks - `/items` — services and products shown in Shop blocks -- `/slots` — manually created bookable time slots for services +- `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions. - `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) - `/globals` — header/footer/colors editor @@ -147,7 +147,14 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client). -**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 releases 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): + +- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does. +- One practitioner works every service, so a slot with **any** place taken blocks every other slot that overlaps it — whatever the service — counting each service's get-ready time (`items.bufferMinutes`) after it. The client can offer three massages at 10:00; once one is in a basket or booked, the other two disappear. A group session with one place booked blocks massages at that time too, while staying bookable itself until full. +- `GET /api/shop/slots` lists the bookable future slots (public; feeds the Shop block). With `?detail=1` a signed-in admin gets every slot in a range with booked/held places and what blocks it (the `/slots` page). +- Adding to a basket (`add_slot`, with `seats`) and changing a group line's places re-check capacity and blocking inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. Setup: @@ -158,7 +165,7 @@ Setup: stripe listen --forward-to www.localhost:8080/api/webhooks/stripe ``` Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`. -4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). The `basket_lines.slot` partial unique index guarantees two visitors can't hold the same slot. +4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). Two visitors can't take the same place: holds are checked and written in one PocketBase transaction (see *Slot availability*). 5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it. ## Booking emails (Brevo) diff --git a/app-admin/src/lib/admin/slots/BulkActions.svelte b/app-admin/src/lib/admin/slots/BulkActions.svelte new file mode 100644 index 0000000..bc7aedb --- /dev/null +++ b/app-admin/src/lib/admin/slots/BulkActions.svelte @@ -0,0 +1,54 @@ + + +{#if bulk.error}{/if} + +{#if preview} +
+ {#if preview.count} +

+ {plural(preview.count, 'slot')} will be {deleting ? 'deleted' : 'created'}{preview.count > 1 + ? `, from ${formatDateTime(preview.firstStart, timezone)} to ${formatDateTime(preview.lastStart, timezone)}` + : `, at ${formatDateTime(preview.firstStart, timezone)}`}. +

+ {:else} +

Nothing to {deleting ? 'delete' : 'create'}.

+ {/if} +
    + {#if preview.skippedOverlap}
  • {plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.
  • {/if} + {#if preview.skippedPast}
  • {plural(preview.skippedPast, 'slot')} skipped — in the past.
  • {/if} + {#if preview.kept}
  • {plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.
  • {/if} +
+
+{/if} + + diff --git a/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte new file mode 100644 index 0000000..5ff93c6 --- /dev/null +++ b/app-admin/src/lib/admin/slots/ClearSlotsModal.svelte @@ -0,0 +1,59 @@ + + + +
+

Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.

+ +
+ + +
+ + + + (open = false)} /> + +
diff --git a/app-admin/src/lib/admin/slots/CopyWeekModal.svelte b/app-admin/src/lib/admin/slots/CopyWeekModal.svelte new file mode 100644 index 0000000..ef2437a --- /dev/null +++ b/app-admin/src/lib/admin/slots/CopyWeekModal.svelte @@ -0,0 +1,68 @@ + + + +
+

Repeat one week’s slots in the weeks after it — same weekdays and times. Slots already there are left alone.

+ +
+ + +
+ + + + (open = false)} /> + +
diff --git a/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte b/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte new file mode 100644 index 0000000..fe78858 --- /dev/null +++ b/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte @@ -0,0 +1,145 @@ + + + +
+ + +
+ + +
+ +
+ Days +
+ {#each WEEKDAYS as weekday (weekday.day)} + + {/each} +
+
+ +
+ Opening hours ({timezone}) +
+ {#each draft.windows as window, i} +
+ + – + + {#if draft.windows.length > 1} + + {/if} +
+ {/each} +
+ +
+ +
+ + +
+ + {#if service} +

+ {#if startTimes.length} + {startTimes.length} per day: {startTimes.join(', ')} + {:else} + No {service.duration}-minute appointment fits in these hours. + {/if} +

+ {/if} + + + + (open = false)} /> + +
diff --git a/app-admin/src/lib/admin/slots/bulkForm.svelte.ts b/app-admin/src/lib/admin/slots/bulkForm.svelte.ts new file mode 100644 index 0000000..27bd175 --- /dev/null +++ b/app-admin/src/lib/admin/slots/bulkForm.svelte.ts @@ -0,0 +1,60 @@ +import { applyAction } from '$app/forms'; +import type { SubmitFunction } from '@sveltejs/kit'; +import type { BulkResult } from '$lib/slots'; + +/** + * State for a /slots bulk form (generate, copy, clear), which is always + * submitted twice: first `intent=preview` (the server says what it would + * do), then `intent=create` to do it. The preview only counts while the + * inputs are unchanged — `inputsKey` is a snapshot of them — so the admin + * can't confirm numbers for a form they have since edited. + * + * Previews and errors stay inside the modal; a finished run closes it and + * reloads the page, whose `form.bulk` then shows the outcome. + */ +export function bulkForm(inputsKey: () => string, close: () => void) { + let preview = $state(null); + let previewKey = $state(''); + let error = $state(''); + let busy = $state(false); + + const submit: SubmitFunction = () => { + const key = inputsKey(); + busy = true; + error = ''; + return async ({ result, update }) => { + busy = false; + if (result.type === 'success' && result.data?.bulk?.intent === 'preview') { + preview = result.data.bulk as BulkResult; + previewKey = key; + } else if (result.type === 'failure') { + error = String(result.data?.message || 'Something went wrong.'); + } else if (result.type === 'success') { + preview = null; + close(); + await update({ reset: false }); + } else { + await applyAction(result); + } + }; + }; + + return { + get preview() { + return preview && previewKey === inputsKey() ? preview : null; + }, + get error() { + return error; + }, + get busy() { + return busy; + }, + reset() { + preview = null; + error = ''; + }, + submit + }; +} + +export type BulkForm = ReturnType; diff --git a/app-admin/src/lib/server/slots.ts b/app-admin/src/lib/server/slots.ts new file mode 100644 index 0000000..f3afb64 --- /dev/null +++ b/app-admin/src/lib/server/slots.ts @@ -0,0 +1,43 @@ +// Server helpers for the /slots page. Planning is pure and lives in +// $shared/slots; this file does the PocketBase reads/writes around it. + +import type { SlotDetail } from '$lib/slots'; +import type { createPocketBase } from '$lib/pb'; + +type Pb = ReturnType; + +/** How many PocketBase writes a bulk action runs at once. */ +const WRITE_CONCURRENCY = 5; + +/** + * Slots with their places and blocking, from the shop hook — the same + * availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js). + * Either slots starting in `[from, to)` (optionally one service) or one slot by id. + */ +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', { + query: { detail: 1, ...query }, + requestKey: null + }); + return slots; +} + +/** One slot's details, or null if it doesn't exist (any other failure throws). */ +export async function loadSlotDetail(pb: Pb, id: string) { + return (await loadSlotDetails(pb, { id }))[0] ?? null; +} + +export const seatsTaken = (slot: Pick) => slot.booked + slot.held; + +/** Run `fn` over `values` a few at a time; returns how many succeeded. */ +export async function runInBatches(values: T[], label: string, fn: (value: T) => Promise) { + let succeeded = 0; + for (let i = 0; i < values.length; i += WRITE_CONCURRENCY) { + const results = await Promise.allSettled(values.slice(i, i + WRITE_CONCURRENCY).map(fn)); + for (const result of results) { + if (result.status === 'fulfilled') succeeded++; + else console.error(`[slots] ${label} failed`, result.reason); + } + } + return succeeded; +} diff --git a/app-admin/src/lib/slots.ts b/app-admin/src/lib/slots.ts new file mode 100644 index 0000000..9582d76 --- /dev/null +++ b/app-admin/src/lib/slots.ts @@ -0,0 +1 @@ +export * from '$shared/slots'; diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index 0de226c..8b8a2ca 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -8,8 +8,12 @@ function itemPayload(data: FormData) { const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; const rawStock = String(data.get('stock') ?? '').trim(); const rawDuration = String(data.get('duration') ?? '').trim(); + const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); + const rawCapacity = String(data.get('capacity') ?? '').trim(); const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null; const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null; + const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null; + const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null; return { name: String(data.get('name') || '').trim(), @@ -19,6 +23,8 @@ function itemPayload(data: FormData) { type, stock: Number.isNaN(stock) ? null : stock, duration: Number.isNaN(duration) ? null : duration, + bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, + capacity: Number.isNaN(capacity) ? null : capacity, active: String(data.get('active')) === 'true' }; } @@ -35,6 +41,8 @@ function normalizeItem(record: Record): ItemRecord { 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 }; } diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte index e1ed32f..3524857 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -21,6 +21,8 @@ type: ItemType; stock: string; duration: string; + bufferMinutes: string; + capacity: string; active: boolean; }; @@ -30,7 +32,7 @@ let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); function emptyDraft(): ItemDraft { - return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true }; + return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true }; } function createItem() { @@ -50,6 +52,8 @@ type: item.type, stock: item.stock == null ? '' : String(item.stock), duration: item.duration == null ? '' : String(item.duration), + bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), + capacity: item.capacity == null ? '' : String(item.capacity), active: item.active }; uploadError = ''; @@ -107,7 +111,7 @@ {item.type === 'item_with_time' ? 'Service' : 'Product'} {money.format(item.price)} {item.type === 'item' ? (item.stock ?? '∞') : '—'} - {item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'} + {item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'} {item.active ? 'Active' : 'Inactive'} @@ -156,10 +160,22 @@ {:else} - +
+ + + +
{/if}
diff --git a/app-admin/src/routes/slots/+page.server.ts b/app-admin/src/routes/slots/+page.server.ts index d617cfb..ab5508a 100644 --- a/app-admin/src/routes/slots/+page.server.ts +++ b/app-admin/src/routes/slots/+page.server.ts @@ -1,24 +1,56 @@ import { env } from '$env/dynamic/private'; import { fail } from '@sveltejs/kit'; -import { zonedInputToIso } from '$lib/calendar'; +import { toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import type { createPocketBase } from '$lib/pb'; import { attempt } from '$lib/server/actions'; -import type { SlotStatus } from '$lib/types'; +import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots'; +import { + MAX_BULK_SLOTS, + addDaysToKey, + dateKeysBetween, + instantMs, + isDateKey, + mondayOfKey, + monthGridKeys, + overlapsAny, + planGeneratedSlots, + shiftByDays, + timeToMinutes, + type BulkResult, + type PlannedSlot, + type SlotDetail, + type TimeWindow +} from '$lib/slots'; import type { Actions, PageServerLoad } from './$types'; type Pb = ReturnType; type SlotPayload = - | { payload: { item: string; start: string; end: string; notes: string } } + | { payload: { item: string; start: string; end: string; capacity: number; notes: string } } | { error: string }; -const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo'; +/** A slot to create: planned times plus what it copies (service, places, notes). */ +type Candidate = PlannedSlot & { item: string; capacity: number; notes: string }; -/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */ -function isHoldActive(slot: Record | null) { - if (slot?.status !== 'held') return false; - const until = Date.parse(String(slot.heldUntil || '').replace(' ', 'T')); - return Number.isNaN(until) || until > Date.now(); +const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo'; +const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10); +/** Midnight at the start of `key` in the site timezone, as an ISO instant. */ +const dayStartIso = (key: string) => zonedInputToIso(`${key}T00:00`, siteTimezone()); + +const MAX_RANGE_DAYS = 366; +const MAX_COPY_WEEKS = 12; +const MAX_CAPACITY = 500; + +/** + * Places from the form: a whole number 1–500, or the service's own + * capacity (default 1) when the field is left empty. + */ +function parseCapacity(data: FormData, item: Record): number | { error: string } { + const raw = String(data.get('capacity') ?? '').trim(); + if (raw === '') return Math.max(1, Number(item.capacity) || 1); + const capacity = Number(raw); + if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) return { error: `Places must be a whole number from 1 to ${MAX_CAPACITY}.` }; + return capacity; } async function slotPayload(data: FormData, pb: Pb): Promise { @@ -41,15 +73,102 @@ async function slotPayload(data: FormData, pb: Pb): Promise { } if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' }; + const capacity = parseCapacity(data, item); + if (typeof capacity !== 'number') return capacity; + const duration = Number(item.duration) || 0; const end = new Date(start.getTime() + duration * 60_000); - // Status is never taken from the form: it is owned by the booking flow - // (held by a basket, booked by a paid order). New slots start available. - return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } }; + // Bookings are never stored on the slot: places are counted from orders + // and basket holds by the shop hook, which also works out blocking. + return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), capacity, notes } }; } -export const load: PageServerLoad = async ({ locals }) => { +/** Validated `from`/`to` date keys from a bulk form, or an error message. */ +function dateRange(data: FormData): { fromDate: string; toDate: string } | { error: string } { + const fromDate = String(data.get('fromDate') || ''); + const toDate = String(data.get('toDate') || ''); + if (!isDateKey(fromDate) || !isDateKey(toDate)) return { error: 'Choose a start and end date.' }; + if (toDate < fromDate) return { error: 'The end date is before the start date.' }; + if (dateKeysBetween(fromDate, toDate).length > MAX_RANGE_DAYS) return { error: 'Choose a range of at most one year.' }; + return { fromDate, toDate }; +} + +/** Slot details for the days `fromKey`–`toKey` (inclusive), or null if PocketBase can't be read. */ +function slotsForDays(pb: Pb, fromKey: string, toKey: string, item = '') { + return loadSlotDetails(pb, { from: dayStartIso(fromKey), to: dayStartIso(addDaysToKey(toKey, 1)), item }).catch((e) => { + console.error('[slots] could not load slot details', e); + return null; + }); +} + +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 + * service (existing, or accepted earlier in this run). Different services + * may share a time: whichever is booked first blocks the others. + */ +function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) { + const now = Date.now(); + const taken = new Map(); + for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]); + + const accepted: Candidate[] = []; + let skippedPast = 0; + let skippedOverlap = 0; + for (const candidate of candidates) { + if (instantMs(candidate.start) <= now) { + skippedPast++; + continue; + } + const ranges = taken.get(candidate.item) ?? []; + if (overlapsAny(candidate, ranges)) { + skippedOverlap++; + continue; + } + ranges.push(candidate); + taken.set(candidate.item, ranges); + accepted.push(candidate); + } + accepted.sort((a, b) => instantMs(a.start) - instantMs(b.start)); + return { accepted, skippedPast, skippedOverlap }; +} + +function bulkResult(fields: Partial & Pick): { bulk: BulkResult } { + return { bulk: { skippedOverlap: 0, skippedPast: 0, kept: 0, firstStart: '', lastStart: '', failed: 0, ...fields } }; +} + +/** Preview, or create, the accepted candidates. */ +async function previewOrCreate(pb: Pb, action: 'generate' | 'copy', intent: string, result: ReturnType) { + const { accepted, skippedPast, skippedOverlap } = result; + if (accepted.length > MAX_BULK_SLOTS) { + return fail(400, { message: `That would create ${accepted.length} slots — at most ${MAX_BULK_SLOTS} at once. Choose a shorter range.` }); + } + const summary = { + action, + skippedPast, + skippedOverlap, + firstStart: accepted[0]?.start ?? '', + lastStart: accepted.at(-1)?.start ?? '' + }; + if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: accepted.length }); + + const created = await runInBatches(accepted, 'create', (slot) => + pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, capacity: slot.capacity, notes: slot.notes }) + ); + return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created }); +} + +export const load: PageServerLoad = async ({ locals, url }) => { + const today = todayKey(); + const monthParam = url.searchParams.get('month') || ''; + const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7); + const itemRecords = await locals.pb .collection('items') .getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' }) @@ -57,27 +176,16 @@ export const load: PageServerLoad = async ({ locals }) => { const items = itemRecords.map((record) => ({ id: record.id, name: String(record.name || ''), - duration: record.duration ?? 0 + duration: Number(record.duration) || 0, + bufferMinutes: Number(record.bufferMinutes) || 0, + capacity: Math.max(1, Number(record.capacity) || 1) })); - const slotRecords = await locals.pb - .collection('slots') - .getFullList({ sort: 'start', expand: 'item' }) - .catch(() => []); - const slots = slotRecords.map((record) => ({ - id: record.id, - item: String(record.item || ''), - itemName: String(record.expand?.item?.name || 'Unknown service'), - itemDuration: record.expand?.item?.duration ?? null, - start: String(record.start || ''), - end: record.end ? String(record.end) : '', - status: String(record.status || 'available') as SlotStatus, - heldUntil: record.heldUntil ? String(record.heldUntil) : '', - order: record.order ? String(record.order) : '', - notes: String(record.notes || '') - })); + // Only the slots shown in the month grid (which spans whole weeks). + const grid = monthGridKeys(month); + const slots = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]); - return { items, slots }; + return { items, slots: slots ?? [], slotsError: slots === null, month, today }; }; export const actions: Actions = { @@ -85,9 +193,7 @@ export const actions: Actions = { const data = await request.formData(); const result = await slotPayload(data, locals.pb); if ('error' in result) return fail(400, { message: result.error }); - const created = await attempt('Could not create the slot.', () => - locals.pb.collection('slots').create({ ...result.payload, status: 'available' }) - ); + const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload)); if (!created.ok) return created.failure; return { ok: true }; }, @@ -96,15 +202,20 @@ export const actions: Actions = { const id = String(data.get('id') || ''); if (!id) return fail(400, { message: 'Slot id is required.' }); - // Re-read the slot: the page may be stale, and a customer may have - // held or booked it since. Only notes can change while it's held. - const current = await locals.pb.collection('slots').getOne(id).catch(() => null); + // 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 + // and time are fixed; places can't go below what's taken. + const current = await loadSlotDetail(locals.pb, id).catch(() => undefined); + if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' }); if (!current) return fail(404, { message: 'This slot no longer exists.' }); - if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' }); - let patch: Record; - if (isHoldActive(current)) { - patch = { notes: String(data.get('notes') || '').trim() }; + const taken = seatsTaken(current); + let patch: Record; + if (taken > 0) { + const capacity = parseCapacity(data, { capacity: current.capacity }); + if (typeof capacity !== 'number') return fail(400, { message: capacity.error }); + if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` }); + patch = { capacity, notes: String(data.get('notes') || '').trim() }; } else { const result = await slotPayload(data, locals.pb); if ('error' in result) return fail(400, { message: result.error }); @@ -118,11 +229,114 @@ export const actions: Actions = { const data = await request.formData(); const id = String(data.get('id') || ''); if (!id) return fail(400, { message: 'Slot id is required.' }); - const record = await locals.pb.collection('slots').getOne(id).catch(() => null); - if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' }); - if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' }); + const current = await loadSlotDetail(locals.pb, id).catch(() => undefined); + if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' }); + if (current?.booked) return fail(400, { message: 'This slot has bookings and can’t be deleted.' }); + if (current?.held) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' }); const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id)); if (!deleted.ok) return deleted.failure; return { ok: true }; + }, + + /** Fill a date range with slots: chosen weekdays, time windows, get-ready gap. */ + generate: async ({ request, locals }) => { + const data = await request.formData(); + const intent = String(data.get('intent') || 'preview'); + const range = dateRange(data); + if ('error' in range) return fail(400, { message: range.error }); + + const item = await bookableService(locals.pb, String(data.get('item') || '')); + if (!item) return fail(400, { message: 'Choose a bookable service.' }); + const duration = Number(item.duration) || 0; + if (duration <= 0) return fail(400, { message: `“${item.name}” has no duration — set one under Services & products.` }); + const capacity = parseCapacity(data, item); + if (typeof capacity !== 'number') return fail(400, { message: capacity.error }); + + const 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 result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id, capacity, notes })), existing); + return previewOrCreate(locals.pb, 'generate', intent, result); + }, + + /** Repeat one week's slots (all services, or one) for the following weeks. */ + copy: async ({ request, locals }) => { + const data = await request.formData(); + const intent = String(data.get('intent') || 'preview'); + const sourceWeek = mondayOfKey(String(data.get('sourceDate') || '')); + if (!sourceWeek) return fail(400, { message: 'Choose the week to copy.' }); + const weeks = parseInt(String(data.get('weeks') || ''), 10); + if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` }); + const itemId = String(data.get('item') || ''); + + const source = await slotsForDays(locals.pb, sourceWeek, addDaysToKey(sourceWeek, 6), itemId); + const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 7), addDaysToKey(sourceWeek, 7 * (weeks + 1) - 1), itemId); + if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' }); + if (!source.length) return fail(400, { message: 'That week has no slots to copy.' }); + + // Copies are new, empty slots: same service, places and notes. + const candidates: Candidate[] = []; + for (let week = 1; week <= weeks; week++) { + for (const slot of source) { + const start = shiftByDays(slot.start, 7 * week, siteTimezone()); + if (!start) continue; + const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString(); + candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes }); + } + } + + return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing)); + }, + + /** Delete the slots in a date range that have no places taken. */ + clear: async ({ request, locals }) => { + const data = await request.formData(); + const intent = String(data.get('intent') || 'preview'); + const range = dateRange(data); + if ('error' in range) return fail(400, { message: range.error }); + const itemId = String(data.get('item') || ''); + + const slots = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId); + if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' }); + + const removable = slots.filter((slot) => seatsTaken(slot) === 0); + const summary = { + action: 'clear' as const, + kept: slots.length - removable.length, + firstStart: removable[0]?.start ?? '', + lastStart: removable.at(-1)?.start ?? '' + }; + if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length }); + + // Re-check each slot just before deleting it: a customer may have put + // it in their basket since the list was read. + const deleted = await runInBatches(removable, 'delete', async (slot) => { + const fresh = await loadSlotDetail(locals.pb, slot.id); + if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview'); + await locals.pb.collection('slots').delete(slot.id); + }); + return bulkResult({ ...summary, intent: 'done', count: deleted, failed: removable.length - deleted }); } }; diff --git a/app-admin/src/routes/slots/+page.svelte b/app-admin/src/routes/slots/+page.svelte index 4c5b1f1..20d97cc 100644 --- a/app-admin/src/routes/slots/+page.svelte +++ b/app-admin/src/routes/slots/+page.svelte @@ -1,25 +1,116 @@ @@ -57,57 +168,157 @@

Slots

-

Create bookable time slots for your services. Times are in {data.timezone}.

+

Bookable time slots for your services. Times are in {data.timezone}.

+
+
+ + + +
-
{#if form?.message}{/if} + {#if bulkDone}
{bulkMessage(bulkDone)}
{/if} + {#if !items.length}
Add a bookable service under Services & products first.
{/if} + {#if data.slotsError}{/if}
-
+
+ +

{monthLabel}

+ +
+ +
+ {#each WEEKDAYS as weekday (weekday.day)}
{weekday.label}
{/each} +
+
+ {#each gridKeys as key (key)} + {@const daySlotList = slotsByDay.get(key) ?? []} + {@const isToday = key === data.today} +
+ +
+ {#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)} + {@const state = slotState(slot)} + + {/each} + {#if daySlotList.length > MAX_CHIPS} + + {/if} +
+
+ {/each} +
+ +
+ {#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)} + {label} + {/each} + — a booking (or basket) at one time blocks every other service overlapping it, including get-ready time. +
+
+ + +
+ All slots in {monthLabel} ({monthSlots.length}) +
- + - {#each slots as slot (slot.id)} + {#each monthSlots as slot (slot.id)} + {@const state = slotState(slot)} - + {:else} - + {/each}
ServiceDateDurationStatus
ServiceDatePlacesStatus
{slot.itemName} {formatDateTime(slot.start, data.timezone)}{slot.itemDuration ? `${slot.itemDuration} min` : '—'}{slot.booked + slot.held}/{slot.capacity} - {slot.status} + {SLOT_STATE_LABELS[state]} - +
{items.length ? 'No slots yet — create one so customers can book.' : 'Add a bookable service under Services & products first.'}
No slots this month — use “Generate slots” to fill it.
-
+
+ + + + + + {#if daySlots.length} +
    + {#each daySlots as slot (slot.id)} + {@const state = slotState(slot)} +
  • + {formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''} + + {slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''} + {#if state === 'blocked'}{blockedReason(slot)}{/if} + {#if slot.notes}{slot.notes}{/if} + + {SLOT_STATE_LABELS[state]} + +
  • + {/each} +
+ {:else} +

No slots on this day{serviceFilter ? ' for this service' : ''}.

+ {/if} + +
+ -
+ - {#if isHeld} + {#if editorError}{/if} + + {#if taken}
- This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed. + {[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.
{/if}