Merge pull request 'Slots: bulk tools, get-ready time, group places, and bookings block overlapping slots' (#3) from session/redo-slots-and-add-get-ready-tim into main
Reviewed-on: #3
This commit is contained in:
commit
148b07253e
29 changed files with 2049 additions and 273 deletions
11
AGENTS.md
11
AGENTS.md
|
|
@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb,
|
|||
app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
||||
├── 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.<domain>)
|
|||
│ │ ├── 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 `<input type="date">` fields follow the visitor's browser language and can't be changed from the page.
|
||||
- **Dates/times in admin**: entered and displayed in `SITE_TIMEZONE` (layout data `timezone`), via `toZonedDatetimeInput`, `zonedInputToIso`, `formatDateTime` in `$shared/calendar`. Never `new Date(localInput)` on the server — the container runs in UTC.
|
||||
- **Prose**: `.prose-wellness` class for rich text content styling
|
||||
|
||||
|
|
@ -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".
|
||||
|
|
|
|||
21
README.md
21
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)
|
||||
|
|
|
|||
54
app-admin/src/lib/admin/slots/BulkActions.svelte
Normal file
54
app-admin/src/lib/admin/slots/BulkActions.svelte
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<script lang="ts">
|
||||
// Footer of a bulk slot form: the server's preview, then Preview / confirm
|
||||
// buttons. See bulkForm.svelte.ts for the two-step submit.
|
||||
import { formatDateTime } from '$lib/calendar';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
import type { BulkForm } from './bulkForm.svelte';
|
||||
|
||||
let { bulk, timezone, onCancel }: { bulk: BulkForm; timezone: string; onCancel: () => void } = $props();
|
||||
|
||||
let preview = $derived(bulk.preview);
|
||||
let deleting = $derived(preview?.action === 'clear');
|
||||
let plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
||||
</script>
|
||||
|
||||
{#if bulk.error}<div class="alert alert-error mt-3 text-sm" role="alert">{bulk.error}</div>{/if}
|
||||
|
||||
{#if preview}
|
||||
<div class="mt-3 rounded-box bg-base-200 p-4 text-sm">
|
||||
{#if preview.count}
|
||||
<p class="font-semibold">
|
||||
{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)}`}.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="font-semibold">Nothing to {deleting ? 'delete' : 'create'}.</p>
|
||||
{/if}
|
||||
<ul class="mt-1 list-inside list-disc text-base-content/70 empty:hidden">
|
||||
{#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.</li>{/if}
|
||||
{#if preview.skippedPast}<li>{plural(preview.skippedPast, 'slot')} skipped — in the past.</li>{/if}
|
||||
{#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.</li>{/if}
|
||||
</ul>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="modal-action">
|
||||
<button class="btn" type="button" onclick={onCancel}>Cancel</button>
|
||||
<button class={['btn', !preview?.count && 'btn-primary']} type="submit" name="intent" value="preview" disabled={bulk.busy}>
|
||||
{#if bulk.busy}<span class="loading loading-spinner loading-xs"></span>{/if}
|
||||
{preview ? 'Preview again' : 'Preview'}
|
||||
</button>
|
||||
{#if preview?.count}
|
||||
<button
|
||||
class={['btn', deleting ? 'btn-error' : 'btn-primary']}
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="create"
|
||||
disabled={bulk.busy}
|
||||
onclick={deleting ? confirmSubmit(`Delete ${plural(preview.count, 'slot')}?`) : undefined}
|
||||
>
|
||||
{deleting ? 'Delete' : 'Create'} {plural(preview.count, 'slot')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
59
app-admin/src/lib/admin/slots/ClearSlotsModal.svelte
Normal file
59
app-admin/src/lib/admin/slots/ClearSlotsModal.svelte
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
fromDate,
|
||||
toDate
|
||||
}: { open?: boolean; items: { id: string; name: string }[]; timezone: string; fromDate: string; toDate: string } = $props();
|
||||
|
||||
let draft = $state({ fromDate: '', toDate: '', item: '' });
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
// Each opening starts from the range the admin opened it for (a day or the month).
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
draft.fromDate = fromDate;
|
||||
draft.toDate = toDate;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Clear slots" wide>
|
||||
<form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1">
|
||||
<p class="text-sm text-base-content/70">Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.</p>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">From</span>
|
||||
<input class="input w-full" type="date" name="fromDate" required bind:value={draft.fromDate} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">To</span>
|
||||
<input class="input w-full" type="date" name="toDate" required min={draft.fromDate} bind:value={draft.toDate} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Services</span>
|
||||
<select class="select w-full" name="item" bind:value={draft.item}>
|
||||
<option value="">All services</option>
|
||||
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
68
app-admin/src/lib/admin/slots/CopyWeekModal.svelte
Normal file
68
app-admin/src/lib/admin/slots/CopyWeekModal.svelte
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import { addDaysToKey, formatDateKey, mondayOfKey } from '$lib/slots';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
sourceDate
|
||||
}: { open?: boolean; items: { id: string; name: string }[]; timezone: string; sourceDate: string } = $props();
|
||||
|
||||
let draft = $state({ sourceDate: '', weeks: 1, item: '' });
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
// Each opening copies from the week the admin opened it from.
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
draft.sourceDate = sourceDate;
|
||||
});
|
||||
});
|
||||
|
||||
const shortDate = (key: string) => formatDateKey(key, { weekday: 'short', day: 'numeric', month: 'short' });
|
||||
let monday = $derived(mondayOfKey(draft.sourceDate));
|
||||
let weeks = $derived(Math.max(1, Math.min(12, Number(draft.weeks) || 1)));
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Copy a week" wide>
|
||||
<form method="POST" action="?/copy" use:enhance={bulk.submit} class="space-y-1">
|
||||
<p class="text-sm text-base-content/70">Repeat one week’s slots in the weeks after it — same weekdays and times. Slots already there are left alone.</p>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Copy the week of</span>
|
||||
<input class="input w-full" type="date" name="sourceDate" required bind:value={draft.sourceDate} />
|
||||
{#if monday}<span class="label">{shortDate(monday)} – {shortDate(addDaysToKey(monday, 6))}</span>{/if}
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Into the next</span>
|
||||
<select class="select w-full" name="weeks" bind:value={draft.weeks}>
|
||||
{#each Array.from({ length: 12 }, (_, i) => i + 1) as n}
|
||||
<option value={n}>{n} week{n === 1 ? '' : 's'}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{#if monday}<span class="label">{shortDate(addDaysToKey(monday, 7))} – {shortDate(addDaysToKey(monday, 7 * (weeks + 1) - 1))}</span>{/if}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Services</span>
|
||||
<select class="select w-full" name="item" bind:value={draft.item}>
|
||||
<option value="">All services</option>
|
||||
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
145
app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
Normal file
145
app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { enhance } from '$app/forms';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import { WEEKDAYS, addDaysToKey, startTimesInWindows, type TimeWindow } from '$lib/slots';
|
||||
import BulkActions from './BulkActions.svelte';
|
||||
import { bulkForm } from './bulkForm.svelte';
|
||||
|
||||
type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number };
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
items,
|
||||
timezone,
|
||||
today
|
||||
}: { open?: boolean; items: Service[]; timezone: string; today: string } = $props();
|
||||
|
||||
// Kept between openings, so a second run starts from the last settings.
|
||||
let draft = $state({
|
||||
item: '',
|
||||
fromDate: '',
|
||||
toDate: '',
|
||||
weekdays: [1, 2, 3, 4, 5],
|
||||
windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[],
|
||||
bufferMinutes: '',
|
||||
capacity: '',
|
||||
notes: ''
|
||||
});
|
||||
|
||||
const bulk = bulkForm(
|
||||
() => JSON.stringify(draft),
|
||||
() => (open = false)
|
||||
);
|
||||
|
||||
let service = $derived(items.find((item) => item.id === draft.item));
|
||||
let startTimes = $derived(
|
||||
service ? startTimesInWindows(draft.windows, service.duration, Number(draft.bufferMinutes) || 0) : []
|
||||
);
|
||||
|
||||
// Each opening starts without a stale preview; the first one also fills in dates.
|
||||
$effect(() => {
|
||||
if (!open) return;
|
||||
untrack(() => {
|
||||
bulk.reset();
|
||||
if (!draft.fromDate) {
|
||||
draft.fromDate = today;
|
||||
draft.toDate = addDaysToKey(today, 27);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function selectService(id: string) {
|
||||
draft.item = id;
|
||||
// The service's own get-ready time and places are the defaults; both can be overridden here.
|
||||
const item = items.find((item) => item.id === id);
|
||||
draft.bufferMinutes = String(item?.bufferMinutes ?? 0);
|
||||
draft.capacity = String(item?.capacity ?? 1);
|
||||
}
|
||||
|
||||
function addWindow() {
|
||||
const last = draft.windows.at(-1);
|
||||
draft.windows.push(last ? { from: last.to, to: last.to } : { from: '09:00', to: '17:00' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="Generate slots" wide>
|
||||
<form method="POST" action="?/generate" use:enhance={bulk.submit} class="space-y-1">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Service</span>
|
||||
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}>
|
||||
<option value="" disabled>Select a service…</option>
|
||||
{#each items as item (item.id)}
|
||||
<option value={item.id}>{item.name} ({item.duration} min)</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">From</span>
|
||||
<input class="input w-full" type="date" name="fromDate" required bind:value={draft.fromDate} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">To</span>
|
||||
<input class="input w-full" type="date" name="toDate" required min={draft.fromDate} bind:value={draft.toDate} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="fieldset">
|
||||
<span class="fieldset-legend">Days</span>
|
||||
<div class="join grid grid-cols-7">
|
||||
{#each WEEKDAYS as weekday (weekday.day)}
|
||||
<input class="btn join-item btn-sm px-1" type="checkbox" name="weekday" value={weekday.day} aria-label={weekday.label} bind:group={draft.weekdays} />
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fieldset">
|
||||
<span class="fieldset-legend">Opening hours ({timezone})</span>
|
||||
<div class="space-y-2">
|
||||
{#each draft.windows as window, i}
|
||||
<div class="flex items-center gap-2">
|
||||
<input class="input w-32" type="time" name="windowFrom" required aria-label="From" bind:value={window.from} />
|
||||
<span>–</span>
|
||||
<input class="input w-32" type="time" name="windowTo" required aria-label="To" bind:value={window.to} />
|
||||
{#if draft.windows.length > 1}
|
||||
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove these hours" onclick={() => draft.windows.splice(i, 1)}>✕</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<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 class="grid gap-x-4 md:grid-cols-2">
|
||||
<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 appointment. Defaults to the service’s own.</span>
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Places per slot</span>
|
||||
<input class="input w-32" type="number" min="1" max="500" step="1" name="capacity" bind:value={draft.capacity} />
|
||||
<span class="label">More than 1 for a group session. Defaults to the service’s own.</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if service}
|
||||
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
|
||||
{#if startTimes.length}
|
||||
<span class="font-semibold">{startTimes.length} per day:</span> {startTimes.join(', ')}
|
||||
{:else}
|
||||
No {service.duration}-minute appointment fits in these hours.
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Notes <span class="font-normal text-base-content/50">(optional, added to every slot)</span></span>
|
||||
<input class="input w-full" name="notes" bind:value={draft.notes} />
|
||||
</label>
|
||||
|
||||
<BulkActions {bulk} {timezone} onCancel={() => (open = false)} />
|
||||
</form>
|
||||
</Modal>
|
||||
60
app-admin/src/lib/admin/slots/bulkForm.svelte.ts
Normal file
60
app-admin/src/lib/admin/slots/bulkForm.svelte.ts
Normal file
|
|
@ -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<BulkResult | null>(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<typeof bulkForm>;
|
||||
43
app-admin/src/lib/server/slots.ts
Normal file
43
app-admin/src/lib/server/slots.ts
Normal file
|
|
@ -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<typeof createPocketBase>;
|
||||
|
||||
/** 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<SlotDetail, 'booked' | 'held'>) => slot.booked + slot.held;
|
||||
|
||||
/** Run `fn` over `values` a few at a time; returns how many succeeded. */
|
||||
export async function runInBatches<T>(values: T[], label: string, fn: (value: T) => Promise<unknown>) {
|
||||
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;
|
||||
}
|
||||
1
app-admin/src/lib/slots.ts
Normal file
1
app-admin/src/lib/slots.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/slots';
|
||||
|
|
@ -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<string, any>): 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
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 @@
|
|||
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
|
||||
<td>{money.format(item.price)}</td>
|
||||
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
|
||||
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td>
|
||||
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td>
|
||||
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||
</tr>
|
||||
|
|
@ -156,10 +160,22 @@
|
|||
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
|
||||
</label>
|
||||
{:else}
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Duration (minutes)</span>
|
||||
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} />
|
||||
</label>
|
||||
<div class="grid gap-x-4 md:grid-cols-2">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Duration (minutes)</span>
|
||||
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} />
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Get-ready time (minutes)</span>
|
||||
<input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} />
|
||||
<span class="label">Gap after each appointment — between generated slots, and before another service can start</span>
|
||||
</label>
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Places per slot</span>
|
||||
<input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} />
|
||||
<span class="label">1 for one-to-one; more for a group session. New slots start with this.</span>
|
||||
</label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="fieldset">
|
||||
|
|
|
|||
|
|
@ -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<typeof createPocketBase>;
|
||||
|
||||
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<string, any> | 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<string, any>): 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<SlotPayload> {
|
||||
|
|
@ -41,15 +73,102 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
|
|||
}
|
||||
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<string, PlannedSlot[]>();
|
||||
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<BulkResult> & Pick<BulkResult, 'action' | 'intent' | 'count'>): { 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<typeof filterCandidates>) {
|
||||
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<string, string>;
|
||||
if (isHoldActive(current)) {
|
||||
patch = { notes: String(data.get('notes') || '').trim() };
|
||||
const taken = seatsTaken(current);
|
||||
let patch: Record<string, string | number>;
|
||||
if (taken > 0) {
|
||||
const capacity = parseCapacity(data, { capacity: current.capacity });
|
||||
if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
|
||||
if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` });
|
||||
patch = { capacity, notes: String(data.get('notes') || '').trim() };
|
||||
} else {
|
||||
const 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 });
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,25 +1,116 @@
|
|||
<script lang="ts">
|
||||
import type { SubmitFunction } from '@sveltejs/kit';
|
||||
import { enhance } from '$app/forms';
|
||||
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
|
||||
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte';
|
||||
import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte';
|
||||
import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
|
||||
import type { BulkResult, SlotState } from '$lib/slots';
|
||||
|
||||
let { data, form } = $props();
|
||||
let items = $derived(data.items || []);
|
||||
let slots = $derived(data.slots || []);
|
||||
let showEditor = $state(false);
|
||||
let serviceFilter = $state('');
|
||||
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter));
|
||||
type Slot = (typeof slots)[number];
|
||||
let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot])));
|
||||
|
||||
// ── Month grid (date keys in the site timezone) ──
|
||||
const MAX_CHIPS = 4;
|
||||
let gridKeys = $derived(monthGridKeys(data.month));
|
||||
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
|
||||
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
|
||||
let slotsByDay = $derived.by(() => {
|
||||
const byDay = new Map<string, Slot[]>();
|
||||
for (const slot of slots) {
|
||||
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
|
||||
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
|
||||
}
|
||||
return byDay;
|
||||
});
|
||||
let monthSlots = $derived(slots.filter((slot) => toZonedDatetimeInput(slot.start, data.timezone).startsWith(data.month)));
|
||||
|
||||
// ── Modals ──
|
||||
let showEditor = $state(false);
|
||||
let showGenerate = $state(false);
|
||||
let showCopy = $state(false);
|
||||
let showClear = $state(false);
|
||||
let dayKey = $state('');
|
||||
let showDay = $state(false);
|
||||
let copyFrom = $state('');
|
||||
let clearRange = $state({ from: '', to: '' });
|
||||
let daySlots = $derived(slotsByDay.get(dayKey) ?? []);
|
||||
|
||||
let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null);
|
||||
|
||||
function bulkMessage(result: BulkResult) {
|
||||
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
|
||||
const verb = result.action === 'clear' ? 'Deleted' : 'Created';
|
||||
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : '';
|
||||
return `${verb} ${n(result.count)}.${failed}`;
|
||||
}
|
||||
|
||||
const STATE_CLASSES: Record<SlotState, string> = {
|
||||
free: 'border-success/40 bg-success/10',
|
||||
held: 'border-warning/50 bg-warning/20',
|
||||
booked: 'border-info/40 bg-info/15',
|
||||
full: 'border-info/60 bg-info/30',
|
||||
blocked: 'border-base-300 bg-base-100 text-base-content/40 line-through'
|
||||
};
|
||||
const BADGE_CLASSES: Record<SlotState, string> = {
|
||||
free: 'badge-success',
|
||||
held: 'badge-warning',
|
||||
booked: 'badge-info badge-soft',
|
||||
full: 'badge-info',
|
||||
blocked: 'badge-ghost'
|
||||
};
|
||||
|
||||
/** "2/8" for group slots, '' for one-to-one. */
|
||||
function places(slot: Slot) {
|
||||
return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
|
||||
}
|
||||
|
||||
/** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */
|
||||
function blockedReason(slot: Slot) {
|
||||
const blocker = slotsById.get(slot.blockedBy);
|
||||
return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking';
|
||||
}
|
||||
|
||||
function openDay(key: string) {
|
||||
dayKey = key;
|
||||
showDay = true;
|
||||
}
|
||||
|
||||
function openCopy(key: string) {
|
||||
copyFrom = mondayOfKey(key);
|
||||
showDay = false;
|
||||
showCopy = true;
|
||||
}
|
||||
|
||||
function openClear(from: string, to: string) {
|
||||
clearRange = { from, to };
|
||||
showDay = false;
|
||||
showClear = true;
|
||||
}
|
||||
|
||||
// ── Single slot editor ──
|
||||
type SlotDraft = {
|
||||
id: string;
|
||||
item: string;
|
||||
start: string;
|
||||
status: string;
|
||||
heldUntil: string;
|
||||
capacity: string;
|
||||
booked: number;
|
||||
held: number;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
let draft = $state<SlotDraft>(emptyDraft());
|
||||
let editorError = $state('');
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let isHeld = $derived(draft.status === 'held');
|
||||
// Once any place is taken, the service and time are fixed (customers booked them).
|
||||
let taken = $derived(draft.booked + draft.held);
|
||||
let selectedItem = $derived(items.find((item) => item.id === draft.item));
|
||||
let endLabel = $derived.by(() => {
|
||||
if (!selectedItem || !draft.start) return '';
|
||||
|
|
@ -29,24 +120,44 @@
|
|||
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
|
||||
});
|
||||
|
||||
function emptyDraft(): SlotDraft {
|
||||
return { id: '', item: '', start: toZonedDatetimeInput(new Date().toISOString(), data.timezone), status: 'available', heldUntil: '', notes: '' };
|
||||
function emptyDraft(day = ''): SlotDraft {
|
||||
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
|
||||
return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' };
|
||||
}
|
||||
|
||||
function createSlot() {
|
||||
draft = emptyDraft();
|
||||
// Enhanced so the page keeps its ?month= after saving (a plain POST to
|
||||
// ?/create would drop it), and errors show inside the open modal.
|
||||
const submitSlot: SubmitFunction = () => {
|
||||
editorError = '';
|
||||
return async ({ result, update }) => {
|
||||
if (result.type === 'failure') {
|
||||
editorError = String(result.data?.message || 'Could not save the slot.');
|
||||
return;
|
||||
}
|
||||
if (result.type === 'success') showEditor = false;
|
||||
await update();
|
||||
};
|
||||
};
|
||||
|
||||
function createSlot(day = '') {
|
||||
editorError = '';
|
||||
draft = emptyDraft(day);
|
||||
showDay = false;
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editSlot(slot: (typeof slots)[number]) {
|
||||
function editSlot(slot: Slot) {
|
||||
editorError = '';
|
||||
draft = {
|
||||
id: slot.id,
|
||||
item: slot.item,
|
||||
start: toZonedDatetimeInput(slot.start, data.timezone),
|
||||
status: slot.status,
|
||||
heldUntil: slot.heldUntil,
|
||||
capacity: String(slot.capacity),
|
||||
booked: slot.booked,
|
||||
held: slot.held,
|
||||
notes: slot.notes
|
||||
};
|
||||
showDay = false;
|
||||
showEditor = true;
|
||||
}
|
||||
</script>
|
||||
|
|
@ -57,57 +168,157 @@
|
|||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Slots</h1>
|
||||
<p class="text-base-content/60">Create bookable time slots for your services. Times are in {data.timezone}.</p>
|
||||
<p class="text-base-content/60">Bookable time slots for your services. Times are in {data.timezone}.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button class="btn" type="button" onclick={() => createSlot()}>Create slot</button>
|
||||
<button class="btn" type="button" onclick={() => openCopy(data.today)}>Copy a week</button>
|
||||
<button class="btn" type="button" onclick={() => openClear(data.today > `${data.month}-01` ? data.today : `${data.month}-01`, monthEnd)}>Clear slots</button>
|
||||
<button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
|
||||
{#if bulkDone}<div class="alert alert-success" role="status">{bulkMessage(bulkDone)}</div>{/if}
|
||||
{#if !items.length}<div class="alert" role="status">Add a bookable service under Services & products first.</div>{/if}
|
||||
{#if data.slotsError}<div class="alert alert-error" role="alert">Could not load this month’s slots — is the database reachable?</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="overflow-x-auto">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex gap-2">
|
||||
<a class="btn btn-outline btn-sm" href="?month={addMonthsToKey(data.month, -1)}" data-sveltekit-noscroll>← Previous</a>
|
||||
<a class="btn btn-ghost btn-sm" href="?month={data.today.slice(0, 7)}" data-sveltekit-noscroll>Today</a>
|
||||
<a class="btn btn-outline btn-sm" href="?month={addMonthsToKey(data.month, 1)}" data-sveltekit-noscroll>Next →</a>
|
||||
</div>
|
||||
<h2 class="text-2xl font-bold">{monthLabel}</h2>
|
||||
<select class="select select-sm w-auto" aria-label="Show service" bind:value={serviceFilter}>
|
||||
<option value="">All services</option>
|
||||
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase text-base-content/50 md:gap-2">
|
||||
{#each WEEKDAYS as weekday (weekday.day)}<div>{weekday.label}</div>{/each}
|
||||
</div>
|
||||
<div class="mt-2 grid grid-cols-7 gap-1 md:gap-2">
|
||||
{#each gridKeys as key (key)}
|
||||
{@const daySlotList = slotsByDay.get(key) ?? []}
|
||||
{@const isToday = key === data.today}
|
||||
<div class="min-h-28 min-w-0 rounded-box border border-base-300 bg-base-200/60 p-1 md:p-2" class:opacity-40={!key.startsWith(data.month)}>
|
||||
<button
|
||||
class="btn btn-circle btn-xs mb-1 {isToday ? 'btn-primary' : 'btn-ghost'}"
|
||||
type="button"
|
||||
title="Show this day"
|
||||
aria-current={isToday ? 'date' : undefined}
|
||||
onclick={() => openDay(key)}>{Number(key.slice(8))}</button
|
||||
>
|
||||
<div class="space-y-1">
|
||||
{#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)}
|
||||
{@const state = slotState(slot)}
|
||||
<button
|
||||
class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}"
|
||||
type="button"
|
||||
title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {state === 'blocked' ? blockedReason(slot) : SLOT_STATE_LABELS[state]}{places(slot) ? ` (${places(slot)})` : ''}"
|
||||
onclick={() => editSlot(slot)}
|
||||
>
|
||||
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
|
||||
<span class="hidden lg:inline">{slot.itemName}</span>
|
||||
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
|
||||
</button>
|
||||
{/each}
|
||||
{#if daySlotList.length > MAX_CHIPS}
|
||||
<button class="btn btn-ghost btn-xs w-full" type="button" onclick={() => openDay(key)}>+{daySlotList.length - MAX_CHIPS} more</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-4 text-xs text-base-content/70">
|
||||
{#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)}
|
||||
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {STATE_CLASSES[state as SlotState]}"></span> {label}</span>
|
||||
{/each}
|
||||
<span>— a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Collapsed by default: a generated month is hundreds of rows, and the calendar covers day-to-day use. -->
|
||||
<details class="collapse collapse-arrow rounded-box bg-base-100 shadow">
|
||||
<summary class="collapse-title text-2xl font-bold">All slots in {monthLabel} <span class="text-base font-normal text-base-content/60">({monthSlots.length})</span></summary>
|
||||
<div class="collapse-content overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<thead><tr><th>Service</th><th>Date</th><th>Places</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each slots as slot (slot.id)}
|
||||
{#each monthSlots as slot (slot.id)}
|
||||
{@const state = slotState(slot)}
|
||||
<tr>
|
||||
<td><span class="font-semibold">{slot.itemName}</span></td>
|
||||
<td>{formatDateTime(slot.start, data.timezone)}</td>
|
||||
<td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td>
|
||||
<td>{slot.booked + slot.held}/{slot.capacity}</td>
|
||||
<td>
|
||||
<span
|
||||
class="badge capitalize"
|
||||
class:badge-success={slot.status === 'available'}
|
||||
class:badge-warning={slot.status === 'held'}
|
||||
class:badge-info={slot.status === 'booked'}
|
||||
>{slot.status}</span>
|
||||
<span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} title={slot.status === 'booked' ? 'Booked slots can’t be edited' : undefined} onclick={() => editSlot(slot)}>Edit</button>
|
||||
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
|
||||
</td>
|
||||
</tr>
|
||||
{:else}
|
||||
<tr><td colspan="5" class="py-10 text-center text-base-content/60">{items.length ? 'No slots yet — create one so customers can book.' : 'Add a bookable service under Services & products first.'}</td></tr>
|
||||
<tr><td colspan="5" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<GenerateSlotsModal bind:open={showGenerate} {items} timezone={data.timezone} today={data.today} />
|
||||
<CopyWeekModal bind:open={showCopy} {items} timezone={data.timezone} sourceDate={copyFrom} />
|
||||
<ClearSlotsModal bind:open={showClear} {items} timezone={data.timezone} fromDate={clearRange.from} toDate={clearRange.to} />
|
||||
|
||||
<Modal bind:open={showDay} title={formatDateKey(dayKey, { weekday: 'long', day: 'numeric', month: 'long' })} wide>
|
||||
{#if daySlots.length}
|
||||
<ul class="divide-y divide-base-300">
|
||||
{#each daySlots as slot (slot.id)}
|
||||
{@const state = slotState(slot)}
|
||||
<li class="flex items-center gap-3 py-2">
|
||||
<span class="w-28 shrink-0 font-semibold">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate">{slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''}</span>
|
||||
{#if state === 'blocked'}<span class="block truncate text-xs text-base-content/60">{blockedReason(slot)}</span>{/if}
|
||||
{#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if}
|
||||
</span>
|
||||
<span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
|
||||
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
|
||||
{/if}
|
||||
<div class="modal-action flex-wrap justify-between">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button>
|
||||
{#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if}
|
||||
</div>
|
||||
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot(dayKey)}>Add slot</button>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}>
|
||||
<form method="POST" action={action} class="space-y-1">
|
||||
<form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
|
||||
{#if isHeld}
|
||||
{#if editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if}
|
||||
|
||||
{#if taken}
|
||||
<div class="alert alert-warning mb-2 text-sm">
|
||||
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.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Service</span>
|
||||
<select class="select w-full" name="item" required disabled={isHeld} bind:value={draft.item}>
|
||||
<select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}>
|
||||
<option value="" disabled>Select a service…</option>
|
||||
{#each items as item (item.id)}
|
||||
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
|
||||
|
|
@ -117,17 +328,23 @@
|
|||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Start ({data.timezone})</span>
|
||||
<input class="input w-full" type="datetime-local" name="start" required disabled={isHeld} bind:value={draft.start} />
|
||||
<input class="input w-full" type="datetime-local" name="start" required disabled={taken > 0} bind:value={draft.start} />
|
||||
{#if endLabel}<span class="label">{endLabel}</span>{/if}
|
||||
</label>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Places</span>
|
||||
<input class="input w-32" type="number" min={Math.max(1, taken)} max="500" step="1" name="capacity" placeholder={String(selectedItem?.capacity ?? 1)} bind:value={draft.capacity} />
|
||||
<span class="label">More than 1 for a group session.{draft.id ? '' : ' Empty = the service’s own.'}</span>
|
||||
</label>
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Notes</span>
|
||||
<textarea class="textarea w-full" name="notes" bind:value={draft.notes}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="modal-action justify-between">
|
||||
{#if draft.id && !isHeld}
|
||||
{#if draft.id && !taken}
|
||||
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit('Delete this slot?')}>Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
import { page } from '$app/state';
|
||||
import type { HeaderGlobal } from '$lib/types';
|
||||
import { getBasketContext } from '$lib/basket.svelte';
|
||||
import { formatPrice } from '$shared/calendar';
|
||||
|
||||
let { header } = $props<{ header: HeaderGlobal }>();
|
||||
|
||||
|
|
@ -29,9 +30,7 @@
|
|||
return href === '/' ? path === '/' : path === href || path.startsWith(href + '/');
|
||||
}
|
||||
|
||||
function formatTotal(amount: number) {
|
||||
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
|
||||
}
|
||||
const formatTotal = formatPrice;
|
||||
</script>
|
||||
|
||||
{#snippet basketIcon()}
|
||||
|
|
|
|||
|
|
@ -72,7 +72,9 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
|||
itemPrice: item?.price,
|
||||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||
slotStart: slot?.start,
|
||||
slotEnd: slot?.end
|
||||
slotEnd: slot?.end,
|
||||
slotCapacity: slot?.capacity,
|
||||
heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined
|
||||
};
|
||||
});
|
||||
return {
|
||||
|
|
@ -82,7 +84,8 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
|||
email: record.email || null,
|
||||
customerDetails: record.customerDetails || null,
|
||||
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
||||
lines: mappedLines
|
||||
lines: mappedLines,
|
||||
serverNow: Date.now()
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
|
|||
import type { ItemRecord, SlotRecord } from '$lib/types';
|
||||
import { BASKET_COOKIE, getBasket } from '$lib/server/shop';
|
||||
import { loadShopData } from '$shared/server/shop';
|
||||
import { DEFAULT_TIMEZONE } from '$shared/calendar';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
|
|
@ -13,7 +15,12 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
|||
}
|
||||
}
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals, cookies }) => {
|
||||
export const load: LayoutServerLoad = async ({ locals, cookies, url }) => {
|
||||
// Reading the path makes this load run again on every navigation, so the
|
||||
// slots and basket are fresh on each page — places free up or get taken
|
||||
// (holds lapse, other customers book) while the visitor browses.
|
||||
void url.pathname;
|
||||
|
||||
const [header, footer, colors] = await Promise.all([
|
||||
getGlobal(locals.pb, 'header', defaultHeader),
|
||||
getGlobal(locals.pb, 'footer', defaultFooter),
|
||||
|
|
@ -35,5 +42,8 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => {
|
|||
const items: ItemRecord[] = shop?.items ?? [];
|
||||
const slots: SlotRecord[] = shop?.slots ?? [];
|
||||
|
||||
return { header, footer, colors, user: locals.user, basket, items, slots };
|
||||
// Booking times are shown in the studio's timezone, wherever the visitor is.
|
||||
const timezone = env.SITE_TIMEZONE || DEFAULT_TIMEZONE;
|
||||
|
||||
return { header, footer, colors, user: locals.user, basket, items, slots, timezone };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,21 +1,12 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { formatInstant, formatPrice } from '$shared/calendar';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
// "Friday 15 January, 10:00" in the studio's timezone.
|
||||
function formatSlotDate(iso?: string | null) {
|
||||
if (!iso) return '';
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
weekday: 'long',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function formatPrice(amount: number) {
|
||||
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
|
||||
return formatInstant(iso, data.timezone, { weekday: 'long', day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
</script>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { getContext, setContext } from 'svelte';
|
||||
import { invalidateAll } from '$app/navigation';
|
||||
import type { Basket, BasketLine } from './types';
|
||||
|
||||
const BASKET_KEY = 'basket';
|
||||
|
|
@ -8,12 +9,20 @@ export type BasketStore = ReturnType<typeof createBasketStore>;
|
|||
export function createBasketStore(initial: Basket | null) {
|
||||
let lines = $state<BasketLine[]>(initial?.lines ?? []);
|
||||
let status = $state<Basket['status']>(initial?.status ?? 'active');
|
||||
// Browser clock minus server clock, so hold countdowns survive a wrong clock.
|
||||
let clockOffset = $state(clockOffsetOf(initial));
|
||||
|
||||
const total = $derived(
|
||||
lines.reduce((sum, line) => sum + (line.itemPrice ?? 0) * line.quantity, 0)
|
||||
);
|
||||
const count = $derived(lines.reduce((sum, line) => sum + line.quantity, 0));
|
||||
|
||||
/** When the first slot reservation in the basket lapses, in browser-clock ms (null: none). */
|
||||
const holdDeadline = $derived.by(() => {
|
||||
const ends = lines.filter((l) => l.lineType === 'slot' && l.heldUntil).map((l) => Date.parse(l.heldUntil!));
|
||||
return ends.length ? Math.min(...ends) + clockOffset : null;
|
||||
});
|
||||
|
||||
async function callApi(body: Record<string, unknown>): Promise<Basket | null> {
|
||||
const res = await fetch('/api/basket', {
|
||||
method: 'POST',
|
||||
|
|
@ -31,13 +40,27 @@ export function createBasketStore(initial: Basket | null) {
|
|||
function applyBasket(basket: Basket | null) {
|
||||
lines = basket?.lines ?? [];
|
||||
status = basket?.status ?? 'active';
|
||||
clockOffset = clockOffsetOf(basket);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a basket change that can free or take slot places, then reload
|
||||
* page data so shop listings (places left, blocked times) match it.
|
||||
*/
|
||||
async function applySlotChange(basket: Basket | null) {
|
||||
applyBasket(basket);
|
||||
await invalidateAll();
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const res = await fetch('/api/basket');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const slotLines = () => lines.filter((l) => l.lineType === 'slot').length;
|
||||
const before = slotLines();
|
||||
applyBasket(data.basket);
|
||||
// Lapsed reservations were dropped: their places are free again.
|
||||
if (slotLines() < before) await invalidateAll();
|
||||
}
|
||||
|
||||
/** Overwrite local state from server-provided layout data. */
|
||||
|
|
@ -50,15 +73,20 @@ export function createBasketStore(initial: Basket | null) {
|
|||
}
|
||||
|
||||
async function addSlotLine(slotId: string) {
|
||||
applyBasket(await callApi({ action: 'add_slot', slotId }));
|
||||
await applySlotChange(await callApi({ action: 'add_slot', slotId }));
|
||||
}
|
||||
|
||||
async function updateQuantity(lineId: string, quantity: number) {
|
||||
applyBasket(await callApi({ action: 'update_quantity', lineId, quantity }));
|
||||
await applySlotChange(await callApi({ action: 'update_quantity', lineId, quantity }));
|
||||
}
|
||||
|
||||
async function removeLine(lineId: string) {
|
||||
applyBasket(await callApi({ action: 'remove_line', lineId }));
|
||||
await applySlotChange(await callApi({ action: 'remove_line', lineId }));
|
||||
}
|
||||
|
||||
/** Hold the basket's time slots for another 10 minutes. */
|
||||
async function renewHolds() {
|
||||
await applySlotChange(await callApi({ action: 'renew_holds' }));
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -74,15 +102,23 @@ export function createBasketStore(initial: Basket | null) {
|
|||
get status() {
|
||||
return status;
|
||||
},
|
||||
get holdDeadline() {
|
||||
return holdDeadline;
|
||||
},
|
||||
refresh,
|
||||
syncFrom,
|
||||
addItemLine,
|
||||
addSlotLine,
|
||||
updateQuantity,
|
||||
removeLine
|
||||
removeLine,
|
||||
renewHolds
|
||||
};
|
||||
}
|
||||
|
||||
function clockOffsetOf(basket: Basket | null) {
|
||||
return basket?.serverNow ? Date.now() - basket.serverNow : 0;
|
||||
}
|
||||
|
||||
export function setBasketContext(store: BasketStore) {
|
||||
setContext(BASKET_KEY, store);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { browser } from '$app/environment';
|
||||
import { goto } from '$app/navigation';
|
||||
import type { CheckoutBlockData } from '$shared/types';
|
||||
import { page } from '$app/state';
|
||||
import type { BasketLine, CheckoutBlockData } from '$shared/types';
|
||||
import { getBasketContext } from '$shared/basket.svelte';
|
||||
import { DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar';
|
||||
import { loadStripe } from '$shared/stripe-client';
|
||||
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
|
||||
|
||||
|
|
@ -38,23 +41,79 @@
|
|||
lastSig = sig;
|
||||
});
|
||||
|
||||
const currency = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const payLabel = $derived(
|
||||
payState === 'confirming'
|
||||
? 'Confirming…'
|
||||
: payState === 'creating'
|
||||
? 'Preparing payment…'
|
||||
: `Pay ${currency.format(basket.total)}`
|
||||
: `Pay ${formatPrice(basket.total)}`
|
||||
);
|
||||
|
||||
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||
|
||||
/** "Fri 15 Jan, 10:00" in the studio's timezone. */
|
||||
function formatSlotTime(iso: string) {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
return formatInstant(iso, timezone, { weekday: 'short', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
// ── Reservation countdown ───────────────────────────────────────────
|
||||
// Time slots are held for a while after being added (longer once payment
|
||||
// starts). Show how long is left, offer more time near the end, and say
|
||||
// so when a reservation runs out instead of the line silently vanishing.
|
||||
|
||||
/** Offer "keep my reservation" once less than this is left. */
|
||||
const RENEW_OFFER_MS = 3 * 60 * 1000;
|
||||
|
||||
// null until mounted, so the server render shows no (soon wrong) countdown.
|
||||
let now = $state<number | null>(null);
|
||||
onMount(() => {
|
||||
now = Date.now();
|
||||
const timer = setInterval(() => (now = Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
});
|
||||
|
||||
const holdLeftMs = $derived(now === null || basket.holdDeadline === null ? null : Math.max(0, basket.holdDeadline - now));
|
||||
const slotLineCount = $derived(basket.lines.filter((l) => l.lineType === 'slot').length);
|
||||
let renewing = $state(false);
|
||||
/** Reservations that ran out while this page was open, e.g. "Group class, Fri 15 Jan, 10:00". */
|
||||
let lapsed = $state<string[]>([]);
|
||||
let nextLapseCheck = 0;
|
||||
|
||||
function formatCountdown(ms: number) {
|
||||
const seconds = Math.ceil(ms / 1000);
|
||||
return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function describeLine(line: BasketLine) {
|
||||
return [line.itemName ?? 'A time slot', line.slotStart ? formatSlotTime(line.slotStart) : ''].filter(Boolean).join(', ');
|
||||
}
|
||||
|
||||
// At zero, reload the basket: the server drops the lapsed line. Retry every
|
||||
// few seconds in case its clock is slightly behind.
|
||||
$effect(() => {
|
||||
if (holdLeftMs !== 0 || now === null || now < nextLapseCheck) return;
|
||||
nextLapseCheck = now + 5000;
|
||||
void checkLapsed();
|
||||
});
|
||||
|
||||
async function checkLapsed() {
|
||||
const before = basket.lines.filter((l) => l.lineType === 'slot');
|
||||
await basket.refresh();
|
||||
const gone = before.filter((l) => !basket.lines.some((line) => line.id === l.id));
|
||||
if (gone.length) lapsed = [...lapsed, ...gone.map(describeLine)];
|
||||
}
|
||||
|
||||
async function renewHolds() {
|
||||
if (renewing) return;
|
||||
renewing = true;
|
||||
errorMsg = '';
|
||||
try {
|
||||
await basket.renewHolds();
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Could not extend your reservation.';
|
||||
} finally {
|
||||
renewing = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetPayment() {
|
||||
|
|
@ -115,6 +174,8 @@
|
|||
);
|
||||
}
|
||||
const { clientSecret } = await res.json();
|
||||
// Starting payment holds the slots longer; show the new countdown.
|
||||
await basket.refresh();
|
||||
|
||||
stripe = await loadStripe();
|
||||
if (!stripe) throw new Error('Payment system failed to load. Please refresh and try again.');
|
||||
|
|
@ -209,14 +270,59 @@
|
|||
<p class="mt-2 text-fg-body/70">{data.heading}</p>
|
||||
{/if}
|
||||
|
||||
{#if lapsed.length}
|
||||
<div class="mt-8 flex items-start justify-between gap-3 rounded-2xl border border-terracotta/40 bg-terracotta/10 px-5 py-4 text-sm text-charcoal" role="alert">
|
||||
<div>
|
||||
<p class="font-medium">
|
||||
{lapsed.length === 1 ? 'Your reservation ran out' : 'Some reservations ran out'}, so {lapsed.length === 1 ? 'it was' : 'they were'} taken out of your basket:
|
||||
</p>
|
||||
<ul class="mt-1 list-disc pl-5">
|
||||
{#each lapsed as description, i (i)}
|
||||
<li>{description}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<p class="mt-1 text-charcoal/70">You can pick the time again in the shop if it’s still free.</p>
|
||||
</div>
|
||||
<button type="button" class="shrink-0 font-bold" aria-label="Dismiss" onclick={() => (lapsed = [])}>✕</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if basket.lines.length === 0}
|
||||
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center">
|
||||
<p class="font-serif text-xl">Your basket is empty</p>
|
||||
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
|
||||
</div>
|
||||
{:else}
|
||||
{#if holdLeftMs !== null && slotLineCount}
|
||||
{@const ending = holdLeftMs < RENEW_OFFER_MS}
|
||||
<div
|
||||
class="mt-8 flex flex-wrap items-center justify-between gap-3 rounded-2xl border px-5 py-3 text-sm {ending
|
||||
? 'border-terracotta/40 bg-terracotta/10'
|
||||
: 'border-sage/30 bg-sage/10'}"
|
||||
role="timer"
|
||||
aria-live={ending ? 'polite' : 'off'}
|
||||
>
|
||||
<p>
|
||||
{slotLineCount === 1 ? 'Your time is' : 'Your times are'} reserved for
|
||||
<strong class="tabular-nums">{formatCountdown(holdLeftMs)}</strong>{ending
|
||||
? ' — after that it goes back to the shop.'
|
||||
: '.'}
|
||||
</p>
|
||||
{#if ending && payState !== 'confirming'}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-charcoal/20 bg-white px-4 py-1.5 font-medium transition hover:bg-charcoal/5 disabled:opacity-60"
|
||||
disabled={renewing}
|
||||
onclick={renewHolds}
|
||||
>
|
||||
{renewing ? 'Extending…' : 'Keep it 10 more minutes'}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Basket lines -->
|
||||
<ul class="mt-8 space-y-4">
|
||||
<ul class="{holdLeftMs !== null && slotLineCount ? 'mt-4' : 'mt-8'} space-y-4">
|
||||
{#each basket.lines as line (line.id)}
|
||||
{@const pending = pendingLines.has(line.id)}
|
||||
<li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
|
||||
|
|
@ -237,10 +343,11 @@
|
|||
{#if line.lineType === 'slot' && line.slotStart}
|
||||
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
|
||||
{/if}
|
||||
<p class="text-sm text-fg-body/70">{currency.format(line.itemPrice ?? 0)}</p>
|
||||
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice ?? 0)}</p>
|
||||
</div>
|
||||
|
||||
{#if line.lineType === 'item'}
|
||||
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
|
||||
{#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1}
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -265,7 +372,7 @@
|
|||
{/if}
|
||||
|
||||
<p class="w-20 shrink-0 text-right font-medium">
|
||||
{currency.format((line.itemPrice ?? 0) * line.quantity)}
|
||||
{formatPrice((line.itemPrice ?? 0) * line.quantity)}
|
||||
</p>
|
||||
|
||||
<button
|
||||
|
|
@ -285,7 +392,7 @@
|
|||
<div class="mt-6 rounded-2xl border border-charcoal/10 bg-white p-5">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-fg-body/70">Subtotal</span>
|
||||
<span class="font-serif text-xl font-bold">{currency.format(basket.total)}</span>
|
||||
<span class="font-serif text-xl font-bold">{formatPrice(basket.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -367,7 +474,7 @@
|
|||
</div>
|
||||
{/if}
|
||||
|
||||
{#if basketChanged}
|
||||
{#if basketChanged && !lapsed.length}
|
||||
<p class="mt-4 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm">
|
||||
Basket changed — please press Pay again.
|
||||
</p>
|
||||
|
|
@ -387,7 +494,7 @@
|
|||
disabled={payState === 'confirming'}
|
||||
onclick={confirmPayment}
|
||||
>
|
||||
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${currency.format(basket.total)}`}
|
||||
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${formatPrice(basket.total)}`}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
<script lang="ts">
|
||||
import type { ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
||||
import { page } from '$app/state';
|
||||
import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
|
||||
import { getBasketContext } from '$shared/basket.svelte';
|
||||
import { getCurrentAndNextMonths } from '$shared/calendar';
|
||||
import { DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey } from '$shared/calendar';
|
||||
import { formatDateKey } from '$shared/slots';
|
||||
|
||||
let { data = {}, items = [], slots = [] } = $props<{
|
||||
data: ShopBlockData;
|
||||
|
|
@ -20,14 +22,16 @@
|
|||
errorMsg = $state<string | null>(null);
|
||||
justAdded = $state(false);
|
||||
pendingSlotId = $state<string | null>(null);
|
||||
/** Months from the current one to the first month shown in the picker. */
|
||||
monthOffset = $state(0);
|
||||
}
|
||||
|
||||
let cardStates = $state<Record<string, CardState>>({});
|
||||
|
||||
const months = getCurrentAndNextMonths();
|
||||
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
|
||||
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
/** The picker shows this many months side by side; the arrows move one month. */
|
||||
const MONTHS_SHOWN = 2;
|
||||
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
||||
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||
|
||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||
let result: ItemRecord[] = items;
|
||||
|
|
@ -43,13 +47,23 @@
|
|||
return result;
|
||||
});
|
||||
|
||||
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
|
||||
// The listing leaves out full slots — including ones whose last places are
|
||||
// in this visitor's own basket. Add those back (no places left) so the
|
||||
// visitor still sees their times and can change or drop their places.
|
||||
let shownSlots = $derived.by<SlotRecord[]>(() => {
|
||||
const listed = new Set(slots.map((s: SlotRecord) => s.id));
|
||||
const own = basket.lines
|
||||
.filter((l) => l.lineType === 'slot' && l.slot && !listed.has(l.slot) && l.slotStart && Date.parse(l.slotStart) > Date.now())
|
||||
.map((l) => ({ id: l.slot!, item: l.item, start: l.slotStart!, end: l.slotEnd ?? l.slotStart!, capacity: l.slotCapacity ?? 1, free: 0 }));
|
||||
return own.length ? [...slots, ...own] : slots;
|
||||
});
|
||||
|
||||
// item id -> day key ('YYYY-MM-DD', in the studio's timezone) -> slots on that day, sorted by start time
|
||||
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
|
||||
const map = new Map<string, Map<string, SlotRecord[]>>();
|
||||
for (const slot of slots) {
|
||||
const day = new Date(slot.start);
|
||||
if (Number.isNaN(day.getTime())) continue;
|
||||
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
|
||||
for (const slot of shownSlots) {
|
||||
const key = zonedDateKey(slot.start, timezone);
|
||||
if (!key) continue;
|
||||
let itemMap = map.get(slot.item);
|
||||
if (!itemMap) {
|
||||
itemMap = new Map();
|
||||
|
|
@ -69,6 +83,18 @@
|
|||
|
||||
let isList = $derived(data.layout === 'list');
|
||||
|
||||
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
|
||||
function monthOffsetOf(key: string) {
|
||||
const today = new Date();
|
||||
const [year, month] = key.split('-').map(Number);
|
||||
return year * 12 + (month - 1) - (today.getFullYear() * 12 + today.getMonth());
|
||||
}
|
||||
|
||||
function pickerMonths(offset: number) {
|
||||
const first = addMonths(startOfMonth(new Date()), offset);
|
||||
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1));
|
||||
}
|
||||
|
||||
// Lazily create card state for whatever items are rendered.
|
||||
$effect(() => {
|
||||
for (const item of visibleItems) {
|
||||
|
|
@ -83,6 +109,15 @@
|
|||
state.errorMsg = null;
|
||||
state.justAdded = false;
|
||||
state.selectedDayKey = null;
|
||||
state.monthOffset = 0;
|
||||
}
|
||||
|
||||
/** Show the month of the first available day and select it. */
|
||||
function showFirstAvailable(itemId: string, key: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state) return;
|
||||
state.monthOffset = Math.max(0, monthOffsetOf(key));
|
||||
state.selectedDayKey = key;
|
||||
}
|
||||
|
||||
function errorMessage(e: unknown, fallback: string) {
|
||||
|
|
@ -110,6 +145,8 @@
|
|||
state.pendingSlotId = slotId;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
// The store reloads the listing afterwards: a booking can block other
|
||||
// times (one practitioner) or fill a group session.
|
||||
await basket.addSlotLine(slotId);
|
||||
state.justAdded = true;
|
||||
} catch (e) {
|
||||
|
|
@ -120,8 +157,31 @@
|
|||
}
|
||||
}
|
||||
|
||||
/** One place more or fewer in a group session already in the basket (0 removes it). */
|
||||
async function changeSeats(itemId: string, line: BasketLine, delta: number) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state || state.adding) return;
|
||||
state.adding = true;
|
||||
state.pendingSlotId = line.slot;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
const seats = line.quantity + delta;
|
||||
if (seats < 1) await basket.removeLine(line.id);
|
||||
else await basket.updateQuantity(line.id, seats);
|
||||
} catch (e) {
|
||||
state.errorMsg = errorMessage(e, 'Could not change the number of places.');
|
||||
} finally {
|
||||
state.adding = false;
|
||||
state.pendingSlotId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(iso: string) {
|
||||
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
|
||||
return formatInstant(iso, timezone, { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function placesLeft(free: number) {
|
||||
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left';
|
||||
}
|
||||
</script>
|
||||
|
||||
|
|
@ -174,7 +234,7 @@
|
|||
{/if}
|
||||
|
||||
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
|
||||
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
|
||||
<span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price)}</span>
|
||||
{#if isService && item.duration != null}
|
||||
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||
|
|
@ -241,8 +301,53 @@
|
|||
</div>
|
||||
|
||||
{#if isService && ui?.pickerOpen && itemSlotsByDay}
|
||||
{@const availableKeys = [...itemSlotsByDay.keys()].sort()}
|
||||
{@const months = pickerMonths(ui.monthOffset)}
|
||||
{@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey}
|
||||
{@const shownTo = months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey}
|
||||
{@const anyShown = availableKeys.some((key) => key >= shownFrom && key <= shownTo)}
|
||||
{@const lastOffset = monthOffsetOf(availableKeys[availableKeys.length - 1]) - (MONTHS_SHOWN - 1)}
|
||||
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
|
||||
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
|
||||
<div class="mb-3 flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
|
||||
aria-label="Previous month"
|
||||
disabled={ui.monthOffset <= 0}
|
||||
onclick={() => ui.monthOffset--}
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
<p class="text-sm font-medium text-charcoal/70">Select a date</p>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
|
||||
aria-label="Next month"
|
||||
disabled={ui.monthOffset >= lastOffset}
|
||||
onclick={() => ui.monthOffset++}
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if !anyShown && availableKeys.length}
|
||||
<!-- Nothing in the months on screen: say when the next date is, so
|
||||
nobody books January thinking it is this month. -->
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal">
|
||||
<span>
|
||||
{availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'}
|
||||
<strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark"
|
||||
onclick={() => showFirstAvailable(item.id, availableKeys.find((key) => key > shownTo) ?? availableKeys[0])}
|
||||
>
|
||||
Go to {availableKeys[0] > shownTo ? 'first' : 'next'} available date →
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grid gap-6 sm:grid-cols-2">
|
||||
{#each months as month (month.label)}
|
||||
<div>
|
||||
|
|
@ -278,31 +383,64 @@
|
|||
|
||||
{#if ui.selectedDayKey}
|
||||
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
|
||||
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
|
||||
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">
|
||||
Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each daySlots as slot (slot.id)}
|
||||
{@const slotInBasket = basket.lines.some((l) => l.slot === slot.id)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={slotInBasket || ui.adding}
|
||||
onclick={() => addSlot(item.id, slot.id)}
|
||||
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
|
||||
? '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 &&
|
||||
!slotInBasket
|
||||
? 'cursor-wait'
|
||||
: ''}"
|
||||
>
|
||||
{#if ui.pendingSlotId === slot.id}
|
||||
<span class="loading loading-spinner loading-xs"></span>
|
||||
{/if}
|
||||
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{slotInBasket
|
||||
? ' · In basket'
|
||||
: ''}
|
||||
</button>
|
||||
{@const line = basket.lines.find((l) => l.slot === slot.id)}
|
||||
{@const isGroup = slot.capacity > 1}
|
||||
{@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
|
||||
{#if isGroup && line}
|
||||
<!-- Places in a group session already in the basket: − / + -->
|
||||
<div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark">
|
||||
<span>{label} · {placesLeft(slot.free)}</span>
|
||||
<span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
|
||||
aria-label="One place fewer"
|
||||
disabled={ui.adding}
|
||||
onclick={() => changeSeats(item.id, line, -1)}
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
|
||||
{#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if}
|
||||
<span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
|
||||
aria-label="One place more"
|
||||
disabled={ui.adding || slot.free <= 0}
|
||||
onclick={() => changeSeats(item.id, line, 1)}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!!line || ui.adding}
|
||||
onclick={() => addSlot(item.id, slot.id)}
|
||||
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {line
|
||||
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
|
||||
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
|
||||
!line
|
||||
? 'cursor-wait'
|
||||
: ''}"
|
||||
>
|
||||
{#if ui.pendingSlotId === slot.id}
|
||||
<span class="loading loading-spinner loading-xs"></span>
|
||||
{/if}
|
||||
{label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
{:else if anyShown}
|
||||
<p class="mt-4 text-sm text-charcoal/60">
|
||||
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -48,6 +48,31 @@ export function dateInputToPocketBase(value: string, allDay = true, timeZone = '
|
|||
return `${value.slice(0, 10)} 00:00:00.000Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Locale for every date, time and price shown to people: day-month-year and
|
||||
* a 24-hour clock. Fixed (not the visitor's or server's default, which is
|
||||
* en-US in the container) so the server render and the browser agree.
|
||||
*/
|
||||
export const DISPLAY_LOCALE = 'en-GB';
|
||||
|
||||
/** Fallback when no SITE_TIMEZONE reaches the page. */
|
||||
export const DEFAULT_TIMEZONE = 'Europe/Oslo';
|
||||
|
||||
export function formatPrice(amount: number) {
|
||||
return new Intl.NumberFormat(DISPLAY_LOCALE, { style: 'currency', currency: 'EUR' }).format(amount);
|
||||
}
|
||||
|
||||
/** Format an instant in `timeZone` with the display locale. */
|
||||
export function formatInstant(value: string | null | undefined, timeZone: string, options: Intl.DateTimeFormatOptions) {
|
||||
const date = parseInstant(value);
|
||||
return date ? new Intl.DateTimeFormat(DISPLAY_LOCALE, { ...options, timeZone }).format(date) : '';
|
||||
}
|
||||
|
||||
/** The calendar date (`YYYY-MM-DD`) of an instant in `timeZone`. */
|
||||
export function zonedDateKey(value: string | null | undefined, timeZone: string) {
|
||||
return toZonedDatetimeInput(value, timeZone).slice(0, 10);
|
||||
}
|
||||
|
||||
// ── Site-timezone helpers ──────────────────────────────────────────────
|
||||
// Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so
|
||||
// what the admin types is what customers book, and the server render (UTC
|
||||
|
|
@ -114,14 +139,14 @@ export function toZonedDatetimeInput(value: string | null | undefined, timeZone:
|
|||
export function formatDateTime(value: string | null | undefined, timeZone: string) {
|
||||
const date = parseInstant(value);
|
||||
if (!date) return '';
|
||||
return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
|
||||
return new Intl.DateTimeFormat(DISPLAY_LOCALE, { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
|
||||
}
|
||||
|
||||
/** "10:00" in `timeZone`. */
|
||||
export function formatTime(value: string | null | undefined, timeZone: string) {
|
||||
const date = parseInstant(value);
|
||||
if (!date) return '';
|
||||
return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date);
|
||||
return new Intl.DateTimeFormat(DISPLAY_LOCALE, { timeZone, timeStyle: 'short' }).format(date);
|
||||
}
|
||||
|
||||
export function parseEventDate(value?: string | null) {
|
||||
|
|
@ -184,7 +209,7 @@ export function createCalendarMonth(monthDate: Date, reference = new Date(), wee
|
|||
|
||||
return {
|
||||
date: first,
|
||||
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
|
||||
label: first.toLocaleDateString(DISPLAY_LOCALE, { month: 'long', year: 'numeric' }),
|
||||
days
|
||||
};
|
||||
}
|
||||
|
|
@ -264,7 +289,7 @@ export function formatEventDateRange(event: CalendarEventRecord) {
|
|||
const start = parseEventDate(event.start);
|
||||
const end = parseEventDate(event.end);
|
||||
if (!start) return '';
|
||||
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
|
||||
const formatter = new Intl.DateTimeFormat(DISPLAY_LOCALE, { month: 'short', day: 'numeric' });
|
||||
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
|
||||
return `${formatter.format(start)} – ${formatter.format(end)}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,20 +3,18 @@ import { getFileUrl } from '../pb';
|
|||
import type { ItemRecord, SlotRecord } from '../types';
|
||||
|
||||
/**
|
||||
* Active items and future available slots, shaped for the Shop/Checkout
|
||||
* Active items and bookable future slots, shaped for the Shop/Checkout
|
||||
* blocks. Used by the public layout and the admin draft preview so both
|
||||
* render the same shop.
|
||||
*
|
||||
* Works with an anonymous client: the API rules expose active items,
|
||||
* available slots and media publicly. Errors propagate.
|
||||
* Works with an anonymous client: active items and media are public, and
|
||||
* slots come from the shop hook (GET /api/shop/slots), which leaves out
|
||||
* full slots and slots blocked by an overlapping booking. Errors propagate.
|
||||
*/
|
||||
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> {
|
||||
const [itemRecords, slotRecords] = await Promise.all([
|
||||
const [itemRecords, { slots }] = await Promise.all([
|
||||
pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }),
|
||||
pb.collection('slots').getFullList({
|
||||
filter: pb.filter("status = 'available' && start >= {:now}", { now: new Date() }),
|
||||
sort: 'start'
|
||||
})
|
||||
pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null })
|
||||
]);
|
||||
|
||||
const items = itemRecords.map((record): ItemRecord => {
|
||||
|
|
@ -31,22 +29,11 @@ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[
|
|||
type: record.type,
|
||||
stock: record.stock ?? null,
|
||||
duration: record.duration ?? null,
|
||||
bufferMinutes: record.bufferMinutes ?? null,
|
||||
capacity: record.capacity ?? null,
|
||||
active: record.active
|
||||
};
|
||||
});
|
||||
|
||||
const slots = slotRecords.map(
|
||||
(record): SlotRecord => ({
|
||||
id: record.id,
|
||||
item: record.item,
|
||||
start: record.start,
|
||||
end: record.end || '',
|
||||
status: record.status,
|
||||
heldUntil: record.heldUntil || null,
|
||||
order: record.order || null,
|
||||
notes: record.notes || ''
|
||||
})
|
||||
);
|
||||
|
||||
return { items, slots };
|
||||
}
|
||||
|
|
|
|||
228
packages/shared/src/slots.ts
Normal file
228
packages/shared/src/slots.ts
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
// Bulk slot planning — pure functions shared by the admin's generate/copy
|
||||
// forms (client hints) and their server actions (what actually gets created).
|
||||
//
|
||||
// Dates are calendar keys (`YYYY-MM-DD`) and times are wall-clock `HH:MM` in
|
||||
// the site's timezone; they become UTC instants only at the very end, via
|
||||
// zonedInputToIso, so a run across a DST change still starts at 09:00.
|
||||
|
||||
import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar';
|
||||
|
||||
/** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */
|
||||
export type TimeWindow = { from: string; to: string };
|
||||
|
||||
export type PlannedSlot = { start: string; end: string };
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const DATE_KEY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const TIME_RE = /^(\d{2}):(\d{2})$/;
|
||||
|
||||
/** Weekday labels Monday-first, with their `Date.getUTCDay()` number. */
|
||||
export const WEEKDAYS = [
|
||||
{ day: 1, label: 'Mon' },
|
||||
{ day: 2, label: 'Tue' },
|
||||
{ day: 3, label: 'Wed' },
|
||||
{ day: 4, label: 'Thu' },
|
||||
{ day: 5, label: 'Fri' },
|
||||
{ day: 6, label: 'Sat' },
|
||||
{ day: 0, label: 'Sun' }
|
||||
];
|
||||
|
||||
/** What a bulk action reports back: a preview to confirm, or the outcome. */
|
||||
export type BulkResult = {
|
||||
action: 'generate' | 'copy' | 'clear';
|
||||
intent: 'preview' | 'done';
|
||||
/** Slots that will be (preview) or were (done) created/deleted. */
|
||||
count: number;
|
||||
skippedOverlap: number;
|
||||
skippedPast: number;
|
||||
/** clear only: booked or currently-held slots that are left alone. */
|
||||
kept: number;
|
||||
firstStart: string;
|
||||
lastStart: string;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A slot with its places and blocking, as the shop hook reports it to the
|
||||
* admin (GET /api/shop/slots?detail=1). Places are taken by paid orders
|
||||
* (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy`
|
||||
* is the overlapping slot whose booking/hold blocks this one.
|
||||
*/
|
||||
export type SlotDetail = PlannedSlot & {
|
||||
id: string;
|
||||
item: string;
|
||||
itemName: string;
|
||||
capacity: number;
|
||||
notes: string;
|
||||
booked: number;
|
||||
held: number;
|
||||
blockedBy: string;
|
||||
};
|
||||
|
||||
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
|
||||
|
||||
export const SLOT_STATE_LABELS: Record<SlotState, string> = {
|
||||
free: 'Available',
|
||||
held: 'In a basket',
|
||||
booked: 'Booked',
|
||||
full: 'Full',
|
||||
blocked: 'Blocked'
|
||||
};
|
||||
|
||||
/**
|
||||
* `full` only when paid bookings fill a group; a slot whose last places are
|
||||
* in baskets reads `held`, since it frees up again if those holds lapse.
|
||||
*/
|
||||
export function slotState(slot: Pick<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): SlotState {
|
||||
if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked';
|
||||
if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held';
|
||||
if (slot.booked) return 'booked';
|
||||
if (slot.held) return 'held';
|
||||
return slot.blockedBy ? 'blocked' : 'free';
|
||||
}
|
||||
|
||||
/** One generate/copy run may create at most this many slots. */
|
||||
export const MAX_BULK_SLOTS = 1000;
|
||||
|
||||
function keyToUtcMs(key: string) {
|
||||
const m = DATE_KEY_RE.exec(key);
|
||||
if (!m) return null;
|
||||
const ms = Date.UTC(+m[1], +m[2] - 1, +m[3]);
|
||||
return Number.isNaN(ms) ? null : ms;
|
||||
}
|
||||
|
||||
function utcMsToKey(ms: number) {
|
||||
return new Date(ms).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function isDateKey(value: string) {
|
||||
return keyToUtcMs(value) !== null;
|
||||
}
|
||||
|
||||
/** `2026-11-03` + 7 → `2026-11-10` (pure calendar arithmetic, no timezone). */
|
||||
export function addDaysToKey(key: string, days: number) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? '' : utcMsToKey(ms + days * DAY_MS);
|
||||
}
|
||||
|
||||
/** 0 = Sunday … 6 = Saturday, for a calendar date key. */
|
||||
export function weekdayOfKey(key: string) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? -1 : new Date(ms).getUTCDay();
|
||||
}
|
||||
|
||||
/** The Monday on or before `key`. */
|
||||
export function mondayOfKey(key: string) {
|
||||
const weekday = weekdayOfKey(key);
|
||||
return weekday < 0 ? '' : addDaysToKey(key, -((weekday + 6) % 7));
|
||||
}
|
||||
|
||||
/** Calendar date keys from `fromKey` to `toKey`, inclusive. */
|
||||
export function dateKeysBetween(fromKey: string, toKey: string) {
|
||||
const from = keyToUtcMs(fromKey);
|
||||
const to = keyToUtcMs(toKey);
|
||||
if (from === null || to === null) return [];
|
||||
const keys: string[] = [];
|
||||
for (let ms = from; ms <= to; ms += DAY_MS) keys.push(utcMsToKey(ms));
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** `2026-11` → the Monday-first grid of date keys covering that month (whole weeks). */
|
||||
export function monthGridKeys(month: string) {
|
||||
const first = `${month}-01`;
|
||||
if (!isDateKey(first)) return [];
|
||||
const [year, monthNumber] = month.split('-').map(Number);
|
||||
const nextFirst = monthNumber === 12 ? `${year + 1}-01-01` : `${year}-${String(monthNumber + 1).padStart(2, '0')}-01`;
|
||||
const gridStart = mondayOfKey(first);
|
||||
const gridEnd = addDaysToKey(mondayOfKey(addDaysToKey(nextFirst, -1)), 6);
|
||||
return dateKeysBetween(gridStart, gridEnd);
|
||||
}
|
||||
|
||||
/** `2026-11` + 1 → `2026-12`. */
|
||||
export function addMonthsToKey(month: string, months: number) {
|
||||
const [year, monthNumber] = month.split('-').map(Number);
|
||||
const index = year * 12 + (monthNumber - 1) + months;
|
||||
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Format a date key with fixed locale (SSR and browser agree), e.g. "Tuesday 3 November". */
|
||||
export function formatDateKey(key: string, options: Intl.DateTimeFormatOptions) {
|
||||
const ms = keyToUtcMs(key);
|
||||
return ms === null ? '' : new Intl.DateTimeFormat(DISPLAY_LOCALE, { ...options, timeZone: 'UTC' }).format(ms);
|
||||
}
|
||||
|
||||
/** `09:30` → 570, or null. */
|
||||
export function timeToMinutes(value: string) {
|
||||
const m = TIME_RE.exec(value);
|
||||
if (!m || +m[1] > 23 || +m[2] > 59) return null;
|
||||
return +m[1] * 60 + +m[2];
|
||||
}
|
||||
|
||||
export function minutesToTime(minutes: number) {
|
||||
return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start times within the windows: a new appointment starts every
|
||||
* `duration + buffer` minutes and must end by the window's end (the
|
||||
* get-ready time after the last one may run past it).
|
||||
*/
|
||||
export function startTimesInWindows(windows: TimeWindow[], durationMinutes: number, bufferMinutes: number) {
|
||||
const step = durationMinutes + Math.max(0, bufferMinutes);
|
||||
if (durationMinutes <= 0) return [];
|
||||
const times = new Set<number>();
|
||||
for (const window of windows) {
|
||||
const from = timeToMinutes(window.from);
|
||||
const to = timeToMinutes(window.to);
|
||||
if (from === null || to === null) continue;
|
||||
for (let t = from; t + durationMinutes <= to; t += step) times.add(t);
|
||||
}
|
||||
return [...times].sort((a, b) => a - b).map(minutesToTime);
|
||||
}
|
||||
|
||||
export type GeneratePlanInput = {
|
||||
fromDate: string;
|
||||
toDate: string;
|
||||
/** `Date.getUTCDay()` numbers (0 = Sunday) of the days to fill. */
|
||||
weekdays: number[];
|
||||
windows: TimeWindow[];
|
||||
durationMinutes: number;
|
||||
bufferMinutes: number;
|
||||
timeZone: string;
|
||||
};
|
||||
|
||||
/** Every slot the generator would create, before skipping overlaps/past ones. */
|
||||
export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] {
|
||||
const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes);
|
||||
const days = new Set(input.weekdays);
|
||||
const slots: PlannedSlot[] = [];
|
||||
for (const key of dateKeysBetween(input.fromDate, input.toDate)) {
|
||||
if (!days.has(weekdayOfKey(key))) continue;
|
||||
for (const time of times) {
|
||||
const start = zonedInputToIso(`${key}T${time}`, input.timeZone);
|
||||
if (!start) continue;
|
||||
slots.push({ start, end: new Date(Date.parse(start) + input.durationMinutes * 60_000).toISOString() });
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
/** The same wall-clock time `days` later in `timeZone` (so 09:00 stays 09:00 across DST). */
|
||||
export function shiftByDays(iso: string, days: number, timeZone: string) {
|
||||
const local = toZonedDatetimeInput(iso, timeZone);
|
||||
if (!local) return '';
|
||||
const key = addDaysToKey(local.slice(0, 10), days);
|
||||
return key ? zonedInputToIso(`${key}${local.slice(10)}`, timeZone) : '';
|
||||
}
|
||||
|
||||
/** PocketBase dates look like `2026-11-03 08:00:00.000Z`; this parses them and ISO strings. */
|
||||
export function instantMs(value: string) {
|
||||
return Date.parse(String(value || '').replace(' ', 'T'));
|
||||
}
|
||||
|
||||
/** Whether `[start, end)` overlaps any of `ranges` (touching ends don't count). */
|
||||
export function overlapsAny(slot: PlannedSlot, ranges: PlannedSlot[]) {
|
||||
const start = instantMs(slot.start);
|
||||
const end = instantMs(slot.end);
|
||||
return ranges.some((range) => start < instantMs(range.end) && end > instantMs(range.start));
|
||||
}
|
||||
|
|
@ -110,20 +110,22 @@ export type ItemRecord = {
|
|||
type: ItemType;
|
||||
stock: number | null;
|
||||
duration: number | null; // minutes, for item_with_time
|
||||
bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots
|
||||
capacity: number | null; // places per slot (default for new slots; >1 = group session)
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
export type SlotStatus = 'available' | 'held' | 'booked';
|
||||
|
||||
/**
|
||||
* A bookable slot as the shop lists it (GET /api/shop/slots): only slots
|
||||
* with places left that no overlapping booking blocks.
|
||||
*/
|
||||
export type SlotRecord = {
|
||||
id: string;
|
||||
item: string; // item id
|
||||
start: string;
|
||||
end: string;
|
||||
status: SlotStatus;
|
||||
heldUntil: string | null;
|
||||
order: string | null;
|
||||
notes: string;
|
||||
capacity: number; // places in total
|
||||
free: number; // places still bookable
|
||||
};
|
||||
|
||||
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
||||
|
|
@ -141,6 +143,9 @@ export type BasketLine = {
|
|||
itemImageUrl?: string;
|
||||
slotStart?: string;
|
||||
slotEnd?: string;
|
||||
slotCapacity?: number;
|
||||
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
|
||||
heldUntil?: string;
|
||||
};
|
||||
|
||||
export type Basket = {
|
||||
|
|
@ -151,6 +156,8 @@ export type Basket = {
|
|||
customerDetails: CustomerDetails | null;
|
||||
stripePaymentIntentId: string | null;
|
||||
lines: BasketLine[];
|
||||
/** Server clock (epoch ms) when this was read, so browsers with a wrong clock count holds down correctly. */
|
||||
serverNow?: number;
|
||||
};
|
||||
|
||||
export type CustomerDetails = {
|
||||
|
|
|
|||
|
|
@ -331,6 +331,8 @@
|
|||
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] },
|
||||
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||
{ "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
|
||||
{ "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true },
|
||||
{ "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
|
||||
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} },
|
||||
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
|
||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
|
|
@ -344,8 +346,8 @@
|
|||
"name": "slots",
|
||||
"type": "base",
|
||||
"system": false,
|
||||
"listRule": "status = 'available' || @request.auth.id != ''",
|
||||
"viewRule": "status = 'available' || @request.auth.id != ''",
|
||||
"listRule": "@request.auth.id != ''",
|
||||
"viewRule": "@request.auth.id != ''",
|
||||
"createRule": "@request.auth.id != ''",
|
||||
"updateRule": "@request.auth.id != ''",
|
||||
"deleteRule": "@request.auth.id != ''",
|
||||
|
|
@ -354,16 +356,13 @@
|
|||
{ "id": "rel_slotitem001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||
{ "id": "date_slotstart0", "name": "start", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||
{ "id": "date_slotend000", "name": "end", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||
{ "id": "sel_slotstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["available", "held", "booked"] },
|
||||
{ "id": "date_slotheldun0", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||
{ "id": "rel_slotorder01", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||
{ "id": "num_slotcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
|
||||
{ "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } },
|
||||
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
|
||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
],
|
||||
"indexes": [
|
||||
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)",
|
||||
"CREATE INDEX `idx_slots_status` ON `slots` (`status`)"
|
||||
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)"
|
||||
],
|
||||
"autodate": true,
|
||||
"options": {}
|
||||
|
|
@ -411,12 +410,13 @@
|
|||
{ "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||
{ "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
|
||||
{ "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] },
|
||||
{ "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" },
|
||||
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
|
||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
],
|
||||
"indexes": [
|
||||
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
|
||||
"CREATE UNIQUE INDEX `idx_basket_lines_slot_unique` ON `basket_lines` (`slot`) WHERE `slot` != ''"
|
||||
"CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)"
|
||||
],
|
||||
"autodate": true,
|
||||
"options": {}
|
||||
|
|
@ -475,7 +475,8 @@
|
|||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||
],
|
||||
"indexes": [
|
||||
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)"
|
||||
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)",
|
||||
"CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)"
|
||||
],
|
||||
"autodate": true,
|
||||
"options": {}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,18 @@
|
|||
/// treats its input as untrusted. The basket id acts as the customer's
|
||||
/// bearer token, exactly like the cookie it comes from.
|
||||
|
||||
// Slot availability (seats + cross-service blocking, see lib.js). Anyone
|
||||
// gets the bookable future slots; a signed-in admin can ask for `detail`.
|
||||
routerAdd('GET', '/api/shop/slots', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
const query = e.request.url.query();
|
||||
if (query.get('detail')) {
|
||||
if (!e.auth) throw new UnauthorizedError('Sign in to see slot details');
|
||||
return e.json(200, { slots: 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) });
|
||||
});
|
||||
|
||||
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
shop.sweepExpiredHolds($app);
|
||||
|
|
|
|||
|
|
@ -55,30 +55,188 @@ function conflict(message) {
|
|||
return new ApiError(409, message);
|
||||
}
|
||||
|
||||
/** Epoch ms → PocketBase's stored datetime format, for comparing dates in filters. */
|
||||
function pbDate(ms) {
|
||||
return new Date(ms).toISOString().replace('T', ' ');
|
||||
}
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
// ── Slot availability ───────────────────────────────────────────────────
|
||||
//
|
||||
// Nothing about bookings is stored on a slot. Its seats are taken by paid
|
||||
// order lines and by basket lines whose hold (`heldUntil`) hasn't lapsed;
|
||||
// it has `capacity` seats (1 for a one-to-one massage, more for a group).
|
||||
//
|
||||
// One practitioner works all services, so a slot with any seat taken
|
||||
// BLOCKS every other slot it overlaps — whatever the service — including
|
||||
// each service's get-ready time after it. The client can offer three
|
||||
// massages at 10:00; once one is booked (or in a basket), the others go.
|
||||
|
||||
/**
|
||||
* Occupancy and blocking for the slots starting in [rangeStart, rangeEnd) (epoch ms).
|
||||
* `options.excludeLineId` leaves one basket line's seats out (used when
|
||||
* changing that line's quantity). Must run inside a transaction when the
|
||||
* result decides a write: PocketBase runs transactions one at a time, so
|
||||
* the check and the write can't interleave with another customer's.
|
||||
*/
|
||||
function slotStates(app, rangeStart, rangeEnd, options) {
|
||||
const opts = options || {};
|
||||
// Slots just outside the range can still block ones inside it.
|
||||
const range = { from: pbDate(rangeStart - DAY_MS), to: pbDate(rangeEnd + DAY_MS) };
|
||||
const records = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start');
|
||||
if (!records.length) return [];
|
||||
|
||||
const items = {};
|
||||
const byId = {};
|
||||
const states = records.map((record) => {
|
||||
const itemId = record.getString('item');
|
||||
if (!(itemId in items)) items[itemId] = findOrNull(app, 'items', itemId);
|
||||
const item = items[itemId];
|
||||
const start = toMs(record.getString('start'));
|
||||
const storedEnd = toMs(record.getString('end'));
|
||||
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,
|
||||
end,
|
||||
readyAt: end + Math.max(0, item ? item.getInt('bufferMinutes') : 0) * 60000,
|
||||
capacity: Math.max(1, record.getInt('capacity')),
|
||||
notes: record.getString('notes'),
|
||||
booked: 0,
|
||||
held: 0,
|
||||
blockedBy: ''
|
||||
};
|
||||
byId[record.id] = state;
|
||||
return state;
|
||||
});
|
||||
|
||||
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);
|
||||
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 slotState(app, slotId, options) {
|
||||
const record = findOrNull(app, 'slots', slotId);
|
||||
if (!record) return null;
|
||||
const start = toMs(record.getString('start'));
|
||||
return slotStates(app, start, start + 1, options).find((s) => s.id === slotId) || null;
|
||||
}
|
||||
|
||||
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 —
|
||||
* for the signed-in admin. `query`: from/to (ISO), optional item, or id.
|
||||
*/
|
||||
function slotDetails(app, query) {
|
||||
let states;
|
||||
if (query.id) {
|
||||
const state = slotState(app, String(query.id));
|
||||
states = state ? [state] : [];
|
||||
} else {
|
||||
const from = toMs(query.from);
|
||||
const to = toMs(query.to);
|
||||
if (Number.isNaN(from) || Number.isNaN(to) || to <= from) throw new BadRequestError('from and to are required');
|
||||
if (to - from > 400 * DAY_MS) throw new BadRequestError('Range too long');
|
||||
states = slotStates(app, from, to);
|
||||
if (query.item) states = states.filter((s) => s.item === query.item);
|
||||
}
|
||||
return states.map((s) => ({
|
||||
id: s.id,
|
||||
item: s.item,
|
||||
itemName: s.itemName,
|
||||
start: new Date(s.start).toISOString(),
|
||||
end: new Date(s.end).toISOString(),
|
||||
capacity: s.capacity,
|
||||
notes: s.notes,
|
||||
booked: s.booked,
|
||||
held: s.held,
|
||||
blockedBy: s.blockedBy
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a slot can take `seats` more seats; returns an ApiError to throw,
|
||||
* or null. Call inside the transaction that then writes the hold.
|
||||
*/
|
||||
function seatProblem(state, seats) {
|
||||
if (!state || !state.bookable) return new NotFoundError('Slot not found');
|
||||
if (state.start <= Date.now()) return conflict('This time has already passed — please pick another');
|
||||
if (state.blockedBy) return conflict('This time is no longer available — please pick another');
|
||||
const free = freeSeats(state);
|
||||
if (seats > free) {
|
||||
return conflict(free <= 0 ? 'This time is fully booked — please pick another' : `Only ${free} place${free === 1 ? '' : 's'} left at this time`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing
|
||||
* is written) or nothing to commit. Unexpected failures become `fallback`.
|
||||
*/
|
||||
function guardedTransaction(app, fallback, fn) {
|
||||
let refusal = null;
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
refusal = fn(tx) || null;
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[shop]', fallback, e);
|
||||
throw conflict(fallback);
|
||||
}
|
||||
if (refusal) throw refusal;
|
||||
}
|
||||
|
||||
// ── Holds and baskets ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Release slots whose hold has lapsed (dropping the basket lines holding
|
||||
* them) and abandon expired baskets. Runs every minute (cron) and before
|
||||
* basket/checkout operations, so expiry is exact where it matters.
|
||||
* Drop basket lines whose slot hold has lapsed (their seats are already
|
||||
* free — availability only counts live holds — this is just tidying) and
|
||||
* abandon expired baskets. Runs every minute (cron) and before
|
||||
* basket/checkout operations.
|
||||
*/
|
||||
function sweepExpiredHolds(app) {
|
||||
const now = Date.now();
|
||||
for (const slot of findAll(app, 'slots', "status = 'held'")) {
|
||||
const until = toMs(slot.getString('heldUntil'));
|
||||
// Still valid, or no parseable hold to judge by — leave it alone.
|
||||
if (Number.isNaN(until) || until > now) continue;
|
||||
for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil < {:now}", { now: pbDate(Date.now()) })) {
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
for (const line of findAll(tx, 'basket_lines', 'slot = {:slot}', { slot: slot.id })) tx.delete(line);
|
||||
const fresh = tx.findRecordById('slots', slot.id);
|
||||
if (fresh.getString('status') !== 'held') return;
|
||||
fresh.set('status', 'available');
|
||||
fresh.set('heldUntil', '');
|
||||
tx.save(fresh);
|
||||
});
|
||||
app.delete(line);
|
||||
} catch (e) {
|
||||
console.error('[shop] could not release slot', slot.id, e);
|
||||
console.error('[shop] could not drop expired basket line', line.id, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -115,26 +273,36 @@ function createBasket(app) {
|
|||
return basket;
|
||||
}
|
||||
|
||||
function releaseSlotHold(app, slotId) {
|
||||
const slot = findOrNull(app, 'slots', slotId);
|
||||
if (!slot || slot.getString('status') !== 'held') return;
|
||||
slot.set('status', 'available');
|
||||
slot.set('heldUntil', '');
|
||||
app.save(slot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renew the hold on every slot line in a basket whose slot is still `held`
|
||||
* (nobody else can take a held slot, so renewing is safe). Used at checkout
|
||||
* start (30 min) and after a failed payment (10 min, so the customer can retry).
|
||||
* Renew the hold on every slot line in a basket. Used at checkout start
|
||||
* (30 min), after a failed payment (10 min, so the customer can retry) and
|
||||
* when the customer asks for more time (`renew_holds`, 10 min). A live hold
|
||||
* is extended, never shortened (its seats are already counted). A lapsed
|
||||
* one that hasn't been swept yet is rescued only if its seats are still
|
||||
* free and nothing has blocked the time since — otherwise it's left for
|
||||
* the sweep, and checkout tells the customer the slot expired.
|
||||
*/
|
||||
function extendBasketHolds(app, basketId, durationMs) {
|
||||
const now = Date.now();
|
||||
const until = isoIn(durationMs);
|
||||
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
|
||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
||||
if (slot && slot.getString('status') === 'held') {
|
||||
slot.set('heldUntil', until);
|
||||
app.save(slot);
|
||||
const heldUntil = toMs(line.getString('heldUntil'));
|
||||
if (heldUntil > now) {
|
||||
if (heldUntil < now + durationMs) {
|
||||
line.set('heldUntil', until);
|
||||
app.save(line);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
const fresh = tx.findRecordById('basket_lines', line.id);
|
||||
if (seatProblem(slotState(tx, fresh.getString('slot')), fresh.getInt('quantity'))) return;
|
||||
fresh.set('heldUntil', until);
|
||||
tx.save(fresh);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[shop] could not renew hold', line.id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,35 +343,38 @@ function basketAction(app, body) {
|
|||
}
|
||||
|
||||
case 'add_slot': {
|
||||
// Adding a slot that's already in the basket adds seats to that line.
|
||||
const slotId = String(body.slotId || '');
|
||||
if (lines.some((l) => l.getString('slot') === slotId)) throw conflict('Slot already in your basket');
|
||||
const slot = findOrNull(app, 'slots', slotId);
|
||||
if (!slot) throw new NotFoundError('Slot not found');
|
||||
if (slot.getString('status') !== 'available') throw conflict('Slot is no longer available');
|
||||
|
||||
// Line + hold in one transaction. basket_lines.slot is UNIQUE, so of
|
||||
// two concurrent requests for the same slot only one can succeed.
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
const fresh = tx.findRecordById('slots', slotId);
|
||||
if (fresh.getString('status') !== 'available') throw new Error('taken');
|
||||
tx.save(newRecord(tx, 'basket_lines', { basket: basket.id, item: fresh.getString('item'), slot: slotId, quantity: 1, lineType: 'slot' }));
|
||||
fresh.set('status', 'held');
|
||||
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||
tx.save(fresh);
|
||||
});
|
||||
} catch (_) {
|
||||
throw conflict('Slot was just reserved by someone else');
|
||||
}
|
||||
const seats = Math.max(1, Math.floor(Number(body.seats)) || 1);
|
||||
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
|
||||
const problem = seatProblem(slotState(tx, slotId), seats);
|
||||
if (problem) return problem;
|
||||
const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0];
|
||||
const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' });
|
||||
line.set('quantity', line.getInt('quantity') + seats);
|
||||
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||
tx.save(line);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'update_quantity': {
|
||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||
if (line.getString('lineType') === 'slot') throw new BadRequestError('Slot lines have fixed quantity 1');
|
||||
const quantity = Number(body.quantity);
|
||||
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
|
||||
if (line.getString('lineType') === 'slot') {
|
||||
// Seats for a group session: re-check capacity without this line's current seats.
|
||||
guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => {
|
||||
const fresh = tx.findRecordById('basket_lines', line.id);
|
||||
const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity);
|
||||
if (problem) return problem;
|
||||
fresh.set('quantity', quantity);
|
||||
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||
tx.save(fresh);
|
||||
});
|
||||
break;
|
||||
}
|
||||
const item = findOrNull(app, 'items', line.getString('item'));
|
||||
const stock = item ? item.get('stock') : null;
|
||||
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
||||
|
|
@ -212,12 +383,17 @@ function basketAction(app, body) {
|
|||
break;
|
||||
}
|
||||
|
||||
case 'renew_holds': {
|
||||
// "Keep my reservation" at checkout. Holds that already lapsed were
|
||||
// swept above; the customer is told and picks the time again.
|
||||
extendBasketHolds(app, basket.id, SLOT_HOLD_MS);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'remove_line': {
|
||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||
const slotId = line.getString('slot');
|
||||
app.delete(line);
|
||||
if (slotId) releaseSlotHold(app, slotId);
|
||||
app.delete(line); // a slot line's seats free up with it
|
||||
break;
|
||||
}
|
||||
|
||||
|
|
@ -303,8 +479,8 @@ function startCheckout(app, body) {
|
|||
if (!item || !item.getBool('active')) throw conflict('An item in your basket is no longer available');
|
||||
const quantity = line.getInt('quantity');
|
||||
if (line.getString('lineType') === 'slot') {
|
||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
||||
if (!slot || slot.getString('status') !== 'held') {
|
||||
// The sweep above dropped lapsed holds that couldn't be renewed.
|
||||
if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) {
|
||||
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
|
||||
}
|
||||
} else {
|
||||
|
|
@ -426,7 +602,9 @@ function createOrderFromIntent(app, intent) {
|
|||
});
|
||||
tx.save(order);
|
||||
|
||||
// Snapshot lines, book slots, decrement stock.
|
||||
// Snapshot lines and decrement stock. A slot's seats move from the
|
||||
// basket line (a hold) to the order line (a booking) in this same
|
||||
// transaction, so availability never sees them free in between.
|
||||
for (const line of lines) {
|
||||
const item = findOrNull(tx, 'items', line.getString('item'));
|
||||
const slot = findOrNull(tx, 'slots', line.getString('slot'));
|
||||
|
|
@ -442,12 +620,7 @@ function createOrderFromIntent(app, intent) {
|
|||
start: slot ? slot.getString('start') : ''
|
||||
})
|
||||
);
|
||||
if (line.getString('lineType') === 'slot' && slot) {
|
||||
slot.set('status', 'booked');
|
||||
slot.set('heldUntil', '');
|
||||
slot.set('order', order.id);
|
||||
tx.save(slot);
|
||||
} else if (item && item.get('stock') != null && item.get('stock') !== '') {
|
||||
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
|
||||
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
|
||||
tx.save(item);
|
||||
}
|
||||
|
|
@ -539,6 +712,8 @@ function recordEmailStatus(app, secretHeader, body) {
|
|||
}
|
||||
|
||||
module.exports = {
|
||||
bookableSlots,
|
||||
slotDetails,
|
||||
sweepExpiredHolds,
|
||||
loadActiveBasket,
|
||||
basketPayload,
|
||||
|
|
|
|||
28
pocketbase/pb_migrations/1792800000_items_buffer_minutes.js
Normal file
28
pocketbase/pb_migrations/1792800000_items_buffer_minutes.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// items.bufferMinutes: the get-ready time a service needs after each
|
||||
// appointment (tidying the room, changing linen). The admin's slot generator
|
||||
// uses it as the default gap between generated slots. Empty = no gap.
|
||||
|
||||
function find(app, name) {
|
||||
try {
|
||||
return app.findCollectionByNameOrId(name);
|
||||
} catch (e) {
|
||||
return null; // fresh install: pb_schema.json (already has the field) is imported later
|
||||
}
|
||||
}
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const collection = find(app, 'items');
|
||||
if (!collection || collection.fields.getByName('bufferMinutes')) return;
|
||||
collection.fields.add(new NumberField({ id: 'num_itembuffer1', name: 'bufferMinutes', min: 0, onlyInt: true }));
|
||||
app.save(collection);
|
||||
},
|
||||
(app) => {
|
||||
const collection = find(app, 'items');
|
||||
if (!collection || !collection.fields.getByName('bufferMinutes')) return;
|
||||
collection.fields.removeByName('bufferMinutes');
|
||||
app.save(collection);
|
||||
}
|
||||
);
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Slots get seats; bookings stop being stored on the slot.
|
||||
//
|
||||
// Before: a slot was one customer — `status` available|held|booked,
|
||||
// `heldUntil`, `order`, and a UNIQUE index so only one basket line could
|
||||
// point at a slot. After: a slot has `capacity` seats (items.capacity is
|
||||
// the service's default), and the shop hooks derive everything else —
|
||||
// seats taken = paid order lines + basket lines with a live `heldUntil`,
|
||||
// plus blocking by overlapping slots (see pb_hooks/shop/lib.js).
|
||||
//
|
||||
// 1. items.capacity, slots.capacity (existing slots: 1).
|
||||
// 2. basket_lines.heldUntil, copied from the slot each line was holding.
|
||||
// 3. basket_lines.slot: unique index → plain index (many baskets may hold
|
||||
// seats on one slot); index order_lines.slot for seat counting.
|
||||
// 4. slots: drop status/heldUntil/order and the status index. Booked
|
||||
// seats already live in order_lines (with the slot and a start snapshot).
|
||||
// 5. slots: API rules signed-in only. The public shop lists slots through
|
||||
// GET /api/shop/slots, which hides full and blocked ones.
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
const AUTH_ONLY = "@request.auth.id != ''";
|
||||
|
||||
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. Capacity.
|
||||
if (items && !items.fields.getByName('capacity')) {
|
||||
items.fields.add(new NumberField({ id: 'num_itemcapacity', name: 'capacity', min: 1, onlyInt: true }));
|
||||
app.save(items);
|
||||
}
|
||||
if (slots && !slots.fields.getByName('capacity')) {
|
||||
slots.fields.add(new NumberField({ id: 'num_slotcapacity', name: 'capacity', min: 1, onlyInt: true }));
|
||||
app.save(slots);
|
||||
for (const slot of app.findAllRecords('slots')) {
|
||||
slot.set('capacity', 1);
|
||||
try {
|
||||
app.saveNoValidate(slot);
|
||||
} catch (e) {
|
||||
console.log(`[migration] could not set capacity on slot ${slot.id}: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Holds move to the basket line.
|
||||
if (basketLines && !basketLines.fields.getByName('heldUntil')) {
|
||||
basketLines.fields.add(new DateField({ id: 'date_blheldunt1', name: 'heldUntil' }));
|
||||
app.save(basketLines);
|
||||
if (slots && slots.fields.getByName('heldUntil')) {
|
||||
for (const line of app.findRecordsByFilter('basket_lines', "slot != ''", '', 0, 0)) {
|
||||
try {
|
||||
const slot = app.findRecordById('slots', line.getString('slot'));
|
||||
if (slot.getString('status') !== 'held') continue; // leaves heldUntil empty → swept
|
||||
line.set('heldUntil', slot.getString('heldUntil'));
|
||||
app.saveNoValidate(line);
|
||||
} catch (e) {
|
||||
console.log(`[migration] could not move the hold of basket line ${line.id}: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Indexes.
|
||||
if (basketLines) {
|
||||
basketLines.indexes = basketLines.indexes
|
||||
.filter((index) => !index.includes('idx_basket_lines_slot_unique'))
|
||||
.concat(basketLines.indexes.some((index) => index.includes('idx_basket_lines_slot`')) ? [] : ['CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)']);
|
||||
app.save(basketLines);
|
||||
}
|
||||
if (orderLines && !orderLines.indexes.some((index) => index.includes('idx_order_lines_slot'))) {
|
||||
orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)'];
|
||||
app.save(orderLines);
|
||||
}
|
||||
|
||||
// 4 + 5. Slot fields and rules.
|
||||
if (slots) {
|
||||
slots.indexes = slots.indexes.filter((index) => !index.includes('idx_slots_status'));
|
||||
for (const name of ['status', 'heldUntil', 'order']) {
|
||||
if (slots.fields.getByName(name)) slots.fields.removeByName(name);
|
||||
}
|
||||
slots.listRule = AUTH_ONLY;
|
||||
slots.viewRule = AUTH_ONLY;
|
||||
app.save(slots);
|
||||
}
|
||||
},
|
||||
(app) => {
|
||||
// Revert the schema. Holds and bookings are NOT written back onto
|
||||
// slots (every slot comes back `available`) — restore a backup if
|
||||
// you need the old state exactly.
|
||||
const slots = find(app, 'slots');
|
||||
if (slots) {
|
||||
if (!slots.fields.getByName('status')) slots.fields.add(new SelectField({ id: 'sel_slotstatus0', name: 'status', values: ['available', 'held', 'booked'], maxSelect: 1 }));
|
||||
if (!slots.fields.getByName('heldUntil')) slots.fields.add(new DateField({ id: 'date_slotheldun0', name: 'heldUntil' }));
|
||||
const orders = find(app, 'orders');
|
||||
if (orders && !slots.fields.getByName('order')) slots.fields.add(new RelationField({ id: 'rel_slotorder01', name: 'order', collectionId: orders.id, maxSelect: 1 }));
|
||||
if (slots.fields.getByName('capacity')) slots.fields.removeByName('capacity');
|
||||
slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_status')), 'CREATE INDEX `idx_slots_status` ON `slots` (`status`)'];
|
||||
slots.listRule = "status = 'available' || @request.auth.id != ''";
|
||||
slots.viewRule = "status = 'available' || @request.auth.id != ''";
|
||||
app.save(slots);
|
||||
for (const slot of app.findAllRecords('slots')) {
|
||||
slot.set('status', 'available');
|
||||
app.saveNoValidate(slot);
|
||||
}
|
||||
}
|
||||
const items = find(app, 'items');
|
||||
if (items && items.fields.getByName('capacity')) {
|
||||
items.fields.removeByName('capacity');
|
||||
app.save(items);
|
||||
}
|
||||
const basketLines = find(app, 'basket_lines');
|
||||
if (basketLines) {
|
||||
if (basketLines.fields.getByName('heldUntil')) basketLines.fields.removeByName('heldUntil');
|
||||
basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_slot`'));
|
||||
app.save(basketLines);
|
||||
}
|
||||
const orderLines = find(app, 'order_lines');
|
||||
if (orderLines) {
|
||||
orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_slot'));
|
||||
app.save(orderLines);
|
||||
}
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue