Compare commits

..

No commits in common. "main" and "evashafik-backups-currency" have entirely different histories.

119 changed files with 4215 additions and 7339 deletions

View file

@ -3,7 +3,7 @@
## Stack ## Stack
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc.
- **PocketBase** — server pinned to **0.40.6** (`docker-compose.yml`, image `elestio/pocketbase`, digest-pinned; runs as non-root uid 100 on port 8090), REST API via the `pocketbase` SDK (v0.28). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). - **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations).
- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site.
- **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy).
@ -25,20 +25,18 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts) │ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts)
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
│ │ ├── +page.svelte # Dashboard (income + chart, hours, utilisation, customers, codes owed, what sells, needs attention); figures from $lib/server/dashboard.ts. Login lands here
│ │ ├── login/ # Admin login │ │ ├── login/ # Admin login
│ │ ├── pages/ # Page CRUD + block editor │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── calendar/ # Event CRUD (menu label: Events)
│ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── passes/ # Vouchers & codes: search, void/extend, issue (menu label: Vouchers & codes) │ │ ├── slots/ # Bookable slots: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear
│ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── orders/ # Order list + booking-email status/resend
│ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings │ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings
│ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors/style editor (menu label: Site design) │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
│ │ ├── backup/ # Export/import UI (calls api/export, api/import) │ │ ├── backup/ # Export/import UI (calls api/export, api/import)
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin) │ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
│ │ └── api/ # upload, export, import, slots (Shop block times in /preview) endpoints │ │ └── api/ # upload, export, import endpoints
│ ├── hooks.server.ts # Auth guard — all routes except /login │ ├── hooks.server.ts # Auth guard — all routes except /login
│ └── app.css # Tailwind + DaisyUI + custom theme │ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets ├── static/ # Static assets
@ -62,7 +60,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
│ │ ├── +layout.svelte # Root layout (always renders Header/Footer) │ │ ├── +layout.svelte # Root layout (always renders Header/Footer)
│ │ ├── +page.svelte # Home page (slug=home) │ │ ├── +page.svelte # Home page (slug=home)
│ │ ├── [slug]/ # Dynamic CMS pages │ │ ├── [slug]/ # Dynamic CMS pages
│ │ ├── api/ # basket, checkout, webhooks, slots (Shop block times) endpoints │ │ ├── api/ # basket, checkout, webhooks endpoints
│ │ └── checkout/return/ # Stripe return URL │ │ └── checkout/return/ # Stripe return URL
│ ├── hooks.server.ts # Creates PB client in locals (no auth guard) │ ├── hooks.server.ts # Creates PB client in locals (no auth guard)
│ └── app.css # Tailwind + DaisyUI + custom theme │ └── app.css # Tailwind + DaisyUI + custom theme
@ -82,7 +80,7 @@ Caddyfile # Subdomain-based routing
Caddy routes by `Host` header — no path stripping: Caddy routes by `Host` header — no path stripping:
- `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app) - `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app)
- `db.{$DOMAIN}:8080` → `pocketbase:8090` (redirects `/` to `/_/`) - `db.{$DOMAIN}:8080` → `pocketbase:80` (redirects `/` to `/_/`)
- `www.{$DOMAIN}:8080`, `*.{$DOMAIN}:8080` → `app-public:3000` (public app) - `www.{$DOMAIN}:8080`, `*.{$DOMAIN}:8080` → `app-public:3000` (public app)
For local dev, `DOMAIN` defaults to `localhost`, so Caddy serves `admin.localhost:8080`, `db.localhost:8080`, `www.localhost:8080`. Caddy's `.localhost` handling works without DNS or hosts-file changes. For local dev, `DOMAIN` defaults to `localhost`, so Caddy serves `admin.localhost:8080`, `db.localhost:8080`, `www.localhost:8080`. Caddy's `.localhost` handling works without DNS or hosts-file changes.
@ -100,14 +98,12 @@ All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `o
### Block System ### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app): Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app):
`text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout | cards | faq | html` `text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout`
- **Renderers (shared)**: `packages/shared/src/blocks/<Type>Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers. - **Renderers (shared)**: `packages/shared/src/blocks/<Type>Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers.
- **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type - **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
- **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults - **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete - **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete
- **Settings on every block** (keys starting with `_`, edited below each block's own fields): `_background`, `_foreground` (colours) and `_anchor` (id for `#anchor` links), applied by `BackgroundWrapper.svelte`.
- **Text is edited visually**: `RichTextEditor.svelte` (Tiptap) only produces `p, h2, h3, strong, em, s, a, ul, ol, li, blockquote, br, hr` — no inline styles or layout HTML. That list is `EDITOR_TAGS` in `packages/shared/src/richText.ts`; keep it and the editor's extensions in step. A layout people keep needing becomes a block (as Cards and FAQ did), never HTML in a text block; one-offs and embeds go in an `html` block. Old text blocks holding other HTML are turned into `html` blocks (or centred text) by `upgradeLegacyBlocks()` on backup import and by migration `1793300000_text_blocks_visual_editor.js`.
To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`. To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`.
@ -123,7 +119,6 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### Shared Code ### Shared Code
- `packages/shared/src/types.ts` — all type definitions - `packages/shared/src/types.ts` — all type definitions
- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) - `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block)
- `packages/shared/src/items.ts` — service durations (`parseDurations`, `formatDuration`, `lowestPrice`); which length costs what is charged by the shop hooks
- `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts` - `packages/shared/src/slots.ts` — pure slot planning (generate/copy-week maths on date keys + wall-clock times in `SITE_TIMEZONE`, DST-safe); the `/slots` actions use it via `$lib/slots`, PocketBase I/O is in `app-admin/src/lib/server/slots.ts`
- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` - Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'`
- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work - Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work
@ -131,39 +126,31 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
### PocketBase Integration ### PocketBase Integration
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie - Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` - `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled); commerce: `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`, `passes` (bundle/voucher codes) - Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled)
- Server load functions use `locals.pb.collection('pages').getFirstListItem()` - Server load functions use `locals.pb.collection('pages').getFirstListItem()`
- **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them). - **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them).
- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Field settings go at the field's top level (`"maxSize": 2000000`), never under `options`: PocketBase has ignored `options` since 0.23. Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. - **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting.
- **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. - **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules.
- **Slot availability** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*. - **Slot availability** (places + blocking by overlapping bookings, incl. get-ready time) is computed only by `slotStates()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots`, `?detail=1` for the admin). Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*.
- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email`, `passes.email`/`recipientName`/`message` and (during checkout) `baskets` / `basket_lines.giftTo`/`giftMessage`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*. - **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email` and (during checkout) `baskets`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*.
- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. Bundle parts are JSON, not relations: the `onRecordDelete` hook on `items` (`deleteBlocker`) keeps parts that bundles or codes still need from being deleted, and a bundle with an inactive part isn't sold. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*.
- **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only). - **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only).
### Styling ### Styling
- **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `font-sans` (body), `font-serif` (headings), chosen in Site design → Style (default DM Sans / Playfair Display). - **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings).
- **Site design → Style** (`style` global: fonts, corners, text size, shadows, page width) becomes `--site-*` variables (`siteStyleVars` in `$shared/theme`) that the `@theme` tokens in both `app.css` files scale. So in public-site markup use the tokens — `rounded-xl`/`rounded-2xl`/`rounded-card`/`rounded-panel`, `shadow-sm`…`shadow-xl`, `max-w-3xl`/`6xl`/`7xl` — never `rounded-[2rem]` or an arbitrary `shadow-[…]`, which ignore the settings. Buttons, chips and icon buttons are `rounded-button` (a pill when Round, square when Sharp); only dots, avatars and badges stay `rounded-full`.
- Keep scrolling smooth: no `backdrop-blur` on public pages (it is redrawn on every scrolled frame; use a nearly solid background), and keep animations short. The `.reveal` / `.animate-fade-in` animations are switched off for people who ask for reduced motion and, by `scrollReveal.ts`, on devices that stutter (`plain-motion` on `<html>`, rules in both `app.css` files).
- Fonts are bundled `@fontsource-variable/*` packages, imported in each app's `src/lib/fonts.ts` and listed in `SITE_FONTS`; a new one goes in all three places.
- **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). Colours come from Site design via `$shared/theme`, rendered as a `<style>` in `<head>` (SSR, no flash): the admin gets only DaisyUI primary (= site Primary) and secondary (= site Accent) with auto-contrast text; `/preview` and the public site get all site colour variables. Never use `text-primary`/`text-secondary` for text — a light brand colour is unreadable as text; mark state with a tint/bar instead. Conventions: - **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). Colours come from Site design via `$shared/theme`, rendered as a `<style>` in `<head>` (SSR, no flash): the admin gets only DaisyUI primary (= site Primary) and secondary (= site Accent) with auto-contrast text; `/preview` and the public site get all site colour variables. Never use `text-primary`/`text-secondary` for text — a light brand colour is unreadable as text; mark state with a tint/bar instead. Conventions:
- Section card: `rounded-box bg-base-100 p-5 shadow` with an `h2.text-2xl.font-bold` title (see Site design / globals). - Section card: `rounded-box bg-base-100 p-5 shadow` with an `h2.text-2xl.font-bold` title (see Site design / globals).
- Form field: `<label class="fieldset"><span class="fieldset-legend">Label</span><input class="input w-full" /></label>`; hints in `<span class="label">`. - Form field: `<label class="fieldset"><span class="fieldset-legend">Label</span><input class="input w-full" /></label>`; hints in `<span class="label">`.
- Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker; in a narrow row (a phone) the label goes above (a `@container` query). More than about four choices don't fit a phone: use a slider (like the background Overlay). - Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker.
- Save results in editors: `$lib/admin/SaveStatus.svelte` (success fades out after a moment, an error stays).
- Images: always `$lib/admin/editors/ImagePicker.svelte` (choose, drag in or paste an image, or pick an uploaded one from the library: `MediaLibrary.svelte`, `/api/media`; address and alt text). It uploads to `media` through `/api/upload`; `withUrl={false}` + `altHint=""` + the `id` from `onChange` where a field stores a media relation (Services & products). Store only `url`/`alt` from `onChange` elsewhere.
- 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). - 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. - 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()`. - 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` with the shop `currency`, `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 and prices shown to people** use `DISPLAY_LOCALE` (`en-GB`: day-month-year, 24-hour clock) and the helpers in `$shared/calendar` (`formatInstant`, `formatPrice` with the shop `currency`, `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. - **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 (in both apps' `app.css`, which must stay alike: the admin preview uses it). A *Quote* in the editor is the pull quote (`blockquote`). - **Prose**: `.prose-wellness` class for rich text content styling
### Routing ### Routing
- **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts` (which also refreshes the token per request and sets the cookie's `Secure` flag from the real scheme). The root layout renders the admin shell (grouped sidebar) except on `/login` and `/preview`. The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works). - **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts` (which also refreshes the token per request and sets the cookie's `Secure` flag from the real scheme). The root layout renders the admin shell (grouped sidebar) except on `/login` and `/preview`. The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works).
- **Public app** (`app-public`): No auth guard. The root layout always renders Header/Footer. `+layout.server.ts` fetches header/footer/colors globals + basket/items/slots for every page. - **Public app** (`app-public`): No auth guard. The root layout always renders Header/Footer. `+layout.server.ts` fetches header/footer/colors globals + basket/items/slots for every page.
- **Booking and basket links**: booking = the header CTA's address, basket = the optional basket page slug typed in Site design (`header.basketPage`; '' = the CTA's address), both from `shopLinks(header)` in `packages/shared/src/types.ts` (blocks read `page.data.header`) — never hard-code `/book`.
- **Class names in components are written out whole** (`'btn-primary'`, not `` `btn-${variant}` ``): Tailwind only generates classes it finds in the source, so a built-up name silently gets no style.
- `+page.server.ts` for home fetches `slug = "home" && published = true` - `+page.server.ts` for home fetches `slug = "home" && published = true`
- `[slug]/+page.server.ts` fetches by dynamic slug - `[slug]/+page.server.ts` fetches by dynamic slug
@ -193,7 +180,7 @@ cd app-public && npm run build
- `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`. - `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`.
- `URL_SCHEME` (default `http`), `URL_PORT` (default `:8080`; set it empty for no port) — build every browser-facing URL below as `<scheme>://<sub>.<DOMAIN><port>`. They must match the address bar exactly: a mismatched `ORIGIN` makes SvelteKit reject form POSTs (admin login) with "Cross-site POST form submissions are forbidden". Behind a TLS reverse proxy: `URL_SCHEME=https`, `URL_PORT=`. (podman-compose 1.5 can't do nested `${A:-${B}}` defaults, hence two flat variables.) - `URL_SCHEME` (default `http`), `URL_PORT` (default `:8080`; set it empty for no port) — build every browser-facing URL below as `<scheme>://<sub>.<DOMAIN><port>`. They must match the address bar exactly: a mismatched `ORIGIN` makes SvelteKit reject form POSTs (admin login) with "Cross-site POST form submissions are forbidden". Behind a TLS reverse proxy: `URL_SCHEME=https`, `URL_PORT=`. (podman-compose 1.5 can't do nested `${A:-${B}}` defaults, hence two flat variables.)
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`<scheme>://db.${DOMAIN}<port>`). Set in `docker-compose.yml`. - `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`<scheme>://db.${DOMAIN}<port>`). Set in `docker-compose.yml`.
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:8090`). Set in `docker-compose.yml`. - `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`.
- `ORIGIN` — SvelteKit origin for SSR. Differs per app: `<scheme>://admin.${DOMAIN}<port>` (admin), `<scheme>://www.${DOMAIN}<port>` (public). - `ORIGIN` — SvelteKit origin for SSR. Differs per app: `<scheme>://admin.${DOMAIN}<port>` (admin), `<scheme>://www.${DOMAIN}<port>` (public).
- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`<scheme>://www.${DOMAIN}<port>`). - `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`<scheme>://www.${DOMAIN}<port>`).
- `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `EMAIL_FROM`, `EMAIL_FROM_NAME` — Brevo SMTP relay for booking emails (both apps). Empty `SMTP_HOST` = log emails instead of sending. - `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `EMAIL_FROM`, `EMAIL_FROM_NAME` — Brevo SMTP relay for booking emails (both apps). Empty `SMTP_HOST` = log emails instead of sending.
@ -201,5 +188,4 @@ cd app-public && npm run build
- `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency. - `STRIPE_CURRENCY` — shop currency (ISO 4217, default `eur`; e.g. `nok`). One setting for what Stripe charges and how prices are shown: PocketBase, both apps' layout data (`currency`, read by blocks via `page.data.currency`) and booking emails. Format prices with `formatPrice(amount, currency)` from `$shared/calendar` — never hard-code a currency.
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. - Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials. - `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
- Shop order: `items.priority` (higher first) is *Recommended*. It's set by dragging the `/items` list (`?/reorder` renumbers n…1), not typed in the item form; `sortItems()` in `packages/shared/src/items.ts` is the one place items are ordered (Shop block `sort` / `showSort`). *Most popular* ranks come from `GET /api/shop/popular` (`popularItems()` in the shop hooks, ids only — never expose sales counts), merged into `ItemRecord.popularRank` by `loadShopData()`. - Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`; slots via `GET /api/shop/slots`); if a Shop block has nothing to show it says "Nothing is available".
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`). The Shop block fetches bookable times itself, per service and length, from `GET /api/slots` in each app (a proxy to `GET /api/shop/slots`); if it has nothing to show it says "Nothing is available".

View file

@ -18,7 +18,7 @@
{$CADDY_SCHEME}://db.{$DOMAIN}:8080 { {$CADDY_SCHEME}://db.{$DOMAIN}:8080 {
# PocketBase admin UI lives at /_/ — redirect bare root there. # PocketBase admin UI lives at /_/ — redirect bare root there.
redir / /_/{path} redir / /_/{path}
reverse_proxy pocketbase:8090 reverse_proxy pocketbase:80
} }
{$CADDY_SCHEME}://www.{$DOMAIN}:8080, {$CADDY_SCHEME}://*.{$DOMAIN}:8080 { {$CADDY_SCHEME}://www.{$DOMAIN}:8080, {$CADDY_SCHEME}://*.{$DOMAIN}:8080 {

View file

@ -73,41 +73,20 @@ Subsequent builds reuse the npm cache declared in each app's `Dockerfile`.
The app containers use two PocketBase URLs: The app containers use two PocketBase URLs:
- `POCKETBASE_INTERNAL_URL=http://pocketbase:8090` for server-side SvelteKit calls from the app containers (the `elestio/pocketbase` image listens on 8090). - `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app containers when using the included `spectado/pocketbase` image.
- `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain. - `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain.
## PocketBase setup ## PocketBase setup
A fresh install, once the stack is up (written for the PocketBase 0.40 dashboard): 1. Open `http://db.localhost:8080/_/`.
2. Create the first PocketBase admin user when prompted.
3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below.
4. Create starter records:
- `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array.
- `globals`: key `header`, data matching the header JSON in the project prompt.
- `globals`: key `footer`, data matching the footer JSON in the project prompt.
1. **Create the first superuser.** PocketBase prints a one-time install link in its log (`docker compose logs pocketbase`): `http://0.0.0.0:8090/_/#/pbinstall/<token>`. Open it with `http://0.0.0.0:8090` replaced by the address you reach PocketBase at, e.g. `http://db.localhost:8080/_/#/pbinstall/<token>`. If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them.
2. **Import the schema.** In the dashboard: **Settings → Import collections → Load from JSON file**, choose `pb_schema.json`, and **tick "Merge with the existing collections"**. It is off by default, and without it the import deletes every collection that isn't in the file, including `users` (so nobody but superusers could sign in to the admin). Review, then **Confirm and import**. `PUT /api/collections/import` with `"deleteMissing": false` does the same.
3. **Add content.** Sign in to the admin app and import a site from `backups/` under **Backup → Import** (see `backups/README.md`), or start from empty: pages are created under **Pages**, and **Site design** creates its own records the first time it is opened.
The migrations in `pocketbase/pb_migrations/` already ran when PocketBase first started (before the collections existed, so they skipped); the imported `pb_schema.json` is the end state they lead to. On that first start the privacy cron also logs `[privacy] retention at startup failed: … no rows in result set`, because the collections don't exist yet; it is harmless and gone from the next start.
### Switching PocketBase image (existing installs)
The PocketBase image changed from `spectado/pocketbase:0.23.12` (removed from Docker Hub) to `elestio/pocketbase:v0.23.12`. It is the same PocketBase version, so the schema, migrations and hooks are unchanged, but the new image runs as a non-root `pocketbase` user (uid 100) and listens on port 8090. Files the old image wrote are owned by root, and PocketBase refuses to start on them (`attempt to write a readonly database`). Fix the ownership once, before the first start on the new image:
```sh
docker compose stop pocketbase
# back up first: the volume is <project>_pocketbase (see `docker volume ls`)
docker compose run --rm --no-deps --user root --entrypoint chown pocketbase -R pocketbase:pocketbase /pb_data
docker compose up -d
```
Fresh installs need nothing: a new volume is created with the right owner.
### Upgrading to PocketBase 0.40 (existing installs)
PocketBase went from 0.23.12 to 0.40.6 (same image, same port and user, so nothing above changes). On its first start 0.40 upgrades `pb_data` in place, and that can't be undone by going back to the old image: **back up `pb_data` first**, and to roll back, restore that backup. Coming from the spectado image, do the `chown` above too.
What changed for this project:
- **JSON field limits.** PocketBase's default limit for JSON fields fell to 1MB in 0.29, and six of ours had relied on it (their limits were under `options` in `pb_schema.json`, which PocketBase ignores). Migration `1793400000_json_field_limits.js` sets them explicitly (page and email blocks 2MB, site design 1MB, …). Real pages are far below that.
- **New dashboard** at `db.…/_/` (rewritten in 0.37); the setup steps above describe it.
- Downloads now send a quoted filename (`filename="photo.jpg"`); nothing here depends on it.
### Migrations ### Migrations
@ -133,16 +112,15 @@ If schema import fails because of a PocketBase version mismatch, create these co
Commerce collections (see the Stripe section above for context): Commerce collections (see the Stripe section above for context):
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time|bundle`, `stock` number + `trackStock` bool (products; PocketBase reads an empty number back as 0, so `trackStock` off = unlimited), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `bundleParts` json (bundles: `[{ item, minutes, count }]`, minutes null for a product), `validMonths` number (bundles: how long a code can be used; empty = no expiry), `priority` number (−1000…1000, empty = 0: Shop blocks' *Recommended* order, higher first, then by name; set by dragging the `/items` list, never typed), `active` bool - `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` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below - `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, `pass` relation→passes (the code applied at checkout) - `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold), `pass` relation→passes (the code paying for this booking), `giftTo` / `giftMessage` text (who a bundle is for) - `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 (empty for an order paid entirely with codes), `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty) - `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty)
- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date and `minutes` number (nullable, the booked time), `pass` relation→passes (the code that paid for this booking; `price` is then 0) - `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)
- `passes` — bundle/voucher codes: `code` text (unique, 8 characters, shown as `ABCD-2345`), `item` relation→items (the bundle), `order` relation→orders (empty when issued in the admin), `name` text, `parts` json (snapshot: `[{ item, name, minutes, count, value }]`, `value` = the part's share of the price), `email` text (buyer), `recipientName` / `message` text, `expiresAt` date, `status` select `active|void`, `anonymisedAt` date. What's used is never stored — see *Bundles and codes*
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool - `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool
> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Field config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`, number `min`/`max`/`onlyInt`) belongs at the field top level — 0.23 silently ignores anything nested under `options`, so the older number/text fields that still use `options` get no min/max on a fresh install (the JSON fields' `maxSize` has been moved up; see *Upgrading to PocketBase 0.40*). Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass; keep *Merge with the existing collections* ticked (`deleteMissing: false`), or `users` is deleted. > **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 ## Authentication
@ -157,13 +135,10 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/login` — sign in - `/login` — sign in
- `/pages` — list/create pages - `/pages` — list/create pages
- `/pages/[slug]` — block editor with draft preview. Text is edited visually (headings, bold, italic, strikethrough, links, lists, pull quotes, lines; alignment and a small *footnote* size per block). Layouts have their own blocks: **Cards** (pictures or numbered steps, optionally linked — e.g. *Who I work with*, *Read next*, *How it works*) and **FAQ** (questions that open to show the answer). An **HTML** block takes raw HTML for embeds and one-offs (inline styles only; anything it loads from another site shares visitors' IPs). Every block has an *Anchor*, so a button or link to `#prices` jumps to it. - `/pages/[slug]` — block editor with draft preview
- `/calendar` — events shown by Upcoming Calendar blocks - `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services, products and bundles shown in Shop blocks, listed in shop order. Drag a row by its ⠿ handle (or focus the handle and press ↑/↓), then *Save order*: the `?/reorder` action stores it as `items.priority` (n…1, first = highest), writing only what changed. New items go to the end - `/items` — services and products shown in Shop blocks
- Shop block order: *Recommended* (by priority), *Most popular*, *Price: low to high / high to low*, *Name (A–Z)*, chosen per block (`sort`); *Let visitors sort* (`showSort`) adds a "Sort by" menu that starts at that order. *Most popular* = units in paid orders over the last 90 days, from `GET /api/shop/popular` (public; item ids best-selling first, never the numbers; refunded orders and products handed over inside a bundle don't count, bookings paid with a code do). Items without recent sales follow in Recommended order, and the menu leaves the choice out until something has sold. Chosen items (`itemIds`) follow the block's order too, not the order they were picked in. - `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions.
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). No two slots may overlap (windows and group sessions alike); bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.
- `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them.
- `/passes` — *Vouchers & codes*: search codes (code, email, recipient, bundle), see what each has used/held/left and each part's share of the price, change the expiry, void/reactivate, and issue a code without a purchase
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons - `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons
- `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*) - `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*)
- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) - `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
@ -175,14 +150,12 @@ The shop/checkout blocks implement a basket-based booking flow: visitors add ser
**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that tidies expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`. **Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that tidies expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
**Slot availability** (`availability()` / `windowStartTimes()` / `checkBooking()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live): **Slot availability** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live):
- A **booking** is a paid order line or a basket line whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts), each with its own `start` and `minutes`. It keeps the practitioner busy until its service's get-ready time (`items.bufferMinutes`) is over. A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does. - 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 no booking may overlap another — whatever the service, whatever the slot — including get-ready time. - 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.
- A **window** offers its services at any of their lengths. A booking must start and end inside it (its get-ready time may run past the end) and fit before the next booking. `startTimes = grid`: every `gridMinutes` (chosen per window: 10, 15, 20, 30, 45 or 60; default 30) from the window's start. `edges`: only right at the start or the end of each free stretch — a 09:00–12:00 window offers a 1-hour massage at 09:00 or 11:00; once 09:00 is booked (+15 min get-ready) it offers 10:15 or 11:00 — so time is taken from the ends and no gaps are left. - `GET /api/shop/slots` lists the bookable future slots (public; feeds the Shop block). With `?detail=1` a signed-in admin gets every slot in a range with booked/held places and what blocks it (the `/slots` page).
- A **group session** has `capacity` places for one service at one length; places are counted from its bookings. With any place taken its whole time is busy (windows lose that time); it stays bookable until full, and can't be booked while another booking overlaps it. - 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.
- `GET /api/shop/slots?item=&minutes=&from=&to=` lists the times a customer can book for one service and length (public; the Shop block fetches it through each app's `GET /api/slots` for the months on screen), plus `next` — the first bookable time after the range — when there are none in it. With `?detail=1` a signed-in admin gets every slot in a range with its bookings, free stretches and what blocks it (the `/slots` page).
- Adding to a basket (`add_slot`: `slotId` plus `itemId`, `minutes`, `start` for a window, or `seats` for a session) and changing a group line's places re-check everything inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. The price is the service's price for the booked length, read again at checkout.
Setup: Setup:
@ -194,20 +167,7 @@ Setup:
``` ```
Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`. 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`). Two visitors can't take the same place: holds are checked and written in one PocketBase transaction (see *Slot availability*). 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 point the header CTA at it (*Site design → Header*); hero buttons without an address and *Book another* after paying lead there too. Put a `checkout` block on the same page, or on a page of its own whose slug you type as the optional *Basket page*: the basket in the header and *view basket* in the shop lead there (empty = the CTA's address). Site design warns when the basket's page isn't published or has no `checkout` block. 5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it.
## Bundles and codes
A **bundle** (Services & products → type *Bundle / voucher*) has its own price and contains services at a set length (e.g. 3 × Massage, 1 hour) and/or products, plus how many months its code stays valid. A gift voucher for one service is a bundle with one part.
- **Buying**: the bundle goes in the basket like a product (its products' stock is checked and taken with the order). The buyer can mark it as a gift (*for* and a message). After payment every bundle bought becomes a **pass** with its own code, sent in the confirmation email and shown on the result page.
- **Redeeming**: whoever has the code enters it in the basket (`apply_code`). It covers bookings of the same service **and** length while it has places left; covered lines cost 0 and carry `pass`. A basket that codes cover entirely is confirmed without Stripe (`/api/shop/checkout` returns `{ free, orderId }`; the result page is `/checkout/return?order=…`, shown only to that basket's cookie).
- **Counting**: a pass's used places are its order lines (not refunded) and its live basket holds — never a stored counter. Refunding a booking's order gives the place back. Holds keep two people with the same code from using its last place at once.
- **Shown in the shop** with what the parts cost bought one by one, crossed out when that's more than the bundle price (`bundleListPrice` in `packages/shared/src/items.ts`).
- **Parts that go away**: a service or product can't be deleted while a bundle contains it, or while a usable code still has sessions of it to book or held (an `onRecordDelete` hook, `deleteBlocker` — bundle parts are JSON, so the database wouldn't stop it). Making it inactive is allowed: a bundle with an inactive part (or a length the service no longer offers) is hidden from the shop and can't be bought or issued; the admin items list marks it *Not on sale* and says why. Codes keep their own snapshot of names and prices, but can't book an inactive service — the items list shows how many codes are still waiting for it.
- **Value**: `parts[].value` splits the bundle price in proportion to what the parts cost on their own, for partial refunds (done in Stripe, as before).
- **Admin**: `/passes` (*Vouchers & codes*), via `GET /api/shop/passes`, `POST /api/shop/passes/update`, `POST /api/shop/passes/issue` (signed-in admins; passes are written only by the shop hooks).
- **Personal data**: a pass holds the buyer's email and possibly a recipient's name and message. Export, correction and erasure cover passes; erasure keeps the code working. Retention anonymises a pass together with orders, once it has expired or has nothing left to book.
## Booking emails (Brevo) ## Booking emails (Brevo)
@ -234,12 +194,12 @@ With `SMTP_HOST` empty (local dev) emails are written to the app container logs
What the software does; the studio (the controller) is responsible for the privacy policy text and for how it uses the data. What the software does; the studio (the controller) is responsible for the privacy policy text and for how it uses the data.
- **What is stored:** name, email, phone and booking notes, on `orders.customerDetails` (one copy per order) and on `baskets` while checkout is in progress. A paid basket's copy is cleared as soon as its order exists. Bundle/voucher codes (`passes`) keep the buyer's email and, for gifts, the recipient's name and message. - **What is stored:** name, email, phone and booking notes, on `orders.customerDetails` (one copy per order) and on `baskets` while checkout is in progress. A paid basket's copy is cleared as soon as its order exists.
- **Privacy policy:** *Site design → Footer → Privacy policy page* links a page from the footer and above the Pay button. *Create a privacy policy draft* makes an unpublished `privacy` page describing what this software does, with [gaps] to fill in. - **Privacy policy:** *Site design → Footer → Privacy policy page* links a page from the footer and above the Pay button. *Create a privacy policy draft* makes an unpublished `privacy` page describing what this software does, with [gaps] to fill in.
- **Checkout:** a short privacy notice with the link, and a hint under the notes field asking customers not to write health details (special-category data). There is deliberately no "I consent" box: booking data is processed to perform the contract, not on consent. Both texts are editable in the Checkout block. - **Checkout:** a short privacy notice with the link, and a hint under the notes field asking customers not to write health details (special-category data). There is deliberately no "I consent" box: booking data is processed to perform the contract, not on consent. Both texts are editable in the Checkout block.
- **Customers (admin):** look a customer up by name, email, phone or notes (orders and unpaid checkouts, matched by email case-insensitively); *Export data (JSON)* for access/portability requests; correct name/email/phone or remove notes on every record; *Erase* anonymises their orders (amounts, services and dates stay for the accounts) and their codes (the codes keep working), and deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards. - **Customers (admin):** look a customer up by name, email, phone or notes (orders and unpaid checkouts, matched by email case-insensitively); *Export data (JSON)* for access/portability requests; correct name/email/phone or remove notes on every record; *Erase* anonymises their orders (amounts, services and dates stay for the accounts) and deletes unpaid checkouts. Stripe and the email provider keep their own copies — handle those in their dashboards.
- **Retention:** daily at 03:15 UTC and on PocketBase start (`pocketbase/pb_hooks/privacy.pb.js`): unpaid checkouts are deleted after *N* days (default 30); orders are anonymised after *M* months (default 0 = never — set it once the accountant has said how long records must be kept). Orders with a booking still ahead are skipped; codes are anonymised with the same age once they have expired or are used up. Settings live in the `privacy` global. - **Retention:** daily at 03:15 UTC and on PocketBase start (`pocketbase/pb_hooks/privacy.pb.js`): unpaid checkouts are deleted after *N* days (default 30); orders are anonymised after *M* months (default 0 = never — set it once the accountant has said how long records must be kept). Orders with a booking still ahead are skipped. Settings live in the `privacy` global.
- **No third parties on page load:** fonts are bundled (`@fontsource-variable/*`; *Site design → Style* picks from them), not loaded from Google, and Stripe.js loads only when the customer presses Pay (`@stripe/stripe-js/pure`). The only cookies are the basket cookie and the admin login, so no cookie banner is needed — keep it that way, or add one before adding analytics. - **No third parties on page load:** fonts are bundled (`@fontsource/*`), not loaded from Google, and Stripe.js loads only when the customer presses Pay (`@stripe/stripe-js/pure`). The only cookies are the basket cookie and the admin login, so no cookie banner is needed — keep it that way, or add one before adding analytics.
- All customer-data reads and writes go through `/api/privacy/*` (signed-in admin only; `orders`/`baskets` are superuser-only collections). - All customer-data reads and writes go through `/api/privacy/*` (signed-in admin only; `orders`/`baskets` are superuser-only collections).
## Public routes (public app) ## Public routes (public app)

View file

@ -20,27 +20,14 @@
"@tiptap/starter-kit": "^3.23.4", "@tiptap/starter-kit": "^3.23.4",
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.28.2", "pocketbase": "^0.26.9",
"svelte-tiptap": "^3.0.1", "svelte-tiptap": "^3.0.1",
"tailwindcss": "^4.3.0", "tailwindcss": "^4.3.0",
"uuid": "^14.0.0" "uuid": "^14.0.0"
}, },
"devDependencies": { "devDependencies": {
"@fontsource-variable/cormorant-garamond": "^5.3.0", "@fontsource/dm-sans": "^5.3.0",
"@fontsource-variable/dm-sans": "^5.3.0", "@fontsource/playfair-display": "^5.3.0",
"@fontsource-variable/eb-garamond": "^5.3.0",
"@fontsource-variable/fraunces": "^5.3.0",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/josefin-sans": "^5.3.0",
"@fontsource-variable/libre-baskerville": "^5.3.0",
"@fontsource-variable/lora": "^5.3.0",
"@fontsource-variable/manrope": "^5.3.0",
"@fontsource-variable/montserrat": "^5.3.0",
"@fontsource-variable/nunito": "^5.3.0",
"@fontsource-variable/outfit": "^5.3.0",
"@fontsource-variable/playfair-display": "^5.3.0",
"@fontsource-variable/raleway": "^5.3.0",
"@fontsource-variable/work-sans": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -133,150 +120,20 @@
"license": "MIT", "license": "MIT",
"peer": true "peer": true
}, },
"node_modules/@fontsource-variable/cormorant-garamond": { "node_modules/@fontsource/dm-sans": {
"version": "5.3.0", "version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/cormorant-garamond/-/cormorant-garamond-5.3.0.tgz", "resolved": "https://registry.npmjs.org/@fontsource/dm-sans/-/dm-sans-5.3.0.tgz",
"integrity": "sha512-rgZJ/5w3hi60swAPnrOXpZf5wEH6NTrvm4H8D9Y4b1QIFUqlX14eM3QTMU/eAznjfh0eXpO1QUqsFhiy58aoMg==", "integrity": "sha512-lYJtMXXO28q1z+yz+z8XKd0s4hXaa9QdkETzkyD760sidCv5heI86weYA0sx0Nc4pAMAQTUuyf4gO44cYKKS9g==",
"dev": true, "dev": true,
"license": "OFL-1.1", "license": "OFL-1.1",
"funding": { "funding": {
"url": "https://github.com/sponsors/ayuhito" "url": "https://github.com/sponsors/ayuhito"
} }
}, },
"node_modules/@fontsource-variable/dm-sans": { "node_modules/@fontsource/playfair-display": {
"version": "5.3.0", "version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/dm-sans/-/dm-sans-5.3.0.tgz", "resolved": "https://registry.npmjs.org/@fontsource/playfair-display/-/playfair-display-5.3.0.tgz",
"integrity": "sha512-BpUG5bqePiDFMBM4ZtLSlPdAIOM990uB1dlXzIf4aw21yQR7BmykedLXXXMqGWsR18aMLOsbWccwJNh3ztTQaA==", "integrity": "sha512-uJSABalvdWc10fEPppQjQocamT21LEyRfzzWfRfqbkPz+sRv+kKpYDKyluBUskvJREkJTos9epj1WjQROGu99Q==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/eb-garamond": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/eb-garamond/-/eb-garamond-5.3.0.tgz",
"integrity": "sha512-656OJsA9Vv24yhqRZFEzXnzS2AYgKdEILLgHJYLzzXndgcWFKfSXFqzbRI5/6Yk1Yt7UfWrUeppE5nRQPQMwlQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/fraunces": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/fraunces/-/fraunces-5.3.0.tgz",
"integrity": "sha512-9BYGySn4AHEJdgp9Z28tQ3X+laJMEOITXkQarZXeloWQZDq5oOvXJ3kDA8c7MGIfpogIaZfjrQBqmda8POOCKA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/josefin-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/josefin-sans/-/josefin-sans-5.3.0.tgz",
"integrity": "sha512-duVgkuzE/co4iuIfJ7jM2qX0ED3b6qdY+SlSjNMs6zfhz7EE7kJxV0qF65hQCv1kN0A20j4FwsGAYJvfpU+iSg==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/libre-baskerville": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/libre-baskerville/-/libre-baskerville-5.3.0.tgz",
"integrity": "sha512-lIjXwDhcdr0OxSdzlAU4G7Tnny1LhgAiPFdp3/PjwRMqYt2JLU6pQiLwz/M5lRBs/kRtHwxknPUqRt37AnqPFg==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/lora": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/lora/-/lora-5.3.0.tgz",
"integrity": "sha512-2ph8KiZ8Bn141hWuC3ErtpJ+Ui8p2MJQn8TJNRSRmLmnCIOCtHfiBM9R7WLRPeUG/q6hXyHOxWQ8DvRSX+ixvQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/manrope": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/manrope/-/manrope-5.3.0.tgz",
"integrity": "sha512-6D5dgokHsWDDMtmXHznKa0hK229NN+1a4BLPmUCLqcO1Pw5EEhWY5RFt0AcXnVRAljFFPfRtLkJePQj6LSsV6g==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/montserrat": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/montserrat/-/montserrat-5.3.0.tgz",
"integrity": "sha512-7PaZoxaxrWLAyrhO46v65An9LhUhfkTExWLhfbywYZCnZEgg/W1rEHnlNmZKjNZ3nJTVYyicqxlJt10z/26yTA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/nunito": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito/-/nunito-5.3.0.tgz",
"integrity": "sha512-tw0ch7evIDSwoeUy+0XzocYHfbRWLeCRPJy22KgbrLjDLAbNw/fErBiil10Ssrs3Sjr55zaZrr36a975j8cBkQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/outfit": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/outfit/-/outfit-5.3.0.tgz",
"integrity": "sha512-fPb5XnYK0k7SbR++HEmm4+ZqDszmLKQ+sPRUr8oQ/KNC0vy6r6hazJFe8iYozv4cqlHbvJ/JECkJWrfDodUMVQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/playfair-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/playfair-display/-/playfair-display-5.3.0.tgz",
"integrity": "sha512-IHdzTvE8eGIXHteZql7KXoqdc3Gfm+Zs1u4XlSC3MeplkwviT3sx/P6gI0tLwg/xIYLF4ZJYveZ5V+bl9cnDwA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/raleway": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/raleway/-/raleway-5.3.0.tgz",
"integrity": "sha512-aSV2k+V6Zz+od0dHpBOzkVxEzmgEdiXcxDfant39jLOx+T89dielQRrZylukwK3Fp+FY255gPqz67ruOfs1rqA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/work-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/work-sans/-/work-sans-5.3.0.tgz",
"integrity": "sha512-le8h/OIIuhm5Z7TdvuMw0yKg2gaCZUiMec8zaumsVVjzeJRBPEF0bQI/MkaZDHCVzZDvZoP/O2LiGOSfDLSbaw==",
"dev": true, "dev": true,
"license": "OFL-1.1", "license": "OFL-1.1",
"funding": { "funding": {
@ -2499,9 +2356,9 @@
} }
}, },
"node_modules/pocketbase": { "node_modules/pocketbase": {
"version": "0.28.2", "version": "0.26.9",
"resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.28.2.tgz", "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.26.9.tgz",
"integrity": "sha512-5lS4g7iDZi90LxLai8kyUK4r5u1GkEAoZ3yuzTEFX97FyDQAoEmXWbTqf+pYA1hz5e/icBQu1MCUjM/9V8mitg==", "integrity": "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/postcss": { "node_modules/postcss": {

View file

@ -10,21 +10,8 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}, },
"devDependencies": { "devDependencies": {
"@fontsource-variable/cormorant-garamond": "^5.3.0", "@fontsource/dm-sans": "^5.3.0",
"@fontsource-variable/dm-sans": "^5.3.0", "@fontsource/playfair-display": "^5.3.0",
"@fontsource-variable/eb-garamond": "^5.3.0",
"@fontsource-variable/fraunces": "^5.3.0",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/josefin-sans": "^5.3.0",
"@fontsource-variable/libre-baskerville": "^5.3.0",
"@fontsource-variable/lora": "^5.3.0",
"@fontsource-variable/manrope": "^5.3.0",
"@fontsource-variable/montserrat": "^5.3.0",
"@fontsource-variable/nunito": "^5.3.0",
"@fontsource-variable/outfit": "^5.3.0",
"@fontsource-variable/playfair-display": "^5.3.0",
"@fontsource-variable/raleway": "^5.3.0",
"@fontsource-variable/work-sans": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -48,7 +35,7 @@
"@tiptap/starter-kit": "^3.23.4", "@tiptap/starter-kit": "^3.23.4",
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.28.2", "pocketbase": "^0.26.9",
"svelte-tiptap": "^3.0.1", "svelte-tiptap": "^3.0.1",
"tailwindcss": "^4.3.0", "tailwindcss": "^4.3.0",
"uuid": "^14.0.0" "uuid": "^14.0.0"

View file

@ -13,28 +13,9 @@
white-space: normal; white-space: normal;
} }
/* Site design → Style sets the --site-* variables (siteStyleVars in
$shared/theme) on the public site and the admin preview; without them
(the admin's own pages) every token below is its usual value. Corners,
shadows and widths are scaled here, so blocks just use rounded-xl,
shadow-sm, max-w-6xl… Buttons and chips use rounded-button (a pill when
Round); dots and avatars stay rounded-full. */
@theme { @theme {
--font-sans: var(--site-font-body, 'DM Sans Variable', ui-sans-serif, system-ui, sans-serif); --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
--font-serif: var(--site-font-heading, 'Playfair Display Variable', Georgia, serif); --font-serif: 'Playfair Display', Georgia, serif;
--radius-lg: calc(0.5rem * var(--site-corners, 1));
--radius-xl: calc(0.75rem * var(--site-corners, 1));
--radius-2xl: calc(1rem * var(--site-corners, 1));
--radius-card: calc(1.25rem * var(--site-corners, 1));
--radius-panel: calc(2rem * var(--site-corners, 1));
--radius-button: var(--site-button-radius, 9999px);
--shadow-sm: 0 1px 3px 0 rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 1px 2px -1px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 2px 4px -2px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 4px 6px -4px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-xl: 0 20px 25px -5px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 8px 10px -6px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--container-3xl: calc(48rem * var(--site-width, 1));
--container-6xl: calc(72rem * var(--site-width, 1));
--container-7xl: calc(80rem * var(--site-width, 1));
--color-warm: var(--color-bg, #faf8f5); --color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c); --color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b); --color-sage: var(--color-primary, #8a9a7b);
@ -73,9 +54,7 @@
--fg-body: var(--color-text, #2c2c2c); --fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5); background: var(--color-bg, #faf8f5);
color: var(--fg-body); color: var(--fg-body);
font-family: var(--font-sans); font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
/* Site design → Style → Text size; rem-sized spacing grows with it. */
font-size: var(--site-text-size, 100%);
} }
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ /* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
@ -105,7 +84,7 @@ h1,
h2, h2,
h3, h3,
h4 { h4 {
font-family: var(--font-serif); font-family: 'Playfair Display', Georgia, serif;
color: var(--fg-heading, #2c2c2c); color: var(--fg-heading, #2c2c2c);
} }
@ -130,36 +109,6 @@ h4 {
padding-left: 1.5rem; padding-left: 1.5rem;
} }
/* The visual editor wraps list items in <p>. */
.prose-wellness li > p {
margin: 0;
}
.prose-wellness ol {
list-style: decimal;
padding-left: 1.5rem;
}
/* Pull quote: a "Quote" in the visual editor. */
.prose-wellness blockquote {
margin: 0.75rem 0;
padding-left: 1.25rem;
border-left: 3px solid var(--color-primary, #8a9a7b);
font-family: var(--font-serif);
font-size: 1.35rem;
font-style: italic;
}
.prose-wellness.text-center blockquote {
border-left: 0;
padding-left: 0;
}
.prose-wellness hr {
margin: 2rem 0;
border-color: color-mix(in srgb, currentColor 20%, transparent);
}
.prose-wellness a { .prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline; text-decoration: underline;
@ -167,13 +116,12 @@ h4 {
} }
/* ── Scroll-reveal animations ── */ /* ── Scroll-reveal animations ── */
/* Kept short: blocks fading in while someone scrolls are what slows scrolling down. */
.reveal { .reveal {
opacity: 0; opacity: 0;
transform: translateY(16px); transform: translateY(30px);
transition: transition:
opacity 0.4s cubic-bezier(0.25, 0.1, 0.25, 1), opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 0.4s cubic-bezier(0.25, 0.1, 0.25, 1); transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
} }
.reveal-visible { .reveal-visible {
@ -184,8 +132,8 @@ h4 {
/* ── Hero fade-in stagger ── */ /* ── Hero fade-in stagger ── */
.animate-fade-in { .animate-fade-in {
opacity: 0; opacity: 0;
transform: translateY(12px); transform: translateY(20px);
animation: fadeInUp 0.5s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
} }
@keyframes fadeInUp { @keyframes fadeInUp {
@ -199,39 +147,3 @@ h4 {
html { html {
scroll-behavior: smooth; scroll-behavior: smooth;
} }
/* No animations on devices that can't keep up (scrollReveal.ts adds .plain-motion
to <html>) or for people whose device asks for less motion. */
html.plain-motion .reveal,
html.plain-motion .animate-fade-in {
opacity: 1;
transform: none;
transition: none;
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.reveal,
.animate-fade-in {
opacity: 1;
transform: none;
transition: none;
animation: none;
}
html {
scroll-behavior: auto;
}
}
/* Visual editor (RichTextEditor): roughly how the site shows text, sized for the sidebar. */
.rich-text h2 { font-size: 1.5rem; font-weight: 700; margin: 0.75rem 0 0.25rem; }
.rich-text h3 { font-size: 1.2rem; font-weight: 700; margin: 0.75rem 0 0.25rem; }
.rich-text p { margin: 0.4rem 0; }
.rich-text ul { list-style: disc; padding-left: 1.5rem; }
.rich-text ol { list-style: decimal; padding-left: 1.5rem; }
.rich-text blockquote { border-left: 3px solid var(--color-primary); padding-left: 1rem; font-style: italic; }
.rich-text hr { margin: 1rem 0; border-color: var(--color-base-300); }
.rich-text a { text-decoration: underline; }
.rich-text > :first-child { margin-top: 0; }
.rich-text li > p { margin: 0; }

View file

@ -30,7 +30,7 @@ export const handle: Handle = async ({ event, resolve }) => {
} }
if (isLoginRoute && isAuthed && event.request.method === 'GET') { if (isLoginRoute && isAuthed && event.request.method === 'GET') {
throw redirect(303, '/'); throw redirect(303, '/pages');
} }
const response = await resolve(event); const response = await resolve(event);

View file

@ -43,34 +43,6 @@
dropIndex = null; dropIndex = null;
} }
// Touch: phones don't fire HTML drag events, so the handle follows the finger with
// pointer events instead (the mouse keeps native drag-and-drop on the whole row).
let list = $state<HTMLUListElement>();
function touchDragStart(e: PointerEvent, index: number) {
if (e.pointerType === 'mouse') return;
e.preventDefault();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragIndex = index;
dropIndex = index;
}
function touchDragMove(e: PointerEvent) {
if (dragIndex === null || !list) return;
const rows = [...list.children] as HTMLElement[];
const over = rows.findIndex((row) => e.clientY < row.getBoundingClientRect().bottom);
dropIndex = over === -1 ? rows.length - 1 : over;
// The handle blocks scrolling, so scroll for the finger near the screen's edges.
if (e.clientY < 64) window.scrollBy(0, -12);
else if (e.clientY > window.innerHeight - 64) window.scrollBy(0, 12);
}
function touchDragEnd() {
if (dragIndex !== null && dropIndex !== null) drop(dropIndex);
dragIndex = null;
dropIndex = null;
}
function moveBy(index: number, delta: number) { function moveBy(index: number, delta: number) {
const to = index + delta; const to = index + delta;
if (to >= 0 && to < blocks.length) onMove(index, to); if (to >= 0 && to < blocks.length) onMove(index, to);
@ -79,7 +51,7 @@
<!-- `isolate` on each row: the delete button's z-indexed layers must stay <!-- `isolate` on each row: the delete button's z-indexed layers must stay
inside their row, or they paint over dropdowns like "Add block". --> inside their row, or they paint over dropdowns like "Add block". -->
<ul class="space-y-2" bind:this={list}> <ul class="space-y-2">
{#each blocks as block, i (block.id)} {#each blocks as block, i (block.id)}
<li <li
class="isolate flex items-center gap-2 rounded-box border bg-base-100 p-2 pl-3 shadow-sm transition-colors {selectedId === block.id ? 'border-primary ring-1 ring-primary' : 'border-base-300 hover:border-base-content/30'}" class="isolate flex items-center gap-2 rounded-box border bg-base-100 p-2 pl-3 shadow-sm transition-colors {selectedId === block.id ? 'border-primary ring-1 ring-primary' : 'border-base-300 hover:border-base-content/30'}"
@ -106,18 +78,7 @@
dropIndex = null; dropIndex = null;
}} }}
> >
<span <span class="cursor-grab select-none text-lg text-base-content/40" aria-hidden="true" title="Drag to reorder">⠿</span>
class="-my-2 -ml-2 cursor-grab touch-none select-none px-2 py-2 text-lg text-base-content/40"
aria-hidden="true"
title="Drag to reorder"
onpointerdown={(e) => touchDragStart(e, i)}
onpointermove={touchDragMove}
onpointerup={touchDragEnd}
onpointercancel={() => {
dragIndex = null;
dropIndex = null;
}}
>⠿</span>
<button <button
type="button" type="button"
class="flex-1 truncate py-1 text-left font-semibold" class="flex-1 truncate py-1 text-left font-semibold"

View file

@ -1,84 +0,0 @@
<script lang="ts">
// Income per month as bars, one series (so no legend: the section title names
// it). The month-by-month table below it on the dashboard is its table view.
// Drawn at the box's real pixel width so labels stay readable on a phone.
/** `label` goes under the bar; `name` (e.g. "October 2026") heads the tooltip. */
type Month = { month: string; label: string; name: string; income: number; orders: number };
let {
months,
format,
tickFormat = format,
current = ''
}: { months: Month[]; format: (amount: number) => string; tickFormat?: (amount: number) => string; current?: string } = $props();
let width = $state(600);
const height = 220;
const pad = { top: 12, right: 8, bottom: 28, left: 64 };
let plotWidth = $derived(Math.max(width - pad.left - pad.right, 100));
const plotHeight = height - pad.top - pad.bottom;
// A 1-2-5 step giving about four gridlines.
let ticks = $derived.by(() => {
const max = Math.max(...months.map((m) => m.income), 0);
if (max <= 0) return [0];
const rough = max / 4;
const magnitude = 10 ** Math.floor(Math.log10(rough));
const step = [1, 2, 5, 10].map((n) => n * magnitude).find((n) => n >= rough)!;
return Array.from({ length: Math.ceil(max / step) + 1 }, (_, i) => i * step);
});
let top = $derived(ticks.at(-1) || 1);
let slot = $derived(plotWidth / Math.max(months.length, 1));
// Thin bars: at most 28px, with the gap between them clearly wider than 2px.
let barWidth = $derived(Math.min(28, slot * 0.6));
const y = (value: number) => pad.top + plotHeight - (value / top) * plotHeight;
/** A bar with 4px rounded top corners, square on the baseline. */
function barPath(x: number, value: number) {
const h = (value / top) * plotHeight;
if (h <= 0) return '';
const r = Math.min(4, h, barWidth / 2);
const yTop = pad.top + plotHeight - h;
const base = pad.top + plotHeight;
return `M${x},${base}V${yTop + r}Q${x},${yTop} ${x + r},${yTop}H${x + barWidth - r}Q${x + barWidth},${yTop} ${x + barWidth},${yTop + r}V${base}Z`;
}
let hovered = $state<number | null>(null);
// Every month labelled when there's room, else every other one (current month always).
let labelEvery = $derived(slot < 40 ? 2 : 1);
</script>
<div class="relative" bind:clientWidth={width}>
<svg {width} {height} role="img" aria-label="Income per month, last {months.length} months. The table below lists the figures.">
{#each ticks as tick (tick)}
<line x1={pad.left} x2={pad.left + plotWidth} y1={y(tick)} y2={y(tick)} class="stroke-base-content/10" stroke-width="1" />
<text x={pad.left - 8} y={y(tick)} dy="0.32em" text-anchor="end" class="fill-base-content/60 text-[11px] tabular-nums">{tickFormat(tick)}</text>
{/each}
{#each months as m, i (m.month)}
{@const x = pad.left + i * slot + (slot - barWidth) / 2}
<path d={barPath(x, m.income)} class={hovered === null || hovered === i ? 'fill-primary' : 'fill-primary/40'} />
{#if i % labelEvery === (months.length - 1) % labelEvery || m.month === current}
<text x={x + barWidth / 2} y={height - 8} text-anchor="middle" class="text-[11px] {m.month === current ? 'fill-base-content font-semibold' : 'fill-base-content/60'}">{m.label}</text>
{/if}
<!-- Hit target: the whole column, much bigger than the bar. -->
<rect
x={pad.left + i * slot}
y={pad.top}
width={slot}
height={plotHeight}
fill="transparent"
role="presentation"
onpointerenter={() => (hovered = i)}
onpointerleave={() => (hovered = null)}
/>
{/each}
</svg>
{#if hovered !== null}
{@const m = months[hovered]}
{@const left = Math.min(Math.max(pad.left + hovered * slot + slot / 2, 70), width - 70)}
<div class="pointer-events-none absolute -translate-x-1/2 whitespace-nowrap rounded-box bg-base-100 px-3 py-2 text-sm shadow-lg ring-1 ring-base-300" style="left: {left}px; top: {Math.max(y(m.income) - 64, 0)}px">
<p class="font-semibold">{m.name}</p>
<p class="tabular-nums">{format(m.income)} · {m.orders} {m.orders === 1 ? 'order' : 'orders'}</p>
</div>
{/if}
</div>

View file

@ -1,26 +0,0 @@
<script lang="ts">
import { browser } from '$app/environment';
import { fly, slide } from 'svelte/transition';
// The result banner of a save, like Site design's: "Saved." goes away by itself
// after a moment; an error stays until the next save. Pass the action's `form`
// (or null for results that belong elsewhere); each new result shows again.
let { result, class: className = '' } = $props<{ result: { ok?: boolean; message?: string } | null | undefined; class?: string }>();
let shown = $state(false);
$effect(() => {
// Not reading `shown` here: that would re-run this when the timer hides it.
const message = !!result?.message;
shown = message;
if (!message || !result?.ok) return;
const timer = setTimeout(() => (shown = false), 2500);
return () => clearTimeout(timer);
});
const motion = (ms: number) => (browser && matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : ms);
</script>
{#if shown && result?.message}
<div class="alert {className}" class:alert-success={result.ok} class:alert-error={!result.ok} role="status" in:fly={{ y: 8, duration: motion(200) }} out:slide={{ duration: motion(350) }}>
{result.message}
</div>
{/if}

View file

@ -11,10 +11,7 @@ export const blockLabels: Record<BlockType, string> = {
testimonials: 'Testimonials', testimonials: 'Testimonials',
upcoming_calendar: 'Upcoming Calendar', upcoming_calendar: 'Upcoming Calendar',
shop: 'Shop', shop: 'Shop',
checkout: 'Checkout', checkout: 'Checkout'
cards: 'Cards',
faq: 'FAQ',
html: 'HTML'
}; };
export const blockTypes = Object.keys(blockLabels) as BlockType[]; export const blockTypes = Object.keys(blockLabels) as BlockType[];
@ -36,7 +33,7 @@ export function createBlock(type: BlockType): ContentBlock {
heading: 'Holistic and Experiential Learning about Happiness', heading: 'Holistic and Experiential Learning about Happiness',
subheading: 'Individual sessions, workshops and events in Oslo', subheading: 'Individual sessions, workshops and events in Oslo',
buttonLabel: 'BOOK NOW', buttonLabel: 'BOOK NOW',
buttonUrl: '' buttonUrl: '/book'
}; };
break; break;
case 'button': case 'button':
@ -73,9 +70,7 @@ export function createBlock(type: BlockType): ContentBlock {
title: 'Our Services', title: 'Our Services',
itemTypeFilter: 'all', itemTypeFilter: 'all',
itemIds: [], itemIds: [],
layout: 'grid', layout: 'grid'
sort: 'recommended',
showSort: false
}; };
break; break;
case 'checkout': case 'checkout':
@ -85,24 +80,6 @@ export function createBlock(type: BlockType): ContentBlock {
notesLabel: 'Notes or special requests' notesLabel: 'Notes or special requests'
}; };
break; break;
case 'cards':
base.data = {
heading: 'Section heading',
intro: '',
align: 'center',
style: 'image',
items: [1, 2, 3].map((n) => ({ imageUrl: '', imageAlt: '', title: `Card ${n}`, subtitle: '', text: '<p>A sentence or two.</p>', href: '', linkLabel: '' }))
};
break;
case 'faq':
base.data = {
heading: 'Questions people ask',
items: [{ question: 'What happens in the first session?', answer: '<p>Answer it here.</p>' }]
};
break;
case 'html':
base.data = { html: '' };
break;
} }
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 }; base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base; return base;

View file

@ -2,7 +2,7 @@
import type { BlockType, ContentBlock } from '$lib/types'; import type { BlockType, ContentBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults'; import { blockLabels } from '$lib/admin/blockDefaults';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImagePicker from './ImagePicker.svelte'; import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte'; import ColorField from './ColorField.svelte';
import ShopBlockEditor from './ShopBlockEditor.svelte'; import ShopBlockEditor from './ShopBlockEditor.svelte';
@ -38,18 +38,6 @@
updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) }); updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) });
} }
function moveArrayItem(key: string, index: number, by: number) {
if (!block) return;
const items = [...(block.data[key] || [])];
const to = index + by;
if (to < 0 || to >= items.length) return;
[items[index], items[to]] = [items[to], items[index]];
updateData({ [key]: items });
}
// "#prices" links jump to the block with anchor "prices"; keep it to characters that work in an address.
const toAnchor = (value: string) => value.trim().toLowerCase().replace(/^#/, '').replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
function toggleCategory(category: string) { function toggleCategory(category: string) {
if (!block) return; if (!block) return;
const categories = block.data.categories || []; const categories = block.data.categories || [];
@ -88,13 +76,9 @@
{#if block.type === 'text'} {#if block.type === 'text'}
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> <RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
<div class="mt-4 space-y-3">
<SegmentedControl label="Alignment" options={['left', 'center']} value={block.data.align === 'center' ? 'center' : 'left'} onChange={(v) => updateData({ align: v })} />
<SegmentedControl label="Text size" options={['normal', 'small']} value={block.data.size === 'small' ? 'small' : 'normal'} onChange={(v) => updateData({ size: v })} formatLabel={(v) => (v === 'small' ? 'Small (footnote)' : 'Normal')} />
</div>
{:else if block.type === 'image_text'} {:else if block.type === 'image_text'}
<div class="space-y-4"> <div class="space-y-4">
<ImagePicker url={block.data.url} alt={block.data.alt} onChange={(image) => updateData({ url: image.url, alt: image.alt })} /> <ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
<SegmentedControl label="Image position" options={['left', 'right']} value={block.data.imagePosition === 'right' ? 'right' : 'left'} onChange={(v) => updateData({ imagePosition: v })} /> <SegmentedControl label="Image position" options={['left', 'right']} value={block.data.imagePosition === 'right' ? 'right' : 'left'} onChange={(v) => updateData({ imagePosition: v })} />
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> <RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
</div> </div>
@ -117,7 +101,7 @@
{@render field('Subheading', block.data.subheading || '', (subheading) => updateData({ subheading }))} {@render field('Subheading', block.data.subheading || '', (subheading) => updateData({ subheading }))}
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
{@render field('Button label', block.data.buttonLabel || '', (buttonLabel) => updateData({ buttonLabel }))} {@render field('Button label', block.data.buttonLabel || '', (buttonLabel) => updateData({ buttonLabel }))}
{@render field('Button URL', block.data.buttonUrl || '', (buttonUrl) => updateData({ buttonUrl }), 'Empty = the CTA button’s address')} {@render field('Button URL', block.data.buttonUrl || '', (buttonUrl) => updateData({ buttonUrl }), '/page or https://…')}
</div> </div>
{:else if block.type === 'button'} {:else if block.type === 'button'}
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
@ -179,97 +163,23 @@
<ShopBlockEditor {block} {items} {onChange} /> <ShopBlockEditor {block} {items} {onChange} />
{:else if block.type === 'checkout'} {:else if block.type === 'checkout'}
<CheckoutBlockEditor {block} {onChange} /> <CheckoutBlockEditor {block} {onChange} />
{:else if block.type === 'cards'}
{@render field('Heading', block.data.heading || '', (heading) => updateData({ heading }), 'Optional')}
<label class="fieldset">
<span class="fieldset-legend">Intro</span>
<textarea class="textarea w-full" rows="2" placeholder="Optional" value={block.data.intro || ''} oninput={(e) => updateData({ intro: e.currentTarget.value })}></textarea>
</label>
<div class="mt-2 space-y-3">
<SegmentedControl label="Heading" options={['left', 'center']} value={block.data.align === 'center' ? 'center' : 'left'} onChange={(v) => updateData({ align: v })} />
<SegmentedControl label="Cards show" options={['image', 'numbered']} value={block.data.style === 'numbered' ? 'numbered' : 'image'} onChange={(v) => updateData({ style: v })} formatLabel={(v) => (v === 'image' ? 'A picture' : 'A number')} />
</div>
<div class="mt-4 space-y-3">
{#each block.data.items || [] as card, i}
<div class="rounded-box border border-base-300 p-3">
<div class="mb-2 flex items-center gap-1">
<span class="flex-1 text-sm font-semibold text-base-content/60">Card {i + 1}</span>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move card up" disabled={i === 0} onclick={() => moveArrayItem('items', i, -1)}>↑</button>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move card down" disabled={i === block.data.items.length - 1} onclick={() => moveArrayItem('items', i, 1)}>↓</button>
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
{#if block.data.style !== 'numbered'}
<ImagePicker url={card.imageUrl} alt={card.imageAlt} onChange={(image) => updateArray('items', i, { imageUrl: image.url, imageAlt: image.alt })} />
{/if}
<div class="grid gap-x-3 md:grid-cols-2">
{@render field('Title', card.title || '', (title) => updateArray('items', i, { title }))}
{@render field('Subtitle', card.subtitle || '', (subtitle) => updateArray('items', i, { subtitle }), 'Optional, shown lighter')}
</div>
<span class="fieldset-legend">Text</span>
<RichTextEditor compact value={card.text} onChange={(text) => updateArray('items', i, { text })} />
<div class="grid gap-x-3 md:grid-cols-2">
{@render field('Link', card.href || '', (href) => updateArray('items', i, { href }), '/page, #anchor or https://…')}
{@render field('Link text', card.linkLabel || '', (linkLabel) => updateArray('items', i, { linkLabel }), 'Optional, e.g. Read more')}
</div>
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { imageUrl: '', imageAlt: '', title: '', subtitle: '', text: '', href: '', linkLabel: '' })}>Add card</button>
<p class="text-sm text-base-content/60">With a link, the whole card is clickable.</p>
</div>
{:else if block.type === 'faq'}
{@render field('Heading', block.data.heading || '', (heading) => updateData({ heading }), 'Optional')}
<div class="mt-3 space-y-3">
{#each block.data.items || [] as item, i}
<div class="rounded-box border border-base-300 p-3">
<div class="mb-2 flex items-center gap-1">
<span class="flex-1 text-sm font-semibold text-base-content/60">Question {i + 1}</span>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move question up" disabled={i === 0} onclick={() => moveArrayItem('items', i, -1)}>↑</button>
<button class="btn btn-ghost btn-xs" type="button" aria-label="Move question down" disabled={i === block.data.items.length - 1} onclick={() => moveArrayItem('items', i, 1)}>↓</button>
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
</div>
<input class="input mb-2 w-full" aria-label="Question" placeholder="Question" value={item.question} oninput={(e) => updateArray('items', i, { question: e.currentTarget.value })} />
<RichTextEditor compact value={item.answer} onChange={(answer) => updateArray('items', i, { answer })} />
</div>
{/each}
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { question: '', answer: '' })}>Add question</button>
<p class="text-sm text-base-content/60">Visitors click a question to show its answer.</p>
</div>
{:else if block.type === 'html'}
<label class="fieldset">
<span class="fieldset-legend">HTML</span>
<textarea class="textarea w-full font-mono text-xs" rows="14" spellcheck="false" value={block.data.html || ''} oninput={(e) => updateData({ html: e.currentTarget.value })}></textarea>
<span class="label">For embeds (a map, a video) and one-offs. Use inline styles: CSS classes from elsewhere don't apply here. Scripts don't run. Anything loaded from another site (an embed, an image) sends visitors' IP addresses there, so it may need mentioning in the privacy policy.</span>
</label>
{/if} {/if}
<div class="mt-6 space-y-3 rounded-box border border-base-300 p-4"> <div class="mt-6 space-y-3 rounded-box border border-base-300 p-4">
<div class="@container">
<label class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3">
<span class="shrink-0 text-sm font-bold @sm:w-28">Anchor</span>
<input class="input input-sm w-full @sm:flex-1" placeholder="e.g. prices — then link to #prices" value={block.data._anchor || ''} onchange={(e) => updateData({ _anchor: toAnchor(e.currentTarget.value) })} />
</label>
</div>
<hr class="border-base-300" />
<SegmentedControl label="Background" strong options={['none', 'color', 'image']} value={block.data._background?.type || 'none'} onChange={(type) => updateBackground({ type })} /> <SegmentedControl label="Background" strong options={['none', 'color', 'image']} value={block.data._background?.type || 'none'} onChange={(type) => updateBackground({ type })} />
{#if block.data._background?.type === 'color'} {#if block.data._background?.type === 'color'}
<ColorField label="Color" value={block.data._background?.color || ''} fallback="#66755d" placeholder="#66755d" onChange={(color) => updateBackground({ color })} /> <ColorField label="Color" value={block.data._background?.color || ''} fallback="#66755d" placeholder="#66755d" onChange={(color) => updateBackground({ color })} />
{:else if block.data._background?.type === 'image'} {:else if block.data._background?.type === 'image'}
<ImagePicker url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateBackground({ imageUrl: image.url, imageAlt: image.alt })} /> <ImageUploader url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateBackground({ imageUrl: image.url, imageAlt: image.alt })} />
<SegmentedControl label="Attachment" options={['scroll', 'fixed']} value={block.data._background?.attachment || 'scroll'} onChange={(attachment) => updateBackground({ attachment })} /> <SegmentedControl label="Attachment" options={['scroll', 'fixed']} value={block.data._background?.attachment || 'scroll'} onChange={(attachment) => updateBackground({ attachment })} />
{@const overlay = block.data._background?.overlay ? (block.data._background?.overlayOpacity ?? 40) : 0} <SegmentedControl
<!-- A slider: ten buttons don't fit a phone. --> label="Overlay"
<div class="@container"> options={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]}
<label class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3"> value={block.data._background?.overlay ? (block.data._background?.overlayOpacity ?? 40) : 0}
<span class="shrink-0 text-sm font-medium @sm:w-28">Overlay</span> onChange={(v) => updateBackground({ overlay: Number(v) > 0, overlayOpacity: Number(v) })}
<span class="flex flex-1 items-center gap-3"> formatLabel={(v) => (Number(v) === 0 ? 'None' : `${v}%`)}
<input class="range range-sm flex-1" type="range" min="0" max="90" step="10" value={overlay} oninput={(e) => updateBackground({ overlay: Number(e.currentTarget.value) > 0, overlayOpacity: Number(e.currentTarget.value) })} /> />
<span class="w-12 text-right text-sm tabular-nums">{overlay === 0 ? 'None' : `${overlay}%`}</span>
</span>
</label>
</div>
{/if} {/if}
<hr class="border-base-300" /> <hr class="border-base-300" />

View file

@ -19,22 +19,19 @@
const isHex = (v: string) => /^#[0-9a-f]{6}$/i.test(v); const isHex = (v: string) => /^#[0-9a-f]{6}$/i.test(v);
</script> </script>
<!-- Label above the field in a narrow row, like SegmentedControl. --> <div class="flex items-center gap-3">
<div class="@container"> <span class="w-28 shrink-0 text-sm font-medium">{label}</span>
<div class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3"> <div class="join flex-1">
<span class="shrink-0 text-sm font-medium @sm:w-28">{label}</span> <input
<div class="join flex-1"> class="input join-item w-12 cursor-pointer p-1"
<input type="color"
class="input join-item w-12 cursor-pointer p-1" aria-label="{label} picker"
type="color" value={isHex(value) ? value : fallback}
aria-label="{label} picker" oninput={(e) => onChange(e.currentTarget.value)}
value={isHex(value) ? value : fallback} />
oninput={(e) => onChange(e.currentTarget.value)} <input class="input join-item min-w-0 flex-1 font-mono text-sm" aria-label={label} {placeholder} {value} oninput={(e) => onChange(e.currentTarget.value.trim())} />
/> {#if value}
<input class="input join-item min-w-0 flex-1 font-mono text-sm" aria-label={label} {placeholder} {value} oninput={(e) => onChange(e.currentTarget.value.trim())} /> <button class="btn join-item" type="button" aria-label="Reset {label} to default" title="Reset to default" onclick={() => onChange('')}>✕</button>
{#if value} {/if}
<button class="btn join-item" type="button" aria-label="Reset {label} to default" title="Reset to default" onclick={() => onChange('')}>✕</button>
{/if}
</div>
</div> </div>
</div> </div>

View file

@ -2,7 +2,7 @@
import type { EmailBlock, EmailBlockType } from '$lib/types'; import type { EmailBlock, EmailBlockType } from '$lib/types';
import { emailBlockLabels } from '$lib/admin/emailBlockDefaults'; import { emailBlockLabels } from '$lib/admin/emailBlockDefaults';
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImagePicker from './ImagePicker.svelte'; import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte'; import ColorField from './ColorField.svelte';
@ -36,7 +36,7 @@
<p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p> <p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p>
{:else if block.type === 'image'} {:else if block.type === 'image'}
<div class="space-y-4"> <div class="space-y-4">
<ImagePicker url={block.data.url} alt={block.data.alt} onChange={(image) => updateData({ url: image.url, alt: image.alt })} /> <ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
<SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} /> <SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} />
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} /> <SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} />
<label class="fieldset"> <label class="fieldset">

View file

@ -1,205 +0,0 @@
<script lang="ts">
import { onMount, type Snippet } from 'svelte';
import { altFromFileName, uploadMedia } from '$lib/pb';
import MediaLibrary from './MediaLibrary.svelte';
type ImageValue = { url: string; alt: string; id?: string };
/**
* The one image field of the admin: choose a file, drag one in, paste one (Ctrl+V while the
* picker has focus, or the Paste button) or pick an uploaded one from the library, and edit
* the address and alt text. Firefox and Safari show their own small "Paste" confirmation for
* the Paste button (a page can't read the clipboard unasked); Ctrl+V needs none.
* `id` is the media record of a new upload or library pick ('' after Remove or a typed address; left out when
* only the alt text changed), for fields that store a relation instead of an address
* (Services & products). Callers that store an address take `url` and `alt` only.
*/
let {
url = '',
alt = '',
withUrl = true,
altHint = 'What the image shows, for people who can’t see it',
uploading = $bindable(false),
children,
onChange = (value: ImageValue) => {}
} = $props<{
url?: string;
alt?: string;
/** Show the Image URL field (off where an uploaded media record is required). */
withUrl?: boolean;
/** Placeholder of Alt text; '' hides the Alt text field (where the alt text comes from elsewhere). */
altHint?: string;
/** True while a file uploads (bind it to hold off a form's Save). */
uploading?: boolean;
/** Extra notes beside the box when there are no fields to show. */
children?: Snippet;
onChange?: (value: ImageValue) => void;
}>();
// What the media collection accepts (pb_schema.json → media.file).
const TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
const MAX_BYTES = 20 * 1024 * 1024;
let dragging = $state(false);
let error = $state('');
let canReadClipboard = $state(false);
let libraryOpen = $state(false);
let fileInput = $state<HTMLInputElement>();
let altInput = $state<HTMLInputElement>();
onMount(() => {
canReadClipboard = typeof navigator.clipboard?.read === 'function';
});
/** `pasted`: a clipboard image is called "image.png", so its name makes no alt text. */
async function upload(file: File, pasted = false) {
error = '';
if (!TYPES.includes(file.type)) {
error = 'That isn’t an image the site can use. Use a JPG, PNG, WebP, GIF or SVG.';
return;
}
if (file.size > MAX_BYTES) {
error = 'That image is larger than 20 MB. Make it smaller and try again.';
return;
}
uploading = true;
try {
// Keep a hand-written alt text; otherwise use the one made from the file name.
const newAlt = alt || (pasted ? '' : altFromFileName(file.name));
const result = await uploadMedia(file, newAlt);
onChange({ url: result.url, alt: newAlt, id: result.record.id });
if (pasted && !newAlt) altInput?.focus();
} catch (e) {
error = e instanceof Error ? e.message : 'Upload failed';
} finally {
uploading = false;
}
}
function pastedFile(blob: Blob) {
const extension = blob.type.split('/')[1]?.replace('svg+xml', 'svg') || 'png';
const stamp = new Date().toISOString().slice(0, 19).replace(/\D/g, '');
return new File([blob], `pasted-${stamp}.${extension}`, { type: blob.type });
}
function onFileChosen(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (file) upload(file);
}
function onDrop(event: DragEvent) {
event.preventDefault();
dragging = false;
const file = event.dataTransfer?.files?.[0];
if (file && !uploading) upload(file);
}
// Paste anywhere in the picker: an image is uploaded; text goes into the focused field as usual.
function onPaste(event: ClipboardEvent) {
const file = [...(event.clipboardData?.files || [])].find((f) => f.type.startsWith('image/'));
if (!file || uploading) return;
event.preventDefault();
upload(pastedFile(file), true);
}
async function pasteFromButton() {
error = '';
try {
for (const item of await navigator.clipboard.read()) {
const type = item.types.find((t) => t.startsWith('image/'));
if (type) return upload(pastedFile(await item.getType(type)), true);
}
error = 'There’s no image on the clipboard. Copy an image first (right-click it → Copy image).';
} catch {
error = 'The browser didn’t allow reading the clipboard. Click the image box and press Ctrl+V (⌘V on a Mac) instead.';
}
}
// An image from the library; like an upload, a hand-written alt text is kept.
function pick(media: { id: string; url: string; alt: string }) {
error = '';
onChange({ url: media.url, alt: alt || media.alt, id: media.id });
}
function remove() {
error = '';
onChange({ url: '', alt: '', id: '' });
}
</script>
<!-- Paste is caught here, from whichever button or field inside has focus. -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="@container" onpaste={onPaste}>
<div class="grid gap-x-5 gap-y-3 @md:grid-cols-[11rem_minmax(0,1fr)] @md:items-center">
<div class="group relative">
<button
type="button"
class="relative flex h-40 w-full flex-col items-center justify-center overflow-hidden rounded-box p-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary {dragging ? 'border-2 border-dashed border-primary bg-primary/10' : url ? 'border border-base-300 bg-base-200' : 'border-2 border-dashed border-base-300 hover:border-primary'}"
aria-label={url ? 'Replace image: choose a file, drop one here, or paste one' : 'Add image: choose a file, drop one here, or paste one'}
aria-busy={uploading}
onclick={() => uploading || fileInput?.click()}
ondragenter={(e) => { e.preventDefault(); dragging = true; }}
ondragover={(e) => e.preventDefault()}
ondragleave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) dragging = false; }}
ondrop={onDrop}
>
{#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span>
<span class="mt-2 text-sm text-base-content/60">Uploading…</span>
{:else if url && !dragging}
<img class="max-h-full max-w-full rounded object-contain" src={url} alt="" />
<span class="absolute inset-0 flex items-center justify-center bg-black/55 p-4 text-center text-sm font-medium text-white opacity-0 transition-opacity group-hover:opacity-100 group-has-[:focus-visible]:opacity-100">Click, drop or paste to replace</span>
{:else}
<svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909M3.75 21h16.5A1.5 1.5 0 0 0 21.75 19.5V4.5A1.5 1.5 0 0 0 20.25 3H3.75A1.5 1.5 0 0 0 2.25 4.5v15A1.5 1.5 0 0 0 3.75 21Zm10.5-11.25h.008v.008h-.008V9.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" />
</svg>
<span class="text-center text-sm font-medium text-base-content/70">{dragging ? 'Drop to upload' : 'Click, drop or paste an image'}</span>
<span class="text-xs text-base-content/40">JPG, PNG, WebP, GIF, SVG</span>
{/if}
</button>
{#if url && !uploading}
<button class="btn btn-circle btn-sm absolute top-2 right-2 border-base-300 bg-base-100 text-error shadow-sm" type="button" aria-label="Remove image" title="Remove image" onclick={remove}>
<svg class="size-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /></svg>
</button>
{/if}
</div>
{#if withUrl || altHint}
<div class="min-w-0">
{#if altHint}
<label class="fieldset pt-0">
<span class="fieldset-legend pt-0">Alt text</span>
<input class="input w-full" value={alt} placeholder={altHint} title={altHint} bind:this={altInput} oninput={(e) => onChange({ url, alt: e.currentTarget.value })} />
</label>
{/if}
{#if withUrl}
<label class="fieldset {altHint ? '' : 'pt-0'}">
<span class="fieldset-legend {altHint ? '' : 'pt-0'}">Image URL</span>
<input class="input w-full text-base-content/70" value={url} placeholder="Filled in by an upload, or https://…" oninput={(e) => onChange({ url: e.currentTarget.value, alt, id: '' })} />
</label>
{/if}
</div>
{:else}
<div class="space-y-2 text-sm text-base-content/60">
<p>Click the box to choose a file, drag an image onto it, or click it and press Ctrl+V to paste.</p>
{@render children?.()}
</div>
{/if}
<div class="flex gap-2 @md:col-span-2">
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={() => (libraryOpen = true)}>Pick from library</button>
{#if canReadClipboard}
<button class="btn btn-sm flex-1" type="button" disabled={uploading} onclick={pasteFromButton} title="Upload the image you copied">Paste</button>
{/if}
</div>
</div>
{#if error}
<div class="alert alert-error mt-3 text-sm" role="alert">{error}</div>
{/if}
<input class="hidden" type="file" accept={TYPES.join(',')} onchange={onFileChosen} bind:this={fileInput} />
<MediaLibrary bind:open={libraryOpen} onPick={pick} />
</div>

View file

@ -0,0 +1,107 @@
<script lang="ts">
import { uploadMedia } from '$lib/pb';
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
url?: string;
alt?: string;
onChange?: (value: { url: string; alt: string }) => void;
}>();
let uploading = $state(false);
let error = $state('');
let fileInput = $state<HTMLInputElement>();
// Local state synced from props so reactivity works reliably in Svelte 5
let localUrl = $state(urlProp);
let localAlt = $state(altProp);
$effect(() => { localUrl = urlProp; });
$effect(() => { localAlt = altProp; });
function emitChange() {
onChange({ url: localUrl, alt: localAlt });
}
async function handleFile(event: Event) {
const file = (event.currentTarget as HTMLInputElement).files?.[0];
if (!file) return;
uploading = true;
error = '';
try {
const result = await uploadMedia(file);
localUrl = result.url;
// Keep a hand-written alt text; otherwise use the one derived from the filename.
if (!localAlt) localAlt = result.record?.alt || '';
emitChange();
} catch (e) {
error = e instanceof Error ? e.message : 'Upload failed';
console.error('Image upload error:', e);
} finally {
uploading = false;
}
}
function removeImage() {
localUrl = '';
localAlt = '';
emitChange();
if (fileInput) fileInput.value = '';
}
</script>
<div class="grid grid-cols-[1fr_1.5fr] gap-4">
<!-- Drop zone / upload area -->
<div
class="flex h-32 cursor-pointer flex-col items-center justify-center rounded-box border-2 border-dashed p-3 transition-colors hover:border-primary {localUrl ? 'border-success/40' : 'border-base-300'}"
role="button"
tabindex="0"
onclick={() => fileInput?.click()}
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
>
{#if uploading}
<span class="loading loading-spinner loading-lg text-primary"></span>
<p class="mt-3 text-sm text-base-content/60">Uploading…</p>
{:else if localUrl}
<div class="relative w-full">
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
<button
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
type="button"
onclick={(e) => { e.stopPropagation(); removeImage(); }}
title="Remove image"
>✕</button>
</div>
{:else}
<svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
</svg>
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
<p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
{/if}
</div>
{#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div>
{/if}
<input
class="hidden"
type="file"
accept="image/*"
onchange={handleFile}
disabled={uploading}
bind:this={fileInput}
/>
<!-- URL & Alt fields -->
<div>
<label class="fieldset pt-0">
<span class="fieldset-legend">Image URL</span>
<input class="input w-full" bind:value={localUrl} oninput={() => emitChange()} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Alt text</span>
<input class="input w-full" bind:value={localAlt} oninput={() => emitChange()} />
</label>
</div>
</div>

View file

@ -1,98 +0,0 @@
<script lang="ts">
import { untrack } from 'svelte';
import Modal from '$lib/admin/Modal.svelte';
import { thumbUrl } from '$shared/pb';
type Media = { id: string; url: string; alt: string };
// The images already uploaded to `media`, to reuse one instead of uploading it again.
let { open = $bindable(false), onPick = (media: Media) => {} } = $props<{
open?: boolean;
onPick?: (media: Media) => void;
}>();
let items = $state<Media[]>([]);
let page = $state(0);
let totalPages = $state(0);
let query = $state('');
let loading = $state(false);
let error = $state('');
let searchTimer: ReturnType<typeof setTimeout> | undefined;
async function load(nextPage: number) {
loading = true;
error = '';
try {
const res = await fetch(`/api/media?page=${nextPage}&q=${encodeURIComponent(query)}`);
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.message || `Loading failed (${res.status})`);
const data = await res.json();
items = nextPage === 1 ? data.items : [...items, ...data.items];
page = data.page;
totalPages = data.totalPages;
} catch (e) {
error = e instanceof Error ? e.message : 'Loading failed';
} finally {
loading = false;
}
}
// Fresh list each time it opens, so new uploads show up.
$effect(() => {
if (open) untrack(() => {
query = '';
load(1);
});
});
function search(value: string) {
query = value;
clearTimeout(searchTimer);
searchTimer = setTimeout(() => load(1), 250);
}
function pick(media: Media) {
onPick(media);
open = false;
}
</script>
<Modal bind:open title="Pick an uploaded image" wide>
<input
class="input mb-4 w-full"
type="search"
placeholder="Search by alt text or file name"
aria-label="Search images"
value={query}
oninput={(e) => search(e.currentTarget.value)}
onkeydown={(e) => e.key === 'Enter' && e.preventDefault()}
/>
{#if error}
<div class="alert alert-error mb-4 text-sm" role="alert">{error}</div>
{/if}
{#if items.length}
<div class="grid max-h-[60vh] grid-cols-3 gap-3 overflow-y-auto p-1 sm:grid-cols-4">
{#each items as media (media.id)}
<button
type="button"
class="group overflow-hidden rounded-box border border-base-300 bg-base-200 text-left transition hover:border-primary focus-visible:outline-2 focus-visible:outline-primary"
title={media.alt || 'No alt text'}
onclick={() => pick(media)}
>
<img class="aspect-square w-full object-cover" src={thumbUrl(media.url)} alt="" loading="lazy" />
<span class="block truncate px-2 py-1 text-xs text-base-content/70 group-hover:text-base-content">{media.alt || '—'}</span>
</button>
{/each}
</div>
{#if page < totalPages}
<div class="mt-3 text-center">
<button class="btn btn-sm" type="button" disabled={loading} onclick={() => load(page + 1)}>{loading ? 'Loading…' : 'Show more'}</button>
</div>
{/if}
{:else if loading}
<div class="py-10 text-center"><span class="loading loading-spinner loading-lg text-primary"></span></div>
{:else if !error}
<p class="py-10 text-center text-base-content/60">{query ? 'No images match that search.' : 'No images have been uploaded yet.'}</p>
{/if}
</Modal>

View file

@ -1,127 +1,78 @@
<script lang="ts"> <script lang="ts">
import { onMount, untrack } from 'svelte'; import { browser } from '$app/environment';
import { Editor } from '@tiptap/core'; import { onMount } from 'svelte';
import StarterKit from '@tiptap/starter-kit';
// The visual editor for text in blocks and emails. It can only produce what let { value = '', onChange = (html: string) => {} } = $props<{ value?: string; onChange?: (html: string) => void }>();
// the toolbar offers (see EDITOR_TAGS in $shared/richText): no inline styles let editorEl: HTMLDivElement | undefined = $state();
// or layout HTML, so pages stay consistent. Layouts are blocks (Cards, FAQ); let mounted = $state(false);
// anything else goes in an HTML block.
let {
value = '',
onChange = (html: string) => {},
compact = false
} = $props<{ value?: string; onChange?: (html: string) => void; compact?: boolean }>();
let element: HTMLDivElement | undefined = $state();
let editor: Editor | undefined = $state();
// Bumped on every editor transaction so the toolbar's active states re-render.
let tick = $state(0);
onMount(() => { onMount(() => {
editor = new Editor({ mounted = true;
element, if (editorEl) {
extensions: [ editorEl.innerHTML = value || '';
StarterKit.configure({ }
heading: { levels: [2, 3] },
code: false,
codeBlock: false,
underline: false,
// It appends an empty paragraph after a closing heading or list, which changed content just by
// opening a block (and looped with the value sync below).
trailingNode: false,
// No target/rel: most links are to the site's own pages, which shouldn't open a new tab.
link: { openOnClick: false, autolink: true, defaultProtocol: 'https', HTMLAttributes: { target: null, rel: null } }
})
],
content: value || '',
editorProps: { attributes: { class: 'rich-text min-h-32 p-4 outline-none', role: 'textbox', 'aria-multiline': 'true' } },
onTransaction: () => tick++,
onUpdate: ({ editor }) => onChange(editor.isEmpty ? '' : editor.getHTML())
});
return () => editor?.destroy();
}); });
// Another block selected: show its content (not echoed back, so nothing is marked unsaved). // Sync content from props when a different block is selected,
// Untracked: setContent runs onTransaction (tick++), which must not become a dependency here. // without overwriting content while the user is actively editing.
$effect(() => { $effect(() => {
const html = value || ''; if (mounted && editorEl && value !== undefined) {
const current = editor; if (editorEl.innerHTML !== value) {
if (!current) return; editorEl.innerHTML = value || '';
untrack(() => { }
if (html !== (current.isEmpty ? '' : current.getHTML())) current.commands.setContent(html, { emitUpdate: false }); }
});
}); });
function active(name: string, attrs?: Record<string, unknown>) { function exec(cmd: string, val?: string) {
tick; if (!browser) return;
return editor?.isActive(name, attrs) ?? false; editorEl?.focus();
document.execCommand(cmd, false, val);
emit();
}
function emit() {
if (editorEl) onChange(editorEl.innerHTML);
} }
function setLink() { function setLink() {
if (!editor) return; const url = prompt('Link URL', 'https://');
const current = editor.getAttributes('link').href || ''; if (url) exec('createLink', url);
const href = prompt('Link address (/page, #anchor or https://…). Empty removes the link.', current);
if (href === null) return;
const chain = editor.chain().focus().extendMarkRange('link');
if (href.trim()) chain.setLink({ href: href.trim() }).run();
else chain.unsetLink().run();
} }
type Tool = { label: string; title: string; run: () => void; on?: () => boolean; class?: string }; function clearFormatting() {
let tools = $derived.by((): Tool[][] => { if (!browser) return;
const c = () => editor!.chain().focus(); editorEl?.focus();
// Compact (cards, FAQ answers): no headings, quotes or lines inside small text. document.execCommand('formatBlock', false, '<p>');
return [ document.execCommand('removeFormat');
compact ? [] : [ emit();
{ label: 'Text', title: 'Paragraph', run: () => c().setParagraph().run(), on: () => active('paragraph') }, }
{ label: 'H2', title: 'Heading', run: () => c().toggleHeading({ level: 2 }).run(), on: () => active('heading', { level: 2 }) },
{ label: 'H3', title: 'Subheading', run: () => c().toggleHeading({ level: 3 }).run(), on: () => active('heading', { level: 3 }) } function handleInput() {
], emit();
[ }
{ label: 'B', title: 'Bold', run: () => c().toggleBold().run(), on: () => active('bold'), class: 'font-bold' },
{ label: 'I', title: 'Italic', run: () => c().toggleItalic().run(), on: () => active('italic'), class: 'italic' },
{ label: 'S', title: 'Strikethrough', run: () => c().toggleStrike().run(), on: () => active('strike'), class: 'line-through' },
{ label: 'Link', title: 'Link', run: setLink, on: () => active('link') }
],
[
{ label: '• List', title: 'Bulleted list', run: () => c().toggleBulletList().run(), on: () => active('bulletList') },
{ label: '1. List', title: 'Numbered list', run: () => c().toggleOrderedList().run(), on: () => active('orderedList') },
...(compact
? []
: [
{ label: 'Quote', title: 'Pull quote', run: () => c().toggleBlockquote().run(), on: () => active('blockquote') },
{ label: '— Line', title: 'Divider line', run: () => c().setHorizontalRule().run() }
])
],
[
{ label: 'Clear', title: 'Remove formatting', run: () => c().unsetAllMarks().clearNodes().run() },
{ label: '↶', title: 'Undo', run: () => c().undo().run() },
{ label: '↷', title: 'Redo', run: () => c().redo().run() }
]
].filter((group) => group.length);
});
</script> </script>
<div class="rounded-box border border-base-300 bg-base-100"> {#if mounted}
<div class="flex flex-wrap gap-1 border-b border-base-300 p-2" role="toolbar" aria-label="Text formatting"> <div class="rounded-box border border-base-300 bg-base-100">
{#each tools as group, g (g)} <div class="flex flex-wrap gap-2 border-b border-base-300 p-2">
{#if g > 0}<span class="mx-1 w-px self-stretch bg-base-300" aria-hidden="true"></span>{/if} <button class="btn btn-xs" onclick={() => exec('bold')} type="button"><b>B</b></button>
{#each group as tool (tool.title)} <button class="btn btn-xs" onclick={() => exec('italic')} type="button"><i>I</i></button>
<button <button class="btn btn-xs" onclick={() => exec('formatBlock', '<h2>')} type="button">H2</button>
type="button" <button class="btn btn-xs" onclick={() => exec('formatBlock', '<h3>')} type="button">H3</button>
class="btn btn-xs {tool.class || ''}" <button class="btn btn-xs" onclick={() => exec('insertUnorderedList')} type="button">List</button>
class:btn-primary={tool.on?.()} <button class="btn btn-xs" onclick={setLink} type="button">Link</button>
aria-pressed={tool.on ? tool.on() : undefined} <button class="btn btn-xs" onclick={clearFormatting} type="button">Clear</button>
title={tool.title} </div>
disabled={!editor} <div
onmousedown={(e) => e.preventDefault()} bind:this={editorEl}
onclick={tool.run}>{tool.label}</button contenteditable
> role="textbox"
{/each} aria-multiline="true"
{/each} class="min-h-40 p-4 outline-none"
oninput={handleInput}
onkeydown={(e) => { if (e.key === 'Tab') { e.preventDefault(); exec('insertHTML', '&emsp;'); } }}
></div>
</div> </div>
<div bind:this={element}> {:else}
{#if !editor}<div class="p-4 text-base-content/50">Loading editor…</div>{/if} <div class="rounded-box border border-base-300 bg-base-100 p-4 text-base-content/50">Loading editor…</div>
</div> {/if}
</div>

View file

@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
// One row of mutually exclusive options with an optional label column on // One row of mutually exclusive options with an optional label column on
// the left (above it in a narrow row) — the standard "setting row" in the block editors (see // the left — the standard "setting row" in the block editors (see
// ColorField for the colour variant; both share the label column width). // ColorField for the colour variant; both share the label column width).
let { let {
label, label,
@ -25,25 +25,22 @@
} = $props(); } = $props();
</script> </script>
<!-- In a narrow row (a phone) the label goes above the buttons, so they keep room for their text. --> <div class="flex items-center gap-3 {className}" role="group" aria-label={label}>
<div class="@container {className}"> {#if label}
<div class="flex flex-col gap-1 @sm:flex-row @sm:items-center @sm:gap-3" role="group" aria-label={label}> <span class="w-28 shrink-0 text-sm" class:font-bold={strong} class:font-medium={!strong}>{label}</span>
{#if label} {/if}
<span class="shrink-0 text-sm @sm:w-28" class:font-bold={strong} class:font-medium={!strong}>{label}</span> <div class="join grid flex-1" style="grid-template-columns: repeat({options.length}, minmax(0, 1fr))">
{/if} {#each options as option}
<div class="join grid flex-1" style="grid-template-columns: repeat({options.length}, minmax(0, 1fr))"> <button
{#each options as option} type="button"
<button class="btn btn-sm join-item px-1"
type="button" class:btn-active={value === option}
class="btn btn-sm join-item px-1" class:btn-primary={value === option}
class:btn-active={value === option} aria-pressed={value === option}
class:btn-primary={value === option} onclick={() => onChange(option)}
aria-pressed={value === option} >
onclick={() => onChange(option)} {formatLabel(option)}
> </button>
{formatLabel(option)} {/each}
</button>
{/each}
</div>
</div> </div>
</div> </div>

View file

@ -1,6 +1,5 @@
<script lang="ts"> <script lang="ts">
import type { ContentBlock, ShopBlockData, ShopSort } from '$lib/types'; import type { ContentBlock, ShopBlockData } from '$lib/types';
import { SHOP_SORTS } from '$shared/items';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
let { let {
@ -29,8 +28,7 @@
const typeFilterLabels: Record<string, string> = { const typeFilterLabels: Record<string, string> = {
all: 'All', all: 'All',
item: 'Products', item: 'Products',
item_with_time: 'Services', item_with_time: 'Services'
bundle: 'Bundles'
}; };
</script> </script>
@ -50,34 +48,17 @@
<SegmentedControl <SegmentedControl
label="Item type" label="Item type"
options={['all', 'item', 'item_with_time', 'bundle']} options={['all', 'item', 'item_with_time']}
value={block.data.itemTypeFilter || 'all'} value={block.data.itemTypeFilter || 'all'}
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })} onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)} formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
/> />
<label class="fieldset">
<span class="fieldset-legend">Order</span>
<select class="select w-full" value={block.data.sort || 'recommended'} onchange={(e) => updateData({ sort: e.currentTarget.value as ShopSort })}>
{#each SHOP_SORTS as choice (choice.value)}
<option value={choice.value}>{choice.label}</option>
{/each}
</select>
<span class="label whitespace-normal">
Recommended follows each item’s priority (Services & products). Most popular counts what sold in the last 90 days; items without recent sales come after, in Recommended order.
</span>
</label>
<label class="label cursor-pointer gap-3 whitespace-normal text-base-content">
<input class="toggle toggle-primary shrink-0" type="checkbox" checked={!!block.data.showSort} onchange={(e) => updateData({ showSort: e.currentTarget.checked })} />
<span>Let visitors sort <span class="text-base-content/60">— a “Sort by” menu above the items, starting at the order chosen above</span></span>
</label>
{#if items.length} {#if items.length}
<div class="rounded-box border border-base-300 p-4"> <div class="rounded-box border border-base-300 p-4">
<div class="mb-3"> <div class="mb-3">
<h3 class="font-semibold">Items</h3> <h3 class="font-semibold">Items</h3>
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type. Chosen items are shown in the order above, not the order you pick them.</p> <p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
{#each items as item} {#each items as item}

View file

@ -30,7 +30,6 @@ export const privacyTemplateHtml = `<h2>Privacy policy</h2>
<h3>How long we keep it</h3> <h3>How long we keep it</h3>
<ul> <ul>
<li>Details entered at checkout without completing payment: deleted after [30] days.</li> <li>Details entered at checkout without completing payment: deleted after [30] days.</li>
<li>Gift vouchers and bundles: the code is kept until it expires; your email and any recipient name and message you added are removed together with your order details.</li>
<li>Orders: your contact details are removed [after N months / when you ask]; the order record without them is kept for [N] years as required for our accounts.</li> <li>Orders: your contact details are removed [after N months / when you ask]; the order record without them is kept for [N] years as required for our accounts.</li>
<li>Server logs (including IP addresses): [a few] days.</li> <li>Server logs (including IP addresses): [a few] days.</li>
</ul> </ul>

View file

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

View file

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

View file

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

View file

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

View file

@ -28,6 +28,4 @@ export type CustomerData = {
lines: { name: string; quantity: number; price: number; start: string }[]; lines: { name: string; quantity: number; price: number; start: string }[];
}[]; }[];
unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[]; unpaidBaskets: { id: string; updated: string; status: string; customerDetails: CustomerDetails }[];
/** Bundle/voucher codes bought with this email, and who they're for. */
codes: { code: string; name: string; created: string; expiresAt: string; status: string; recipientName: string; message: string }[];
}; };

View file

@ -1,19 +0,0 @@
// The fonts Site design → Style offers (SITE_FONTS in $shared/theme), bundled
// and served by this app, not loaded from Google: a Google Fonts request sends
// every visitor's IP address to Google (GDPR). Each import only declares the
// font; a browser downloads the files of the fonts a page actually uses.
import '@fontsource-variable/playfair-display';
import '@fontsource-variable/cormorant-garamond';
import '@fontsource-variable/eb-garamond';
import '@fontsource-variable/libre-baskerville';
import '@fontsource-variable/lora';
import '@fontsource-variable/fraunces';
import '@fontsource-variable/dm-sans';
import '@fontsource-variable/inter';
import '@fontsource-variable/manrope';
import '@fontsource-variable/montserrat';
import '@fontsource-variable/nunito';
import '@fontsource-variable/outfit';
import '@fontsource-variable/raleway';
import '@fontsource-variable/work-sans';
import '@fontsource-variable/josefin-sans';

View file

@ -1,11 +1,10 @@
export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb'; export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb';
// App-specific: admin uploads go through the admin upload endpoint. // App-specific: admin uploads go through the admin upload endpoint.
// Without an alt text, the media record gets one made from the file name. export async function uploadMedia(file: File) {
export async function uploadMedia(file: File, alt = altFromFileName(file.name)) {
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
formData.append('alt', alt); formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const res = await fetch('/api/upload', { method: 'POST', body: formData }); const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) { if (!res.ok) {
@ -14,7 +13,3 @@ export async function uploadMedia(file: File, alt = altFromFileName(file.name))
} }
return res.json(); return res.json();
} }
export function altFromFileName(name: string) {
return name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ');
}

View file

@ -20,5 +20,5 @@ export function updateCustomer(pb: Pb, body: { email: string; name?: string; new
} }
export function eraseCustomer(pb: Pb, email: string) { export function eraseCustomer(pb: Pb, email: string) {
return pb.send<{ ordersAnonymised: number; basketsDeleted: number; passesAnonymised: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null }); return pb.send<{ ordersAnonymised: number; basketsDeleted: number }>('/api/privacy/customer/erase', { method: 'POST', body: { email }, requestKey: null });
} }

View file

@ -1,265 +0,0 @@
// Figures for the admin dashboard (/). Months are calendar months in
// SITE_TIMEZONE.
//
// Income counts an order in the month it was paid, so a voucher sold in March
// is March income and the session it later pays for adds hours but no income.
// Hours are the time covered by bookings, with overlaps counted once: six
// people in one group session are one hour of work, not six. Utilisation is
// that booked time against the time opened in Slots.
//
// Slot places and what codes have left come from the shop hooks (the only
// place that counts them); everything else is read from paid orders.
import { zonedDateKey, zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb';
import { listPasses } from '$lib/server/passes';
import { loadSlotDetails, seatsTaken } from '$lib/server/slots';
type Pb = ReturnType<typeof createPocketBase>;
/** How many months the month-by-month table and chart show, this one included. */
export const DASHBOARD_MONTHS = 12;
const UPCOMING_DAYS = 7;
/** How far ahead "Needs attention" looks for nearly full sessions and expiring codes. */
const ATTENTION_DAYS = 30;
/** A group session is "nearly full" with this share of its places taken (or one place left). */
const NEARLY_FULL_SHARE = 0.75;
const TOP_LIST = 5;
const DAY_MS = 24 * 60 * 60 * 1000;
export type DashboardMonth = { month: string; income: number; orders: number; minutes: number };
export type UpcomingBooking = { start: string; minutes: number; name: string; customer: string; quantity: number };
export type SalesRow = { name: string; minutes: number; count: number; income: number };
export type Regular = { name: string; orders: number; spent: number };
export type Attention =
| { kind: 'email'; orderId: string; customer: string; created: string }
| { kind: 'session'; start: string; name: string; taken: number; capacity: number }
| { kind: 'code'; code: string; name: string; expiresAt: string; left: number };
type Interval = { start: number; end: number };
/** `YYYY-MM` for `months` before (negative) or after `monthKey`. */
function shiftMonth(monthKey: string, months: number) {
const [year, month] = monthKey.split('-').map(Number);
const index = year * 12 + (month - 1) + months;
return `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, '0')}`;
}
/** Epoch ms of a PocketBase date ('2026-10-27 09:00:00.000Z'), NaN if blank. */
const toMs = (value: unknown) => new Date(String(value || '').replace(' ', 'T')).getTime();
/** Intervals merged where they overlap or touch, sorted by start. */
function mergeIntervals(intervals: Interval[]) {
const merged: Interval[] = [];
for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {
const last = merged.at(-1);
if (last && interval.start <= last.end) last.end = Math.max(last.end, interval.end);
else merged.push({ ...interval });
}
return merged;
}
/** Minutes of merged `intervals` that fall inside [from, to). */
function minutesBetween(intervals: Interval[], from: number, to: number) {
return intervals.reduce((total, { start, end }) => total + Math.max(Math.min(end, to) - Math.max(start, from), 0) / 60_000, 0);
}
/** Top rows by income, the rest folded into one "Other" row. */
function topWithOther(rows: SalesRow[], other: string) {
const sorted = [...rows].sort((a, b) => b.income - a.income || b.count - a.count);
if (sorted.length <= TOP_LIST) return sorted;
const rest = sorted.slice(TOP_LIST - 1);
return [
...sorted.slice(0, TOP_LIST - 1),
{ name: other, minutes: 0, count: rest.reduce((n, row) => n + row.count, 0), income: rest.reduce((n, row) => n + row.income, 0) }
];
}
export async function loadDashboard(pb: Pb, timeZone: string, now = new Date()) {
const nowMs = now.getTime();
const thisMonth = zonedDateKey(now.toISOString(), timeZone).slice(0, 7);
const months = Array.from({ length: DASHBOARD_MONTHS }, (_, i) => shiftMonth(thisMonth, i - (DASHBOARD_MONTHS - 1)));
// The table reaches back at least to January, so it covers "this year" too.
const from = zonedInputToIso(`${months[0]}-01T00:00`, timeZone);
const monthStart = zonedInputToIso(`${thisMonth}-01T00:00`, timeZone);
const monthEnd = zonedInputToIso(`${shiftMonth(thisMonth, 1)}-01T00:00`, timeZone);
const attentionUntil = nowMs + ATTENTION_DAYS * DAY_MS;
const [orders, lines, slotDetails, passes] = await Promise.all([
// Every paid order, so "new customer" means first order ever.
pb
.collection('orders')
.getFullList({ filter: "status = 'paid'", fields: 'id,email,total,created,customerDetails,emailError', requestKey: null })
.catch(() => []),
pb
.collection('order_lines')
.getFullList({
filter: pb.filter("order.status = 'paid' && (order.created >= {:from} || start >= {:from})", { from }),
sort: 'start',
expand: 'order',
fields: 'item,name,price,quantity,lineType,start,minutes,expand.order.created,expand.order.customerDetails',
requestKey: null
})
.catch(() => []),
loadSlotDetails(pb, { from: monthStart, to: new Date(Math.max(toMs(monthEnd), attentionUntil)).toISOString() }).catch(() => null),
listPasses(pb, '').catch(() => [])
]);
const monthOf = (value: unknown) => zonedDateKey(String(value || ''), timeZone).slice(0, 7);
const byMonth = new Map<string, DashboardMonth>(months.map((month) => [month, { month, income: 0, orders: 0, minutes: 0 }]));
// ── Income and customers ───────────────────────────────────────────
// Orders from before `created` existed have no date: they count as
// "earlier" (so their customers are returning), never as this month.
const firstOrder = new Map<string, number>();
const regulars = new Map<string, Regular>();
for (const order of [...orders].sort((a, b) => (toMs(a.created) || 0) - (toMs(b.created) || 0))) {
const created = toMs(order.created);
const month = Number.isNaN(created) ? '' : monthOf(order.created);
const row = byMonth.get(month);
if (row) {
row.income += Number(order.total) || 0;
row.orders += 1;
}
// Anonymised orders have no email: they're nobody's history any more.
const email = String(order.email || '').trim().toLowerCase();
if (!email) continue;
if (!firstOrder.has(email)) firstOrder.set(email, Number.isNaN(created) ? 0 : created);
if (row) {
const regular = regulars.get(email) ?? { name: '', orders: 0, spent: 0 };
regular.name = String(order.customerDetails?.name || '') || regular.name || email;
regular.orders += 1;
regular.spent += Number(order.total) || 0;
regulars.set(email, regular);
}
}
let newCustomers = 0;
let returningCustomers = 0;
const seenThisMonth = new Set<string>();
for (const order of orders) {
const email = String(order.email || '').trim().toLowerCase();
if (!email || seenThisMonth.has(email) || Number.isNaN(toMs(order.created)) || monthOf(order.created) !== thisMonth) continue;
seenThisMonth.add(email);
if ((firstOrder.get(email) ?? 0) >= toMs(monthStart)) newCustomers++;
else returningCustomers++;
}
// ── What sells (orders paid in the 12 months) ─────────────────────────
const services = new Map<string, SalesRow>();
const lengths = new Map<string, SalesRow>();
for (const line of lines) {
const created = line.expand?.order?.created;
if (!byMonth.has(monthOf(created))) continue;
const quantity = Number(line.quantity) || 1;
const income = (Number(line.price) || 0) * quantity;
const name = String(line.name || '');
const service = services.get(line.item) ?? { name, minutes: 0, count: 0, income: 0 };
service.count += quantity;
service.income += income;
services.set(line.item, service);
if (line.lineType === 'slot' && line.minutes) {
const key = `${line.item}:${line.minutes}`;
const length = lengths.get(key) ?? { name, minutes: Number(line.minutes), count: 0, income: 0 };
length.count += quantity;
length.income += income;
lengths.set(key, length);
}
}
// Products inside a bundle are lines at price 0: the bundle line has the money.
const sales = topWithOther([...services.values()].filter((row) => row.income > 0), 'Everything else');
const topLengths = [...lengths.values()].sort((a, b) => b.count - a.count || b.income - a.income).slice(0, TOP_LIST);
// ── Hours ────────────────────────────────────────────────────────────
const bookings = mergeIntervals(
lines
.filter((line) => line.lineType === 'slot' && Number(line.minutes) > 0 && !Number.isNaN(toMs(line.start)))
.map((line) => ({ start: toMs(line.start), end: toMs(line.start) + Number(line.minutes) * 60_000 }))
);
for (const { start, end } of bookings) {
const row = byMonth.get(monthOf(new Date(start).toISOString()));
if (row) row.minutes += (end - start) / 60_000;
}
const minutesDoneThisMonth = minutesBetween(bookings, toMs(monthStart), Math.min(nowMs, toMs(monthEnd)));
const minutesAheadThisMonth = minutesBetween(bookings, nowMs, toMs(monthEnd));
const upcomingUntil = nowMs + UPCOMING_DAYS * DAY_MS;
const upcoming: UpcomingBooking[] = lines
.filter((line) => {
if (line.lineType !== 'slot') return false;
const start = toMs(line.start);
return start + (Number(line.minutes) || 0) * 60_000 > nowMs && start < upcomingUntil;
})
.map((line) => ({
start: String(line.start),
minutes: Number(line.minutes) || 0,
name: String(line.name || ''),
customer: String(line.expand?.order?.customerDetails?.name || ''),
quantity: Number(line.quantity) || 1
}));
// Opened time this month (overlapping slots counted once) vs. booked time in it.
const slots = slotDetails?.slots ?? [];
const opened = mergeIntervals(slots.map((slot) => ({ start: toMs(slot.start), end: toMs(slot.end) })).filter((i) => !Number.isNaN(i.start)));
const openMinutes = minutesBetween(opened, toMs(monthStart), toMs(monthEnd));
const bookedInMonth = minutesBetween(bookings, toMs(monthStart), toMs(monthEnd));
// ── Vouchers and codes ───────────────────────────────────────────────
// What's owed: the unbooked share of each usable code's value.
let codesOutstanding = 0;
let valueOutstanding = 0;
const attention: Attention[] = [];
for (const pass of passes) {
const expires = pass.expiresAt ? toMs(pass.expiresAt) : Infinity;
if (pass.status !== 'active' || expires <= nowMs) continue;
const open = pass.parts.filter((part) => part.redeemable && part.left > 0);
if (!open.length) continue;
codesOutstanding++;
valueOutstanding += open.reduce((total, part) => total + (part.count ? (part.value * part.left) / part.count : 0), 0);
if (expires <= attentionUntil) {
attention.push({ kind: 'code', code: pass.code, name: pass.name, expiresAt: pass.expiresAt, left: open.reduce((n, part) => n + part.left, 0) });
}
}
// ── Needs attention ──────────────────────────────────────────────────
for (const order of orders) {
if (order.emailError) {
attention.push({ kind: 'email', orderId: order.id, customer: String(order.customerDetails?.name || order.email || 'A customer'), created: String(order.created || '') });
}
}
for (const slot of slots) {
if (slot.kind !== 'session' || !slot.capacity || toMs(slot.start) <= nowMs || toMs(slot.start) > attentionUntil) continue;
const taken = seatsTaken(slot);
if (taken < slot.capacity && (taken >= slot.capacity * NEARLY_FULL_SHARE || slot.capacity - taken === 1)) {
attention.push({ kind: 'session', start: slot.start, name: slot.itemNames.join(', '), taken, capacity: slot.capacity });
}
}
const year = thisMonth.slice(0, 4);
const monthRows = months.map((month) => byMonth.get(month)!);
return {
thisMonth: byMonth.get(thisMonth)!,
lastMonth: byMonth.get(shiftMonth(thisMonth, -1))!,
incomeThisYear: monthRows.filter((row) => row.month.startsWith(year)).reduce((total, row) => total + row.income, 0),
minutesDoneThisMonth: Math.round(minutesDoneThisMonth),
minutesAheadThisMonth: Math.round(minutesAheadThisMonth),
// null when nothing is opened (or slots couldn't be read): no percentage to show.
utilisation: openMinutes > 0 && slotDetails ? { booked: Math.round(bookedInMonth), open: Math.round(openMinutes) } : null,
upcomingDays: UPCOMING_DAYS,
upcoming,
upcomingMinutes: Math.round(minutesBetween(bookings, nowMs, upcomingUntil)),
newCustomers,
returningCustomers,
regulars: [...regulars.values()]
.filter((regular) => regular.orders > 1)
.sort((a, b) => b.orders - a.orders || b.spent - a.spent)
.slice(0, TOP_LIST),
sales,
lengths: topLengths,
codesOutstanding,
valueOutstanding,
attentionDays: ATTENTION_DAYS,
attention,
// Oldest first: the chart reads left to right.
months: monthRows
};
}

View file

@ -1,38 +0,0 @@
// Bundle/voucher codes for the admin. Codes are commerce data: they are
// only written by the shop hooks in PocketBase (/api/shop/passes*, signed-in
// admins only), which also count what each code has left.
import { ClientResponseError } from 'pocketbase';
import type { createPocketBase } from '$lib/pb';
import type { PassSummary } from '$lib/types';
type Pb = ReturnType<typeof createPocketBase>;
/** A code as the admin list shows it: the summary plus who bought it and when. */
export type AdminPass = PassSummary & { email: string; order: string; created: string; anonymisedAt: string };
export async function listPasses(pb: Pb, q: string) {
const { passes } = await pb.send<{ passes: AdminPass[] }>('/api/shop/passes', { query: { q }, requestKey: null });
return passes;
}
export function updatePass(pb: Pb, body: { id: string; status?: 'active' | 'void'; expiresAt?: string }) {
return pb.send<{ pass: PassSummary }>('/api/shop/passes/update', { method: 'POST', body, requestKey: null });
}
export function issuePass(pb: Pb, body: { itemId: string; email: string; recipientName: string; message: string; months: string }) {
return pb.send<{ pass: PassSummary }>('/api/shop/passes/issue', { method: 'POST', body, requestKey: null });
}
/** Item id → how many usable codes still have sessions of it to book. */
export async function codesWaiting(pb: Pb) {
const { waiting } = await pb.send<{ waiting: Record<string, number> }>('/api/shop/passes/waiting', { requestKey: null });
return waiting;
}
/** The hook's own message (e.g. "Choose a bundle"), or `fallback`. */
export function hookError(e: unknown, fallback: string) {
if (e instanceof ClientResponseError && e.status >= 400 && e.status < 500 && e.response?.message) return String(e.response.message);
console.error(`[passes] ${fallback}`, e);
return fallback;
}

View file

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

View file

@ -1,5 +1,5 @@
import { env } from '$env/dynamic/private'; import { env } from '$env/dynamic/private';
import { defaultColors, defaultStyle } from '$lib/types'; import { defaultColors } from '$lib/types';
import { shopCurrency } from '$shared/calendar'; import { shopCurrency } from '$shared/calendar';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
@ -13,18 +13,10 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
} }
export const load: LayoutServerLoad = async ({ locals }) => { export const load: LayoutServerLoad = async ({ locals }) => {
const [colors, header, style] = await Promise.all([ const colors = await getGlobal(locals.pb, 'colors', defaultColors);
getGlobal(locals.pb, 'colors', defaultColors),
getGlobal(locals.pb, 'header', {}) as Promise<{ logo?: { url?: string } }>,
// Only /preview uses it: the admin's own pages keep their look.
getGlobal(locals.pb, 'style', defaultStyle)
]);
return { return {
user: locals.user, user: locals.user,
colors, colors,
style,
// The site's logo is the admin's tab icon too (same as the public site).
logoUrl: header?.logo?.url || '',
// Admin dates/times are entered and shown in the site's timezone, and // Admin dates/times are entered and shown in the site's timezone, and
// prices in the shop currency — same settings the booking emails use. // prices in the shop currency — same settings the booking emails use.
timezone: env.SITE_TIMEZONE || 'Europe/Oslo', timezone: env.SITE_TIMEZONE || 'Europe/Oslo',

View file

@ -1,15 +1,20 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
import '$lib/fonts'; // Fonts are bundled and served by this app, not loaded from Google: a
// Google Fonts request sends every visitor's IP address to Google (GDPR).
import '@fontsource/dm-sans/400.css';
import '@fontsource/dm-sans/500.css';
import '@fontsource/dm-sans/600.css';
import '@fontsource/dm-sans/700.css';
import '@fontsource/playfair-display/600.css';
import '@fontsource/playfair-display/700.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import { afterNavigate } from '$app/navigation'; import { afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { brandThemeVars, rootStyleTag } from '$shared/theme'; import { brandThemeVars, rootStyleTag } from '$shared/theme';
import { thumbUrl } from '$shared/pb';
let { children, data } = $props(); let { children, data } = $props();
let icon = $derived(data.logoUrl ? thumbUrl(data.logoUrl) : favicon);
// Routes rendered without the admin shell: the login screen, and the // Routes rendered without the admin shell: the login screen, and the
// preview iframe (which must look like the public site, not the admin). // preview iframe (which must look like the public site, not the admin).
@ -22,10 +27,6 @@
// Sidebar navigation, grouped by what the studio is doing. Labels are // Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names. // user-facing names; hrefs keep the original route names.
const navGroups = [ const navGroups = [
{
title: 'Studio',
links: [{ href: '/', label: 'Dashboard' }]
},
{ {
title: 'Website', title: 'Website',
links: [ links: [
@ -40,7 +41,6 @@
{ href: '/customers', label: 'Customers' }, { href: '/customers', label: 'Customers' },
{ href: '/slots', label: 'Slots' }, { href: '/slots', label: 'Slots' },
{ href: '/items', label: 'Services & products' }, { href: '/items', label: 'Services & products' },
{ href: '/passes', label: 'Vouchers & codes' },
{ href: '/calendar', label: 'Events' } { href: '/calendar', label: 'Events' }
] ]
}, },
@ -66,7 +66,7 @@
</script> </script>
<svelte:head> <svelte:head>
<link rel="icon" href={icon} /> <link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Admin buttons/highlights use the site's Primary and Accent colours (sanitised; readable text picked automatically). --> <!-- Admin buttons/highlights use the site's Primary and Accent colours (sanitised; readable text picked automatically). -->
{@html rootStyleTag(brandThemeVars(data.colors))} {@html rootStyleTag(brandThemeVars(data.colors))}
@ -84,7 +84,7 @@
<label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu"> <label for="admin-nav" class="btn btn-square btn-ghost" aria-label="Open menu">
<svg xmlns="http://www.w3.org/2000/svg" class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16" /></svg> <svg xmlns="http://www.w3.org/2000/svg" class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16" /></svg>
</label> </label>
<a class="ml-1 text-lg font-bold tracking-tight" href="/">Massage CMS</a> <a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
</header> </header>
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8"> <main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
{@render children()} {@render children()}
@ -94,7 +94,7 @@
<div class="drawer-side z-40"> <div class="drawer-side z-40">
<label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label> <label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label>
<aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100"> <aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100">
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/">Massage CMS</a> <a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
<nav class="flex-1" aria-label="Main"> <nav class="flex-1" aria-label="Main">
<ul class="menu w-full gap-0.5 px-3"> <ul class="menu w-full gap-0.5 px-3">
{#each navGroups as group (group.title)} {#each navGroups as group (group.title)}

View file

@ -1,7 +0,0 @@
import { env } from '$env/dynamic/private';
import { loadDashboard } from '$lib/server/dashboard';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => ({
dashboard: await loadDashboard(locals.pb, env.SITE_TIMEZONE || 'Europe/Oslo')
});

View file

@ -1,215 +0,0 @@
<script lang="ts">
import IncomeChart from '$lib/admin/IncomeChart.svelte';
import { DISPLAY_LOCALE, formatDateTime, formatInstant, formatPrice, zonedDateKey } from '$lib/calendar';
import { formatDuration } from '$shared/items';
let { data } = $props();
let dashboard = $derived(data.dashboard);
const hoursFormat = new Intl.NumberFormat(DISPLAY_LOCALE, { maximumFractionDigits: 1 });
const hours = (minutes: number) => `${hoursFormat.format(minutes / 60)} h`;
const money = (amount: number) => formatPrice(amount, data.currency);
// Whole units for the chart axis; falls back to the full price if the currency code is unknown.
const roundMoney = (amount: number) => {
try {
return new Intl.NumberFormat(DISPLAY_LOCALE, { style: 'currency', currency: data.currency, maximumFractionDigits: 0 }).format(amount);
} catch {
return money(amount);
}
};
// Mid-month noon UTC is inside the same month in every timezone.
const monthLabel = (month: string, options: Intl.DateTimeFormatOptions = { month: 'long', year: 'numeric' }) =>
formatInstant(`${month}-15T12:00:00Z`, data.timezone, options);
const dayLabel = (value: string) => formatInstant(value, data.timezone, { weekday: 'long', day: 'numeric', month: 'short' });
const timeLabel = (value: string) => formatInstant(value, data.timezone, { hour: '2-digit', minute: '2-digit' });
let thisMonthName = $derived(monthLabel(dashboard.thisMonth.month, { month: 'long' }));
let incomeChange = $derived(dashboard.thisMonth.income - dashboard.lastMonth.income);
let chartMonths = $derived(dashboard.months.map((m) => ({ ...m, label: monthLabel(m.month, { month: 'short' }), name: monthLabel(m.month) })));
let utilisationPercent = $derived(dashboard.utilisation ? Math.round((dashboard.utilisation.booked / dashboard.utilisation.open) * 100) : null);
let todayKey = $derived(zonedDateKey(new Date().toISOString(), data.timezone));
// Coming up, one group per day (bookings arrive sorted by start).
let upcomingDays = $derived.by(() => {
const days: { key: string; label: string; bookings: typeof dashboard.upcoming }[] = [];
for (const booking of dashboard.upcoming) {
const key = zonedDateKey(booking.start, data.timezone);
if (days.at(-1)?.key !== key) days.push({ key, label: dayLabel(booking.start), bookings: [] });
days.at(-1)!.bookings.push(booking);
}
return days;
});
</script>
<svelte:head><title>Dashboard | CMS</title></svelte:head>
{#snippet tile(label: string, value: string, note: string)}
<div class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<p class="text-sm text-base-content/60">{label}</p>
<p class="mt-1 text-2xl font-bold tabular-nums sm:text-3xl">{value}</p>
<p class="mt-1 text-sm text-base-content/60">{note}</p>
</div>
{/snippet}
{#snippet salesTable(rows: typeof dashboard.sales, nameOf: (row: (typeof dashboard.sales)[number]) => string, empty: string)}
{#if rows.length}
<table class="table table-sm">
<thead><tr><th></th><th class="text-right">Sold</th><th class="text-right">Income</th></tr></thead>
<tbody>
{#each rows as row, i (i)}
<tr><td>{nameOf(row)}</td><td class="text-right tabular-nums">{row.count}</td><td class="text-right tabular-nums">{money(row.income)}</td></tr>
{/each}
</tbody>
</table>
{:else}
<p class="text-base-content/60">{empty}</p>
{/if}
{/snippet}
<div class="mb-6">
<h1 class="text-3xl font-bold">Dashboard</h1>
<p class="text-base-content/60">How the studio is doing. Income is paid orders, in the month they were paid; hours are booked appointment time, with group sessions counted once.</p>
</div>
<!-- What's next and what needs doing first; the figures follow. -->
<div class="grid gap-6 xl:grid-cols-2">
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-3 flex flex-wrap items-baseline justify-between gap-x-4">
<h2 class="text-2xl font-bold">Coming up</h2>
<p class="text-sm text-base-content/60">
Next {dashboard.upcomingDays} days: {dashboard.upcoming.length} {dashboard.upcoming.length === 1 ? 'booking' : 'bookings'}, {hours(dashboard.upcomingMinutes)}
</p>
</div>
{#if upcomingDays.length}
<div class="space-y-4">
{#each upcomingDays as day (day.key)}
<div>
<h3 class="mb-1 text-sm font-semibold">{day.key === todayKey ? 'Today' : day.label}</h3>
<ul class="divide-y divide-base-300 rounded-box bg-base-200/60 px-3">
{#each day.bookings as booking, i (i)}
<li class="flex gap-3 py-2">
<span class="w-14 shrink-0 font-semibold tabular-nums">{timeLabel(booking.start)}</span>
<span class="min-w-0 flex-1">
<span class="block">{booking.name}{#if booking.quantity > 1}<span class="text-base-content/60">&nbsp;× {booking.quantity}</span>{/if}</span>
<span class="block text-sm text-base-content/60">{formatDuration(booking.minutes)}{#if booking.customer}&nbsp;· {booking.customer}{/if}</span>
</span>
</li>
{/each}
</ul>
</div>
{/each}
</div>
{:else}
<p class="text-base-content/60">Nothing booked in the next {dashboard.upcomingDays} days.</p>
{/if}
<a class="btn btn-sm mt-4" href="/orders">All orders</a>
</section>
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-3 flex flex-wrap items-baseline justify-between gap-x-4">
<h2 class="text-2xl font-bold">Needs attention</h2>
<p class="text-sm text-base-content/60">Sessions and codes: next {dashboard.attentionDays} days</p>
</div>
{#if dashboard.attention.length}
<ul class="divide-y divide-base-300">
{#each dashboard.attention as item, i (i)}
<li class="flex flex-wrap items-center gap-x-3 gap-y-1 py-2">
{#if item.kind === 'email'}
<span class="badge badge-warning badge-sm">⚠ Email failed</span>
<span class="order-last basis-full">Booking email for {item.customer}{#if item.created}<span class="text-base-content/60">&nbsp;· ordered {formatDateTime(item.created, data.timezone)}</span>{/if}</span>
<a class="btn btn-ghost btn-xs ml-auto" href="/orders">Resend in Orders</a>
{:else if item.kind === 'session'}
<span class="badge badge-info badge-sm">◔ Nearly full</span>
<span class="order-last basis-full">{item.name || 'Group session'} · {formatDateTime(item.start, data.timezone)}<span class="text-base-content/60">&nbsp;· {item.taken} of {item.capacity} places taken</span></span>
<a class="btn btn-ghost btn-xs ml-auto" href="/slots">Slots</a>
{:else}
<span class="badge badge-sm">⏱ Expires soon</span>
<span class="order-last basis-full">{item.code} ({item.name}) · {item.left} {item.left === 1 ? 'session' : 'sessions'} left<span class="text-base-content/60">&nbsp;· expires {formatDateTime(item.expiresAt, data.timezone)}</span></span>
<a class="btn btn-ghost btn-xs ml-auto" href="/passes?q={encodeURIComponent(item.code)}">Vouchers & codes</a>
{/if}
</li>
{/each}
</ul>
{:else}
<p class="text-base-content/60">✓ All clear: no failed emails, nearly full sessions or codes about to expire.</p>
{/if}
</section>
</div>
<div class="mt-6 grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
{@render tile(`Income in ${thisMonthName}`, money(dashboard.thisMonth.income), `${incomeChange >= 0 ? '+' : '−'}${money(Math.abs(incomeChange))} on ${monthLabel(dashboard.lastMonth.month, { month: 'long' })}`)}
{@render tile(`Hours worked in ${thisMonthName}`, hours(dashboard.minutesDoneThisMonth), `${hours(dashboard.minutesAheadThisMonth)} still booked`)}
{@render tile(
'Opened time booked',
utilisationPercent === null ? '—' : `${utilisationPercent} %`,
dashboard.utilisation ? `${hours(dashboard.utilisation.booked)} of ${hours(dashboard.utilisation.open)} in Slots this month` : 'No slots opened this month'
)}
{@render tile('Codes owed', money(dashboard.valueOutstanding), `${dashboard.codesOutstanding} ${dashboard.codesOutstanding === 1 ? 'code' : 'codes'} with sessions to book`)}
</div>
<section class="mt-6 rounded-box bg-base-100 p-4 shadow sm:p-5">
<div class="mb-4 flex flex-wrap items-end justify-between gap-x-6 gap-y-2">
<div>
<h2 class="text-2xl font-bold">Income</h2>
<p class="text-sm text-base-content/60">Per month, last {dashboard.months.length} months</p>
</div>
<div class="sm:text-right">
<p class="text-sm text-base-content/60">Income in {dashboard.thisMonth.month.slice(0, 4)}</p>
<p class="text-2xl font-bold tabular-nums sm:text-3xl">{money(dashboard.incomeThisYear)}</p>
<p class="text-sm text-base-content/60">
{dashboard.thisMonth.orders} {dashboard.thisMonth.orders === 1 ? 'order' : 'orders'} this month{#if dashboard.thisMonth.orders}, {money(dashboard.thisMonth.income / dashboard.thisMonth.orders)} on average{/if}
</p>
</div>
</div>
<IncomeChart months={chartMonths} format={money} tickFormat={roundMoney} current={dashboard.thisMonth.month} />
<details class="mt-2">
<summary class="cursor-pointer text-sm font-medium">Show as table</summary>
<div class="mt-2 overflow-x-auto">
<table class="table table-sm">
<thead>
<tr><th>Month</th><th class="text-right">Orders</th><th class="text-right">Income</th><th class="text-right">Hours</th></tr>
</thead>
<tbody>
{#each [...dashboard.months].reverse() as row (row.month)}
<tr class={row.month === dashboard.thisMonth.month ? 'bg-primary/10' : ''}>
<td>{monthLabel(row.month, { month: 'short', year: 'numeric' })}</td>
<td class="text-right tabular-nums">{row.orders}</td>
<td class="text-right tabular-nums">{money(row.income)}</td>
<td class="text-right tabular-nums">{hours(row.minutes)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
</details>
</section>
<div class="mt-6 grid gap-6 lg:grid-cols-2 xl:grid-cols-3">
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<h2 class="mb-1 text-2xl font-bold">Customers</h2>
<p class="mb-3 text-sm text-base-content/60">
{dashboard.newCustomers + dashboard.returningCustomers} in {thisMonthName}: {dashboard.newCustomers} new, {dashboard.returningCustomers} returning
</p>
<h3 class="font-semibold">Regulars</h3>
{#if dashboard.regulars.length}
<table class="table table-sm">
<thead><tr><th></th><th class="text-right">Orders</th><th class="text-right">Spent</th></tr></thead>
<tbody>
{#each dashboard.regulars as regular, i (i)}
<tr><td>{regular.name}</td><td class="text-right tabular-nums">{regular.orders}</td><td class="text-right tabular-nums">{money(regular.spent)}</td></tr>
{/each}
</tbody>
</table>
{:else}
<p class="text-base-content/60">Nobody has ordered more than once yet.</p>
{/if}
</section>
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<h2 class="mb-3 text-2xl font-bold">What sells</h2>
{@render salesTable(dashboard.sales, (row) => row.name, 'Nothing sold yet.')}
</section>
<section class="rounded-box bg-base-100 p-4 shadow sm:p-5">
<h2 class="mb-3 text-2xl font-bold">Popular lengths</h2>
{@render salesTable(dashboard.lengths, (row) => `${row.name} · ${formatDuration(row.minutes)}`, 'No bookings yet.')}
</section>
</div>
<p class="mt-2 text-sm text-base-content/60">Regulars, what sells and popular lengths cover the last {dashboard.months.length} months.</p>

View file

@ -7,8 +7,6 @@ import {
validateSiteExport, validateSiteExport,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
import { upgradeLegacyBlocks } from '$shared/richText';
import type { ContentBlock } from '$lib/types';
export const POST: RequestHandler = async ({ request, locals }) => { export const POST: RequestHandler = async ({ request, locals }) => {
let body: SiteExport; let body: SiteExport;
@ -56,8 +54,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
// 2. Import pages // 2. Import pages
for (const page of body.pages) { for (const page of body.pages) {
try { try {
// Files exported before the visual editor may hold raw HTML in text blocks. const blocks = restorePlaceholders(page.blocks, keyToUrl);
const blocks = upgradeLegacyBlocks(restorePlaceholders(page.blocks, keyToUrl) as ContentBlock[]);
// Try to find existing page by slug // Try to find existing page by slug
let existing; let existing;

View file

@ -1,29 +0,0 @@
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
const PER_PAGE = 24;
// Uploaded images for the image picker's library, newest first; `q` searches alt text and file name.
export const GET: RequestHandler = async ({ url, locals }) => {
const page = Math.max(1, Number(url.searchParams.get('page')) || 1);
const q = (url.searchParams.get('q') || '').trim();
try {
const list = await locals.pb.collection('media').getList(page, PER_PAGE, {
sort: '-created',
filter: q ? locals.pb.filter('alt ~ {:q} || file ~ {:q}', { q }) : ''
});
return json({
page: list.page,
totalPages: list.totalPages,
items: list.items.map((record) => ({
id: record.id,
alt: record.alt || '',
url: `${env.PUBLIC_POCKETBASE_URL}/api/files/${record.collectionId}/${record.id}/${record.file}`
}))
});
} catch (e) {
console.error('Media list error:', e);
throw error(500, 'Couldn’t load the uploaded images');
}
};

View file

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

View file

@ -100,25 +100,24 @@
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-4 flex items-center justify-between gap-2"> <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<button class="btn btn-outline btn-sm" type="button" aria-label="Previous month" onclick={previousMonth}>←<span class="hidden sm:inline"> Previous</span></button> <button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
<h2 class="text-center text-xl font-bold sm:text-2xl">{month.label}</h2> <h2 class="text-2xl font-bold">{month.label}</h2>
<button class="btn btn-outline btn-sm" type="button" aria-label="Next month" onclick={nextMonth}><span class="hidden sm:inline">Next </span>→</button> <button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
</div> </div>
<div class="grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase text-base-content/50 sm:gap-2"> <div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
{#each weekdays as weekday}<div>{weekday}</div>{/each} {#each weekdays as weekday}<div>{weekday}</div>{/each}
</div> </div>
<!-- On a phone the days only show coloured bars (tap one to edit); the list below names them. --> <div class="mt-2 grid grid-cols-7 gap-2">
<div class="mt-2 grid grid-cols-7 gap-1 sm:gap-2">
{#each month.days as day} {#each month.days as day}
<div class="min-h-16 rounded-box border border-base-300 bg-base-200/60 p-1 sm:min-h-32 sm:p-2" class:opacity-40={!day.inMonth}> <div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
<button class="btn btn-circle btn-xs mb-1 {day.isToday ? 'btn-primary' : 'btn-ghost'}" type="button" title="Create an event on this day" aria-current={day.isToday ? 'date' : undefined} onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button> <button class="btn btn-circle btn-xs mb-1 {day.isToday ? 'btn-primary' : 'btn-ghost'}" type="button" title="Create an event on this day" aria-current={day.isToday ? 'date' : undefined} onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
<div class="space-y-1"> <div class="space-y-1">
{#each eventsForDay(day.date) as event} {#each eventsForDay(day.date) as event}
<button class="block h-3 w-full rounded-lg text-left text-xs font-semibold text-white shadow sm:h-auto sm:px-2 sm:py-1" style={`background:${event.color || '#8a9a7b'}`} type="button" title={event.name} aria-label="Edit {event.name}" onclick={() => editEvent(event)}> <button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
<span class="hidden truncate sm:block">{event.name}</span> <span class="block truncate">{event.name}</span>
<span class="hidden truncate text-[0.65rem] opacity-80 sm:block">{formatEventDateRange(event)}</span> <span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
</button> </button>
{/each} {/each}
</div> </div>
@ -131,16 +130,13 @@
<h2 class="mb-4 text-xl font-bold">All events</h2> <h2 class="mb-4 text-xl font-bold">All events</h2>
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th>Name</th><th class="hidden sm:table-cell">Date</th><th class="hidden md:table-cell">Categories</th><th>Status</th><th></th></tr></thead> <thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each events as event (event.id)} {#each events as event (event.id)}
<tr> <tr>
<td> <td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
<span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name} <td>{formatEventDateRange(event)}</td>
<span class="block text-xs text-base-content/60 sm:hidden">{formatEventDateRange(event)}</span> <td>{event.categories.join(', ')}</td>
</td>
<td class="hidden whitespace-nowrap sm:table-cell">{formatEventDateRange(event)}</td>
<td class="hidden md:table-cell">{event.categories.join(', ')}</td>
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td> <td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
</tr> </tr>

View file

@ -63,11 +63,10 @@ export const actions: Actions = {
const email = String((await request.formData()).get('email') || ''); const email = String((await request.formData()).get('email') || '');
const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email)); const result = await attempt('Could not erase the customer.', () => eraseCustomer(locals.pb, email));
if (!result.ok) return result.failure; if (!result.ok) return result.failure;
const { ordersAnonymised, basketsDeleted, passesAnonymised } = result.value; const { ordersAnonymised, basketsDeleted } = result.value;
const codes = passesAnonymised ? `, ${passesAnonymised} code${passesAnonymised === 1 ? '' : 's'} anonymised (still usable)` : '';
return { return {
ok: true, ok: true,
message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted${codes}.` message: `Erased: ${ordersAnonymised} order${ordersAnonymised === 1 ? '' : 's'} anonymised, ${basketsDeleted} unpaid checkout${basketsDeleted === 1 ? '' : 's'} deleted.`
}; };
}, },

View file

@ -3,7 +3,6 @@
import { page } from '$app/state'; import { page } from '$app/state';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar'; import { DISPLAY_LOCALE, formatDateTime } from '$lib/calendar';
import { formatCode } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let customer = $derived(data.customer); let customer = $derived(data.customer);
@ -155,16 +154,6 @@
{/each} {/each}
</ul> </ul>
{#if customer.codes?.length}
<h3 class="mt-6 font-bold">Codes bought</h3>
<p class="text-sm text-base-content/60">Bundles and vouchers. Erasing keeps the codes usable but removes the email, recipient and message.</p>
<ul class="mt-2 space-y-1 text-sm">
{#each customer.codes as code (code.code)}
<li><span class="font-mono">{formatCode(code.code)}</span> — {code.name}{code.recipientName ? ` · for ${code.recipientName}` : ''}{code.message ? ` · “${code.message}”` : ''}</li>
{/each}
</ul>
{/if}
{#if customer.unpaidBaskets.length} {#if customer.unpaidBaskets.length}
<h3 class="mt-6 font-bold">Unpaid checkouts</h3> <h3 class="mt-6 font-bold">Unpaid checkouts</h3>
<p class="text-sm text-base-content/60">Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.</p> <p class="text-sm text-base-content/60">Details typed at checkout without paying. Deleted automatically after {data.settings.abandonedBasketDays} days.</p>
@ -178,7 +167,7 @@
<div class="mt-6 rounded-box border border-error/40 p-4"> <div class="mt-6 rounded-box border border-error/40 p-4">
<h3 class="font-bold">Erase this customer</h3> <h3 class="font-bold">Erase this customer</h3>
<p class="mt-1 text-sm text-base-content/70"> <p class="mt-1 text-sm text-base-content/70">
For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts), removes their email and any recipient name and message from codes they bought (the codes keep working), and deletes unpaid checkouts. For a request to be forgotten. Removes their name, email, phone and notes from every order (the amounts, services and dates stay, for your accounts) and deletes unpaid checkouts.
Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services. Their payment also exists in Stripe and their booking emails in your email provider's logs — handle those in those services.
</p> </p>
{#if upcoming.length} {#if upcoming.length}

View file

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

View file

@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import BlockList from '$lib/admin/BlockList.svelte'; import BlockList from '$lib/admin/BlockList.svelte';
import SaveStatus from '$lib/admin/SaveStatus.svelte';
import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte'; import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte';
import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults'; import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte'; import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
@ -96,7 +95,9 @@
</div> </div>
</div> </div>
<SaveStatus result={form?.action === 'save' ? form : null} /> {#if form?.action === 'save' && form.message}
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if}
<div class="space-y-2 rounded-box bg-base-100 p-5 shadow"> <div class="space-y-2 rounded-box bg-base-100 p-5 shadow">
<label class="label cursor-pointer gap-3 text-base-content"> <label class="label cursor-pointer gap-3 text-base-content">

View file

@ -2,10 +2,10 @@ import { fail, redirect } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase'; import { ClientResponseError } from 'pocketbase';
import { PRIVACY_PAGE_SLUG, privacyTemplateHtml } from '$lib/admin/privacyTemplate'; import { PRIVACY_PAGE_SLUG, privacyTemplateHtml } from '$lib/admin/privacyTemplate';
import { attempt } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import { defaultColors, defaultFooter, defaultHeader, defaultStyle } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
const SECTIONS = ['header', 'footer', 'colors', 'style'] as const; const SECTIONS = ['header', 'footer', 'colors'] as const;
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try { try {
@ -21,22 +21,16 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
} }
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
const [header, footer, colors, style] = await Promise.all([ const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader), getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter), getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors), getGlobal(locals.pb, 'colors', defaultColors)
getGlobal(locals.pb, 'style', defaultStyle)
]); ]);
// All pages for the page selectors, with what the basket setting warns // Fetch all pages for the home page selector
// about (unpublished, no Checkout block). const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug', fields: 'id,slug,title' });
const records = await locals.pb.collection('pages').getFullList({ sort: 'slug', fields: 'id,slug,title,published,blocks' });
const pages = records.map((page) => {
const types = new Set(((page.blocks as { type?: string }[]) || []).map((block) => block.type));
return { id: page.id, slug: page.slug, title: page.title, published: !!page.published, hasCheckout: types.has('checkout') };
});
return { header, footer, colors, style, pages }; return { header, footer, colors, pages };
}; };
export const actions: Actions = { export const actions: Actions = {

View file

@ -1,25 +1,16 @@
<script lang="ts"> <script lang="ts">
import { browser } from '$app/environment';
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { fly, slide } from 'svelte/transition'; import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import { PRIVACY_PAGE_SLUG } from '$lib/admin/privacyTemplate'; import { PRIVACY_PAGE_SLUG } from '$lib/admin/privacyTemplate';
import { defaultStyle, shopLinks } from '$lib/types';
import { SITE_FONTS, readableTextOn, siteStyleVars } from '$shared/theme';
import type { SubmitFunction } from '@sveltejs/kit'; import type { SubmitFunction } from '@sveltejs/kit';
let { data, form } = $props(); let { data, form } = $props();
let header = $state(structuredClone(data.header.data)); let header = $state(structuredClone(data.header.data));
let footer = $state(structuredClone(data.footer.data)); let footer = $state(structuredClone(data.footer.data));
let colors = $state(structuredClone(data.colors.data)); let colors = $state(structuredClone(data.colors.data));
let style = $state({ ...defaultStyle, ...data.style.data });
// The sample below the style settings: the variables the public site gets, as an inline style.
let styleSample = $derived(Object.entries(siteStyleVars(style)).map(([name, value]) => `${name}:${value}`).join(';'));
let saving = $state(''); let saving = $state('');
// Older records may predate the CTA button and the basket page; the inputs below need values. // Older records may predate the CTA button; the inputs below need an object.
header.ctaButton ??= { label: '', href: '' }; header.ctaButton ??= { label: '', href: '' };
header.basketPage ??= '';
footer.privacyPage ??= ''; footer.privacyPage ??= '';
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; } function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
@ -43,45 +34,10 @@
{ key: 'accent', label: 'Accent', hint: 'Highlights' } { key: 'accent', label: 'Accent', hint: 'Highlights' }
]; ];
const pageBySlug = (slug: string) => data.pages.find((page) => page.slug === slug);
// Only addresses like "/book" are checked: the CTA may also point to "/" or another site.
function ctaProblem() {
const slug = header.ctaButton.href?.trim().match(/^\/([^/?#]+)\/?$/)?.[1];
if (!slug) return '';
const page = pageBySlug(slug);
if (!page) return `There is no page with the slug “${slug}”.`;
if (!page.published) return `“${page.title}” isn’t published yet.`;
return '';
}
// The page the basket links lead to: the basket page, else the CTA's address when that is a page here.
function basketProblem() {
const slug = shopLinks(header).basket.replace(/^\/|\/$/g, '');
const page = pageBySlug(slug);
// The CTA may point anywhere (even another site); a typed basket slug must be a page here.
if (!page) return header.basketPage?.trim() ? `There is no page with the slug “${slug}”.` : '';
if (!page.published) return `“${page.title}” isn’t published yet.`;
if (!page.hasCheckout) return `“${page.title}” has no Checkout block, so people can’t pay from it.`;
return '';
}
const isHex = (value: unknown) => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value); const isHex = (value: unknown) => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value);
// "Saved." goes away by itself after a moment; an error stays until the next save.
let statusShown = $state('');
$effect(() => {
if (!form?.section || !form.message) return;
statusShown = form.section;
if (!form.ok) return;
const timer = setTimeout(() => (statusShown = ''), 2500);
return () => clearTimeout(timer);
});
const motion = (ms: number) => (browser && matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : ms);
const submit: SubmitFunction = ({ formData }) => { const submit: SubmitFunction = ({ formData }) => {
saving = String(formData.get('section')); saving = String(formData.get('section'));
statusShown = '';
return async ({ update }) => { return async ({ update }) => {
// Re-run loads so the admin theme picks up saved colours immediately. // Re-run loads so the admin theme picks up saved colours immediately.
await update({ reset: false }); await update({ reset: false });
@ -93,23 +49,11 @@
<svelte:head><title>Site design | CMS</title></svelte:head> <svelte:head><title>Site design | CMS</title></svelte:head>
{#snippet status(section: string)} {#snippet status(section: string)}
{#if statusShown === section && form?.section === section && form.message} {#if form?.section === section && form.message}
<div class="alert mt-4 py-2 text-sm" class:alert-success={form.ok} class:alert-error={!form.ok} role="status" in:fly={{ y: 8, duration: motion(200) }} out:slide={{ duration: motion(350) }}> <div class="alert mt-4 py-2 text-sm" class:alert-success={form.ok} class:alert-error={!form.ok} role="status">{form.message}</div>
{form.message}
</div>
{/if} {/if}
{/snippet} {/snippet}
{#snippet info(text: string)}
<span class="tooltip tooltip-bottom sm:tooltip-right font-sans font-normal before:max-w-48" data-tip={text}>
<button class="btn btn-circle btn-ghost btn-xs text-base-content/60" type="button" aria-label={text}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">
<circle cx="12" cy="12" r="9" /><path stroke-linecap="round" d="M12 11v5M12 8h.01" />
</svg>
</button>
</span>
{/snippet}
{#snippet saveButton(section: string, label: string)} {#snippet saveButton(section: string, label: string)}
<div class="flex-grow"></div> <div class="flex-grow"></div>
{@render status(section)} {@render status(section)}
@ -121,25 +65,17 @@
<div class="mb-6"> <div class="mb-6">
<h1 class="text-3xl font-bold">Site design</h1> <h1 class="text-3xl font-bold">Site design</h1>
<p class="text-base-content/60">The header, footer, colors and style shared by every page of the site.</p> <p class="text-base-content/60">The header, footer and colors shared by every page of the site.</p>
</div> </div>
<div class="grid gap-6 xl:grid-cols-2 2xl:grid-cols-4"> <div class="grid gap-6 xl:grid-cols-3">
<form class="flex flex-col rounded-box bg-base-100 p-5 shadow" method="POST" action="?/save" use:enhance={submit}> <form class="flex flex-col rounded-box bg-base-100 p-5 shadow" method="POST" action="?/save" use:enhance={submit}>
<input type="hidden" name="id" value={data.header.id} /> <input type="hidden" name="id" value={data.header.id} />
<input type="hidden" name="section" value="header" /> <input type="hidden" name="section" value="header" />
<input type="hidden" name="data" value={JSON.stringify(header)} /> <input type="hidden" name="data" value={JSON.stringify(header)} />
<h2 class="mb-4 text-2xl font-bold">Header</h2> <h2 class="mb-4 text-2xl font-bold">Header</h2>
<h3 class="mb-2 font-bold">Logo</h3> <h3 class="mb-2 font-bold">Logo</h3>
<ImagePicker url={header.logo?.url} alt={header.logo?.alt} altHint="Usually the business name" onChange={(image) => (header.logo = { url: image.url, alt: image.alt })} /> <ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
<h3 class="mt-6 mb-2 font-bold">Home page</h3>
<select class="select w-full" aria-label="Home page" bind:value={header.homePage}>
<option value="">— Select a page —</option>
{#each data.pages as page (page.id)}
<option value={page.slug}>{page.title} [{page.slug}]</option>
{/each}
</select>
<p class="mt-1 text-sm text-base-content/60">The page that "/" will redirect to.</p>
<h3 class="mt-6 font-bold">Navigation</h3> <h3 class="mt-6 font-bold">Navigation</h3>
{#each header.navLinks || [] as link, i} {#each header.navLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2"> <div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
@ -149,18 +85,19 @@
</div> </div>
{/each} {/each}
<button class="btn btn-sm mt-1" type="button" onclick={addHeaderLink}>Add link</button> <button class="btn btn-sm mt-1" type="button" onclick={addHeaderLink}>Add link</button>
<h3 class="mt-6 mb-2 flex items-center gap-1 font-bold">CTA button {@render info('Hero buttons without a link and “Book another” after paying go here too.')}</h3> <h3 class="mt-6 mb-2 font-bold">CTA button</h3>
<div class="grid grid-cols-2 gap-2"> <div class="grid grid-cols-2 gap-2">
<input class="input w-full" aria-label="Button label" bind:value={header.ctaButton.label} placeholder="Label" /> <input class="input w-full" aria-label="Button label" bind:value={header.ctaButton.label} placeholder="Label" />
<input class="input w-full" aria-label="Button address" bind:value={header.ctaButton.href} placeholder="/book" /> <input class="input w-full" aria-label="Button address" bind:value={header.ctaButton.href} placeholder="/book" />
</div> </div>
{#if ctaProblem()}<p class="mt-1 text-sm font-semibold">⚠ {ctaProblem()}</p>{/if} <h3 class="mt-6 mb-2 font-bold">Home page</h3>
<h3 class="mt-6 mb-2 flex items-center gap-1 font-bold"> <select class="select w-full" aria-label="Home page" bind:value={header.homePage}>
Basket page <span class="font-normal text-base-content/50">(optional)</span> <option value="">— Select a page —</option>
{@render info('Slug of the page with the Checkout block. Empty = the CTA button’s page.')} {#each data.pages as page (page.id)}
</h3> <option value={page.slug}>{page.title} [{page.slug}]</option>
<input class="input w-full" aria-label="Basket page" bind:value={header.basketPage} placeholder="e.g. basket" /> {/each}
{#if basketProblem()}<p class="mt-1 text-sm font-semibold">⚠ {basketProblem()}</p>{/if} </select>
<p class="mt-1 text-sm text-base-content/60">The page that "/" will redirect to.</p>
{@render saveButton('header', 'Save header')} {@render saveButton('header', 'Save header')}
</form> </form>
@ -223,53 +160,4 @@
{/each} {/each}
{@render saveButton('colors', 'Save colors')} {@render saveButton('colors', 'Save colors')}
</form> </form>
<form class="flex flex-col rounded-box bg-base-100 p-5 shadow" method="POST" action="?/save" use:enhance={submit}>
<input type="hidden" name="id" value={data.style.id} />
<input type="hidden" name="section" value="style" />
<input type="hidden" name="data" value={JSON.stringify(style)} />
<h2 class="mb-4 text-2xl font-bold">Style</h2>
<p class="mb-2 text-sm text-base-content/60">Fonts and shapes for the public site. The fonts come with the site, so visitors' browsers don't contact Google for them.</p>
{#snippet fontSelect(label: string, key: 'headingFont' | 'bodyFont')}
<label class="fieldset py-1">
<span class="fieldset-legend pb-0">{label}</span>
<select class="select w-full" bind:value={style[key]}>
<optgroup label="Serif">
{#each SITE_FONTS.filter((font) => font.serif) as font (font.id)}
<option value={font.id} style="font-family: '{font.family}'">{font.label}</option>
{/each}
</optgroup>
<optgroup label="Sans-serif">
{#each SITE_FONTS.filter((font) => !font.serif) as font (font.id)}
<option value={font.id} style="font-family: '{font.family}'">{font.label}</option>
{/each}
</optgroup>
</select>
</label>
{/snippet}
{@render fontSelect('Headings', 'headingFont')}
{@render fontSelect('Body text', 'bodyFont')}
<div class="mt-3 space-y-2">
<SegmentedControl label="Corners" options={['sharp', 'soft', 'round']} value={style.corners} onChange={(v) => (style.corners = v as typeof style.corners)} />
<SegmentedControl label="Text size" options={['small', 'normal', 'large']} value={style.textSize} onChange={(v) => (style.textSize = v as typeof style.textSize)} />
<SegmentedControl label="Shadows" options={['none', 'soft', 'strong']} value={style.shadows} onChange={(v) => (style.shadows = v as typeof style.shadows)} />
<SegmentedControl label="Page width" options={['narrow', 'normal', 'wide']} value={style.width} onChange={(v) => (style.width = v as typeof style.width)} />
</div>
<p class="mt-1 text-sm text-base-content/60">Page width is how wide text and sections may get on a big screen; phones are unaffected.</p>
<!-- How the choices look. Inline styles, because the radius and shadow tokens in app.css
are worked out once for the whole page and can't follow variables set on this box. -->
<div
class="mt-4 border border-base-300 p-4"
style="{styleSample}; background: {colors.background}; color: {colors.text}; font-family: var(--site-font-body); font-size: var(--site-text-size); border-radius: calc(1rem * var(--site-corners))"
aria-label="Style sample"
>
<p class="text-2xl font-semibold" style="font-family: var(--site-font-heading); color: {colors.heading}">A calm space for you</p>
<div class="mt-3 bg-white p-3" style="border-radius: calc(1rem * var(--site-corners)); box-shadow: 0 1px 3px 0 rgb(0 0 0 / calc(0.1 * var(--site-shadow))), 0 1px 2px -1px rgb(0 0 0 / calc(0.1 * var(--site-shadow)))">
<p>Body text looks like this. Sessions last an hour.</p>
<span class="mt-3 inline-block px-5 py-2 text-sm font-medium" style="border-radius: var(--site-button-radius); background: {colors.primary}; color: {readableTextOn(colors.primary)}">Book</span>
</div>
</div>
{@render saveButton('style', 'Save style')}
</form>
</div> </div>

View file

@ -1,200 +1,86 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase'; import { getFileUrl } from '$lib/pb';
import { attempt, pbErrorMessage } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import { codesWaiting } from '$lib/server/passes'; import type { ItemRecord, ItemType } from '$lib/types';
import { parseDurations } from '$shared/items';
import { mapItemRecord } from '$shared/server/shop';
import type { BundlePart, ItemDuration, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
/** Longest bookable length, in minutes (a booking must fit in one day's window). */ function itemPayload(data: FormData) {
const MAX_DURATION_MINUTES = 12 * 60; const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
/** A service's lengths and prices from the form's `durationMinutes`/`durationPrice` rows (empty rows are skipped). */
function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
const minutes = data.getAll('durationMinutes').map((v) => String(v).trim());
const prices = data.getAll('durationPrice').map((v) => String(v).trim());
const durations: ItemDuration[] = [];
for (let i = 0; i < minutes.length; i++) {
if (minutes[i] === '' && (prices[i] ?? '') === '') continue;
const length = Number(minutes[i]);
const price = Number(prices[i]);
if (!Number.isInteger(length) || length < 5 || length > MAX_DURATION_MINUTES) return { error: `Each length must be a whole number of minutes from 5 to ${MAX_DURATION_MINUTES}.` };
if (prices[i] === '' || !Number.isFinite(price) || price < 0) return { error: `Give the ${length}-minute length a price (0 or more).` };
if (durations.some((d) => d.minutes === length)) return { error: `${length} minutes is listed twice.` };
durations.push({ minutes: length, price });
}
if (!durations.length) return { error: 'Add at least one length with its price.' };
return durations.sort((a, b) => a.minutes - b.minutes);
}
/** Priorities go from -this to this (the field's limits in pb_schema.json). Set by dragging the list (?/reorder), never typed. */
const MAX_PRIORITY = 1000;
/** Most units of one thing a bundle can hold. */
const MAX_PART_COUNT = 50;
/**
* A bundle's parts from the form's `partItem`/`partMinutes`/`partCount` rows:
* services (at one of their lengths) and products, not other bundles.
*/
function parseBundleRows(data: FormData, items: Record<string, any>[]): BundlePart[] | { error: string } {
const ids = data.getAll('partItem').map(String);
const minutes = data.getAll('partMinutes').map(String);
const counts = data.getAll('partCount').map(String);
const parts: BundlePart[] = [];
for (let i = 0; i < ids.length; i++) {
if (!ids[i]) continue;
const item = items.find((candidate) => candidate.id === ids[i]);
if (!item || item.type === 'bundle') return { error: 'A bundle can only contain services and products.' };
const count = Number(counts[i]);
if (!Number.isInteger(count) || count < 1 || count > MAX_PART_COUNT) return { error: `How many of “${item.name}”: a whole number from 1 to ${MAX_PART_COUNT}.` };
let length: number | null = null;
if (item.type === 'item_with_time') {
length = Number(minutes[i]);
if (!parseDurations(item.durations).some((d) => d.minutes === length)) return { error: `Choose one of the lengths “${item.name}” is offered for.` };
}
if (parts.some((p) => p.item === item.id && p.minutes === length)) return { error: `“${item.name}” is listed twice — raise its count instead.` };
parts.push({ item: item.id, minutes: length, count });
}
if (!parts.some((p) => p.minutes)) return { error: 'A bundle needs at least one service — its code is what books it.' };
return parts;
}
function itemPayload(data: FormData, items: Record<string, any>[]) {
const rawType = String(data.get('type'));
const type: ItemType = rawType === 'item_with_time' || rawType === 'bundle' ? rawType : 'item';
const name = String(data.get('name') || '').trim();
if (!name) return { error: 'Name is required.' };
const rawStock = String(data.get('stock') ?? '').trim(); const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').trim(); const rawCapacity = String(data.get('capacity') ?? '').trim();
let price: number;
let durations: ItemDuration[] = [];
let bundleParts: BundlePart[] = [];
let validMonths: number | null = null;
if (type === 'bundle') {
const parsed = parseBundleRows(data, items.filter((item) => item.id !== String(data.get('id') || '')));
if ('error' in parsed) return parsed;
bundleParts = parsed;
price = parseFloat(String(data.get('price') || ''));
if (Number.isNaN(price) || price <= 0) return { error: 'A bundle needs a price above 0.' };
const rawMonths = String(data.get('validMonths') ?? '').trim();
validMonths = rawMonths === '' ? null : Number(rawMonths);
if (validMonths !== null && !(Number.isInteger(validMonths) && validMonths >= 1 && validMonths <= 120)) return { error: 'Valid for: 1 to 120 months, or empty for no expiry.' };
} else if (type === 'item_with_time') {
const parsed = parseDurationRows(data);
if ('error' in parsed) return parsed;
durations = parsed;
// Kept as the lowest duration price: what "from …" and old readers show.
price = Math.min(...durations.map((d) => d.price));
} else {
price = parseFloat(String(data.get('price') || ''));
if (Number.isNaN(price) || price < 0) return { error: 'A valid price is required.' };
}
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null; const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null; const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null; const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null;
return { return {
payload: { name: String(data.get('name') || '').trim(),
name, description: String(data.get('description') || '').trim(),
description: String(data.get('description') || '').trim(), price: parseFloat(String(data.get('price') || '')),
price, image: String(data.get('image') || '').trim(),
image: String(data.get('image') || '').trim(), type,
type, stock: Number.isNaN(stock) ? null : stock,
// Empty = unlimited (PocketBase can't store an empty number, hence the flag). duration: Number.isNaN(duration) ? null : duration,
stock: Number.isNaN(stock) ? 0 : (stock ?? 0), bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
trackStock: stock !== null && !Number.isNaN(stock), capacity: Number.isNaN(capacity) ? null : capacity,
durations, active: String(data.get('active')) === 'true'
bundleParts,
validMonths,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
capacity: Number.isNaN(capacity) ? null : capacity,
active: String(data.get('active')) === 'true'
}
}; };
} }
/** Every item, for checking what a bundle may contain. */ function normalizeItem(record: Record<string, any>): ItemRecord {
function allItems(pb: App.Locals['pb']) { const media = record.expand?.image;
return pb.collection('items').getFullList({ fields: 'id,name,type,durations,priority' }).catch(() => []); return {
id: record.id,
name: String(record.name || ''),
description: String(record.description || ''),
price: Number(record.price) || 0,
image: String(record.image || ''),
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type === 'item_with_time' ? 'item_with_time' : 'item',
stock: record.stock ?? null,
duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
};
} }
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
const [records, waiting] = await Promise.all([ const records = await locals.pb
locals.pb .collection('items')
.collection('items') .getFullList({ sort: 'name', expand: 'image' })
.getFullList({ sort: '-priority,name', expand: 'image' }) .catch(() => []);
.catch(() => []), const items = records.map((record) => normalizeItem(record));
codesWaiting(locals.pb).catch(() => ({}) as Record<string, number>) return { items };
]);
return { items: records.map(mapItemRecord), waiting };
}; };
export const actions: Actions = { export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const items = await allItems(locals.pb); const data = await request.formData();
const result = itemPayload(await request.formData(), items); const payload = itemPayload(data);
if ('error' in result) return fail(400, { message: result.error }); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
// New items go to the end of the shop order; drag them up from there. const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload));
const lowest = items.length ? Math.min(...items.map((item) => Number(item.priority) || 0)) : 1; if (!result.ok) return result.failure;
const priority = Math.max(-MAX_PRIORITY, lowest - 1);
const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create({ ...result.payload, priority }));
if (!created.ok) return created.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
const result = itemPayload(data, await allItems(locals.pb)); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
if ('error' in result) return fail(400, { message: result.error }); const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload));
const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload)); if (!result.ok) return result.failure;
if (!updated.ok) return updated.failure;
return { ok: true }; return { ok: true };
}, },
/**
* The list's new order (`order`: JSON item ids, first = shown first) →
* priorities n…1. Only items whose priority changes are written; items
* missing from the list (added meanwhile) go after it.
*/
reorder: async ({ request, locals }) => {
let ids: unknown;
try {
ids = JSON.parse(String((await request.formData()).get('order') || '[]'));
} catch {
ids = null;
}
if (!Array.isArray(ids) || !ids.every((id) => typeof id === 'string')) return fail(400, { message: 'Could not read the new order — reload the page and try again.' });
const records = await locals.pb.collection('items').getFullList({ fields: 'id,priority', sort: '-priority,name' });
const known = new Set(records.map((record) => record.id));
const listed = [...new Set(ids as string[])].filter((id) => known.has(id));
const ordered = [...listed, ...records.map((record) => record.id).filter((id) => !listed.includes(id))];
if (ordered.length > MAX_PRIORITY) return fail(400, { message: `The order can only be set for up to ${MAX_PRIORITY} items.` });
const current = new Map(records.map((record) => [record.id, Number(record.priority) || 0]));
for (const [index, id] of ordered.entries()) {
const priority = ordered.length - index;
if (current.get(id) === priority) continue;
const saved = await attempt('Could not save the order.', () => locals.pb.collection('items').update(id, { priority }));
if (!saved.ok) return saved.failure;
}
return { ok: true, message: 'Order saved.' };
},
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
try { const result = await attempt('Could not delete the item — if it has slots or past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
await locals.pb.collection('items').delete(id); if (!result.ok) return result.failure;
} catch (e) {
// In a bundle, or still to be booked with a code: the shop hook says which.
if (e instanceof ClientResponseError && e.response?.data?.item?.code === 'in_use') return fail(400, { message: String(e.response.message) });
console.error('[action] Could not delete the item', e);
return fail(400, { message: pbErrorMessage(e, 'Could not delete the item — if it has past orders, switch it to inactive instead.') });
}
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -1,96 +1,15 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { uploadMedia } from '$lib/pb';
import ImagePicker from '$lib/admin/editors/ImagePicker.svelte';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import SaveStatus from '$lib/admin/SaveStatus.svelte';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
let showEditor = $state(false); let showEditor = $state(false);
let uploading = $state(false); let uploading = $state(false);
let uploadError = $state('');
// ── Shop order ───────────────────────────────────────────────────── let fileInput: HTMLInputElement | undefined = $state();
// The list is in shop order (highest priority first). Dragging a row (or
// the arrow keys on its handle) changes `order` here; "Save order" turns
// it into priorities on the server (?/reorder). null = as saved.
let order = $state<string[] | null>(null);
let shown = $derived.by(() => {
if (!order) return items;
const byId = new Map(items.map((item: ItemRecord) => [item.id, item]));
const listed = order.map((id) => byId.get(id)).filter((item): item is ItemRecord => !!item);
// Anything added meanwhile (another tab) goes at the end.
return [...listed, ...items.filter((item: ItemRecord) => !order!.includes(item.id))];
});
let orderChanged = $derived(!!order && shown.map((item) => item.id).join() !== items.map((item: ItemRecord) => item.id).join());
let savingOrder = $state(false);
warnOnUnsavedChanges(() => orderChanged);
function move(from: number, to: number) {
if (to < 0 || to >= shown.length || from === to) return;
const ids = shown.map((item) => item.id);
const [id] = ids.splice(from, 1);
ids.splice(to, 0, id);
order = ids;
}
// Mouse: native drag and drop on the whole row. Touch: phones don't fire
// drag events, so the handle follows the finger with pointer events (as
// in the page editor's block list).
let dragIndex = $state<number | null>(null);
let dropIndex = $state<number | null>(null);
function endDrag() {
if (dragIndex !== null && dropIndex !== null) move(dragIndex, dropIndex);
dragIndex = null;
dropIndex = null;
}
function rowDrag(index: number) {
return {
draggable: true,
ondragstart: (e: DragEvent) => {
dragIndex = index;
// Firefox won't start a drag without data.
e.dataTransfer?.setData('text/plain', String(index));
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
},
ondragover: (e: DragEvent) => {
e.preventDefault();
dropIndex = index;
},
ondrop: (e: DragEvent) => {
e.preventDefault();
endDrag();
},
ondragend: () => {
dragIndex = null;
dropIndex = null;
}
};
}
function touchDragStart(e: PointerEvent, index: number) {
if (e.pointerType === 'mouse') return;
e.preventDefault();
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
dragIndex = index;
dropIndex = index;
}
function touchDragMove(e: PointerEvent) {
if (dragIndex === null) return;
// The rows are the children of the list (phones) or the table body.
const rows = [...((e.currentTarget as HTMLElement).closest('ul, tbody')?.children ?? [])] as HTMLElement[];
const over = rows.findIndex((row) => e.clientY < row.getBoundingClientRect().bottom);
dropIndex = over === -1 ? rows.length - 1 : over;
// The handle blocks scrolling, so scroll for the finger near the screen's edges.
if (e.clientY < 64) window.scrollBy(0, -12);
else if (e.clientY > window.innerHeight - 64) window.scrollBy(0, 12);
}
type ItemDraft = { type ItemDraft = {
id: string; id: string;
@ -101,11 +20,7 @@
imageUrl: string; imageUrl: string;
type: ItemType; type: ItemType;
stock: string; stock: string;
/** Service lengths and prices, as typed (one form row each). */ duration: string;
durations: { minutes: string; price: string }[];
/** Bundle contents, as typed (one form row each); minutes '' for a product. */
parts: { item: string; minutes: string; count: string }[];
validMonths: string;
bufferMinutes: string; bufferMinutes: string;
capacity: string; capacity: string;
active: boolean; active: boolean;
@ -117,71 +32,12 @@
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft { function emptyDraft(): ItemDraft {
return { return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true };
id: '',
name: '',
description: '',
price: 0,
image: '',
imageUrl: '',
type: 'item',
stock: '',
durations: [{ minutes: '60', price: '' }],
parts: [{ item: '', minutes: '', count: '1' }],
validMonths: '12',
bufferMinutes: '',
capacity: '',
active: true
};
}
/** What a bundle can contain: services and products (never itself or another bundle). */
let partChoices = $derived(items.filter((item) => item.type !== 'bundle' && item.id !== draft.id));
function choosePartItem(row: ItemDraft['parts'][number], id: string) {
row.item = id;
const item = items.find((candidate) => candidate.id === id);
row.minutes = item?.durations[0] ? String(item.durations[0].minutes) : '';
}
/** "3× Massage (1 hour), 1× Oil" for the table. */
function bundleList(item: ItemRecord) {
const names = new Map(items.map((i) => [i.id, i.name]));
return item.bundleParts.map((p) => `${p.count}× ${names.get(p.item) ?? 'deleted item'}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', ');
}
/** Why an active bundle isn't on sale (the shop hides it and won't sell it), or ''. */
function bundleProblem(item: ItemRecord) {
for (const part of item.bundleParts) {
const partItem = items.find((i) => i.id === part.item);
if (!partItem) return 'One of its parts was deleted — edit the bundle.';
if (!partItem.active) return `“${partItem.name}” is inactive.`;
if (part.minutes && !partItem.durations.some((d) => d.minutes === part.minutes)) return `“${partItem.name}” is no longer offered for ${formatDuration(part.minutes)}.`;
}
return '';
}
/** What the parts cost on their own, to compare with the bundle price. */
let partsListPrice = $derived(
draft.parts.reduce((sum, row) => {
const item = items.find((candidate) => candidate.id === row.item);
const unit = item?.type === 'item_with_time' ? (item.durations.find((d) => String(d.minutes) === row.minutes)?.price ?? 0) : (item?.price ?? 0);
return sum + unit * (Number(row.count) || 0);
}, 0)
);
function addDuration() {
const last = Number(draft.durations.at(-1)?.minutes) || 0;
draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' });
}
/** "1 hour / 2 hours" for the table. */
function durationList(item: ItemRecord) {
return item.durations.map((d) => formatDuration(d.minutes)).join(' / ') || 'no lengths set';
} }
function createItem() { function createItem() {
draft = emptyDraft(); draft = emptyDraft();
uploadError = '';
showEditor = true; showEditor = true;
} }
@ -195,15 +51,31 @@
imageUrl: item.imageUrl, imageUrl: item.imageUrl,
type: item.type, type: item.type,
stock: item.stock == null ? '' : String(item.stock), stock: item.stock == null ? '' : String(item.stock),
durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }], duration: item.duration == null ? '' : String(item.duration),
parts: item.bundleParts.length ? item.bundleParts.map((p) => ({ item: p.item, minutes: p.minutes ? String(p.minutes) : '', count: String(p.count) })) : [{ item: '', minutes: '', count: '1' }],
validMonths: item.type === 'bundle' ? (item.validMonths == null ? '' : String(item.validMonths)) : '12',
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity), capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active active: item.active
}; };
uploadError = '';
showEditor = true; showEditor = true;
} }
async function onImageSelected(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
uploading = true;
uploadError = '';
try {
const result = await uploadMedia(file);
draft = { ...draft, image: result.record.id, imageUrl: result.url };
} catch (err) {
uploadError = err instanceof Error ? err.message : 'Upload failed.';
} finally {
uploading = false;
input.value = '';
}
}
</script> </script>
<svelte:head><title>Services & products | CMS</title></svelte:head> <svelte:head><title>Services & products | CMS</title></svelte:head>
@ -212,162 +84,39 @@
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div>
<h1 class="text-3xl font-bold">Services & products</h1> <h1 class="text-3xl font-bold">Services & products</h1>
<p class="text-base-content/60">Bookable services, products and bundles (codes for sessions booked later). Shop blocks show them in this order (their <em>Recommended</em> order): drag <span aria-hidden="true">⠿</span> to change it.</p> <p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button> <button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
</div> </div>
<SaveStatus result={form} /> {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
{#if orderChanged} <div class="rounded-box bg-base-100 p-5 shadow">
<!-- Sticky, so Save stays in reach while dragging down a long list. -->
<form
method="POST"
action="?/reorder"
class="sticky top-2 z-10 flex flex-wrap items-center gap-3 rounded-box bg-base-100 p-3 shadow-lg"
use:enhance={() => {
savingOrder = true;
return async ({ result, update }) => {
await update();
savingOrder = false;
// Saved: the reloaded list is in the new order.
if (result.type === 'success') order = null;
};
}}
>
<input type="hidden" name="order" value={JSON.stringify(shown.map((item) => item.id))} />
<span class="badge badge-warning">Unsaved order</span>
<span class="min-w-40 flex-1 text-sm text-base-content/70">Shop blocks change once it’s saved.</span>
<span class="ml-auto flex gap-2">
<button class="btn btn-sm" type="button" disabled={savingOrder} onclick={() => (order = null)}>Undo</button>
<button class="btn btn-primary btn-sm" type="submit" disabled={savingOrder}>Save order</button>
</span>
</form>
{/if}
{#snippet thumbnail(item: ItemRecord)}
{#if item.imageUrl}
<img class="size-10 shrink-0 rounded-box object-cover" src={item.imageUrl} alt="" />
{:else}
<div class="size-10 shrink-0 rounded-box bg-base-200"></div>
{/if}
{/snippet}
{#snippet handle(item: ItemRecord, index: number)}
<!-- A button so the keyboard can move it too (↑/↓); the pointer drags the whole row. -->
<button
class="btn btn-ghost btn-sm btn-square shrink-0 cursor-grab touch-none text-xl text-base-content/50"
type="button"
title="Drag to change the order (or focus and press ↑/↓)"
aria-label="Move {item.name} — use the arrow keys"
disabled={shown.length < 2}
onpointerdown={(e) => touchDragStart(e, index)}
onpointermove={touchDragMove}
onpointerup={endDrag}
onpointercancel={() => {
dragIndex = null;
dropIndex = null;
}}
onkeydown={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
e.preventDefault();
const to = index + (e.key === 'ArrowUp' ? -1 : 1);
move(index, to);
// Keep the focus on this item's handle in its new place.
const button = e.currentTarget;
requestAnimationFrame(() => (button.closest('ul, tbody')?.children[Math.max(0, Math.min(to, shown.length - 1))]?.querySelector('button') as HTMLElement | null)?.focus());
}}>⠿</button
>
{/snippet}
{#snippet typeBadge(item: ItemRecord)}
<span class="badge">{item.type === 'item_with_time' ? 'Service' : item.type === 'bundle' ? 'Bundle' : 'Product'}</span>
{/snippet}
{#snippet price(item: ItemRecord)}{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}{/snippet}
{#snippet details(item: ItemRecord)}
{#if item.type === 'item_with_time'}
{durationList(item)}{item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}{(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}
{:else if item.type === 'bundle'}
{bundleList(item)} · {item.validMonths ? `valid ${item.validMonths} months` : 'no expiry'}
{:else}—{/if}
{/snippet}
{#snippet status(item: ItemRecord, problem: string)}
{#if problem}
<span class="badge badge-warning whitespace-nowrap">Not on sale</span>
{:else}
<span class="badge whitespace-nowrap" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span>
{/if}
{/snippet}
{#snippet notes(problem: string, waiting: number)}
{#if problem}
<span class="mt-1 block text-xs text-base-content/60">{problem}</span>
{/if}
{#if waiting}
<span class="mt-1 block text-xs text-base-content/70">{waiting === 1 ? '1 code has' : `${waiting} codes have`} sessions of this left to book — they can’t while it’s inactive.</span>
{/if}
{/snippet}
<!-- Phones and tablets: one card per item (seven columns didn't fit; long bundle lists made rows very tall). -->
<ul class="divide-y divide-base-200 rounded-box bg-base-100 shadow lg:hidden">
{#each shown as item, i (item.id)}
{@const problem = item.type === 'bundle' && item.active ? bundleProblem(item) : ''}
{@const waiting = !item.active && item.type === 'item_with_time' ? (data.waiting[item.id] ?? 0) : 0}
<li class="p-4 pl-2 transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
<div class="flex items-start gap-2">
{@render handle(item, i)}
{@render thumbnail(item)}
<div class="min-w-0 flex-1">
<span class="block font-semibold break-words">{item.name}</span>
<div class="mt-1 flex flex-wrap items-center gap-2 text-sm">
{@render typeBadge(item)}
{@render status(item, problem)}
<span class="text-base-content/70">{@render price(item)}{item.type === 'item' ? ` · stock ${item.stock ?? '∞'}` : ''}</span>
</div>
{#if item.type !== 'item'}
<p class="mt-2 text-sm text-base-content/70">{@render details(item)}</p>
{/if}
{@render notes(problem, waiting)}
</div>
<button class="btn btn-sm shrink-0" type="button" onclick={() => editItem(item)}>Edit</button>
</div>
</li>
{:else}
<li class="py-10 text-center text-base-content/60">No items yet — create a service or product.</li>
{/each}
</ul>
<div class="hidden rounded-box bg-base-100 p-5 shadow lg:block">
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th class="w-0"><span class="sr-only">Order</span></th><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead> <thead><tr><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each shown as item, i (item.id)} {#each items as item (item.id)}
{@const problem = item.type === 'bundle' && item.active ? bundleProblem(item) : ''} <tr>
{@const waiting = !item.active && item.type === 'item_with_time' ? (data.waiting[item.id] ?? 0) : 0}
<tr class="transition-colors" class:opacity-50={dragIndex === i} class:bg-base-200={dropIndex === i && dragIndex !== i} {...rowDrag(i)}>
<td class="pr-0">{@render handle(item, i)}</td>
<td> <td>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
{@render thumbnail(item)} {#if item.imageUrl}
<img class="size-10 rounded-box object-cover" src={item.imageUrl} alt="" />
{:else}
<div class="size-10 rounded-box bg-base-200"></div>
{/if}
<span class="font-semibold">{item.name}</span> <span class="font-semibold">{item.name}</span>
</div> </div>
</td> </td>
<td>{@render typeBadge(item)}</td> <td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{@render price(item)}</td> <td>{money.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td> <td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
<td>{@render details(item)}</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> <td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
{@render status(item, problem)}
{@render notes(problem, waiting)}
</td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr> </tr>
{:else} {:else}
<tr><td colspan="8" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr> <tr><td colspan="7" class="py-10 text-center text-base-content/60">No items yet — create a service or product.</td></tr>
{/each} {/each}
</tbody> </tbody>
</table> </table>
@ -391,115 +140,68 @@
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea> <textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label> </label>
<label class="fieldset"> <div class="grid gap-x-4 md:grid-cols-2">
<span class="fieldset-legend">Type</span> <label class="fieldset">
<select class="select w-full" name="type" bind:value={draft.type}> <span class="fieldset-legend">Price ({data.currency})</span>
<option value="item">Product</option> <input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
<option value="item_with_time">Service (bookable)</option> </label>
<option value="bundle">Bundle / voucher (paid now, booked later with a code)</option> <label class="fieldset">
</select> <span class="fieldset-legend">Type</span>
</label> <select class="select w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service (bookable)</option>
</select>
</label>
</div>
{#if draft.type === 'bundle'} {#if draft.type === 'item'}
<div class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">What’s in it</span> <span class="fieldset-legend">Stock</span>
<div class="space-y-2"> <input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
{#each draft.parts as row, i} </label>
{@const partItem = items.find((item) => item.id === row.item)}
<div class="flex flex-wrap items-center gap-2">
<input class="input w-20" type="number" min="1" max="50" step="1" name="partCount" required aria-label="How many" bind:value={row.count} />
<span>×</span>
<select class="select w-56" name="partItem" required aria-label="Service or product" value={row.item} onchange={(e) => choosePartItem(row, e.currentTarget.value)}>
<option value="" disabled>Choose…</option>
{#each partChoices as choice (choice.id)}<option value={choice.id}>{choice.name}{choice.type === 'item' ? ' (product)' : ''}</option>{/each}
</select>
{#if partItem?.type === 'item_with_time'}
<select class="select w-36" name="partMinutes" aria-label="Length" bind:value={row.minutes}>
{#each partItem.durations as duration (duration.minutes)}<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>{/each}
</select>
{:else}
<input type="hidden" name="partMinutes" value="" />
{/if}
{#if draft.parts.length > 1}
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove this part" onclick={() => draft.parts.splice(i, 1)}>✕</button>
{/if}
</div>
{/each}
</div>
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={() => draft.parts.push({ item: '', minutes: '', count: '1' })}>+ Add a service or product</button>
<span class="label whitespace-normal">The buyer gets a code; whoever has it books the services, each at the length set here, without paying again. Products are handed over with the purchase. A one-service voucher is a bundle with one part.</span>
</div>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Bundle price ({data.currency})</span>
<input class="input w-full" type="number" step="0.01" min="0.01" name="price" required bind:value={draft.price} />
{#if partsListPrice}<span class="label">Bought separately: {money.format(partsListPrice)}</span>{/if}
</label>
<label class="fieldset">
<span class="fieldset-legend">Valid for (months)</span>
<input class="input w-full" type="number" min="1" max="120" step="1" name="validMonths" placeholder="No expiry" bind:value={draft.validMonths} />
<span class="label">From the day it’s bought. Check local rules on minimum validity for gift cards.</span>
</label>
</div>
{:else if draft.type === 'item'}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Price ({data.currency})</span>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label>
<label class="fieldset">
<span class="fieldset-legend">Stock</span>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
</div>
{:else} {:else}
<div class="fieldset">
<span class="fieldset-legend">Lengths and prices</span>
<div class="space-y-2">
{#each draft.durations as row, i}
<div class="flex flex-wrap items-center gap-2">
<label class="input w-36">
<input type="number" min="5" max="720" step="5" name="durationMinutes" required aria-label="Length in minutes" bind:value={row.minutes} />
<span class="label">min</span>
</label>
<label class="input w-40">
<input type="number" min="0" step="0.01" name="durationPrice" required aria-label="Price for this length" bind:value={row.price} />
<span class="label">{data.currency}</span>
</label>
{#if Number(row.minutes) >= 5}<span class="text-sm text-base-content/60">{formatDuration(Number(row.minutes))}</span>{/if}
{#if draft.durations.length > 1}
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove this length" onclick={() => draft.durations.splice(i, 1)}>✕</button>
{/if}
</div>
{/each}
</div>
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addDuration}>+ Add a length</button>
<span class="label">Customers pick a length with a slider in the shop; the price follows it.</span>
</div>
<div class="grid gap-x-4 md:grid-cols-2"> <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"> <label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span> <span class="fieldset-legend">Get-ready time (minutes)</span>
<input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} /> <input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each appointment, before the next one can start</span> <span class="label">Gap after each appointment — between generated slots, and before another service can start</span>
</label> </label>
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Places in a group session</span> <span class="fieldset-legend">Places per slot</span>
<input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} /> <input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} />
<span class="label">Only for group sessions (Slots → group session). New sessions start with this.</span> <span class="label">1 for one-to-one; more for a group session. New slots start with this.</span>
</label> </label>
</div> </div>
{/if} {/if}
<div class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Image</span> <span class="fieldset-legend">Image</span>
<ImagePicker url={draft.imageUrl} withUrl={false} altHint="" bind:uploading onChange={(image) => (draft = { ...draft, image: image.id ?? draft.image, imageUrl: image.url })}> <div class="flex items-center gap-4">
<p>The shop uses the name as the image’s alt text.</p> {#if draft.imageUrl}
</ImagePicker> <img class="size-20 rounded-box object-cover shadow" src={draft.imageUrl} alt="" />
{:else}
<div class="grid size-20 place-items-center rounded-box border-2 border-dashed border-base-300 text-xs text-base-content/40">No image</div>
{/if}
<div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" disabled={uploading} onclick={() => fileInput?.click()}>
{#if uploading}<span class="loading loading-spinner loading-xs"></span> Uploading…{:else}{draft.imageUrl ? 'Replace image' : 'Upload image'}{/if}
</button>
{#if draft.image}
<button class="btn btn-ghost btn-sm text-error" type="button" onclick={() => (draft = { ...draft, image: '', imageUrl: '' })}>Remove</button>
{/if}
</div>
<input class="hidden" type="file" accept="image/*" bind:this={fileInput} onchange={onImageSelected} />
</div>
{#if uploadError}<span class="label text-error">{uploadError}</span>{/if}
</div> </div>
<label class="label mt-2 cursor-pointer gap-3 whitespace-normal text-base-content"> <label class="label mt-2 cursor-pointer gap-3 text-base-content">
<input class="toggle toggle-success shrink-0" type="checkbox" bind:checked={draft.active} /> <input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} />
<span>Active <span class="text-base-content/60">— inactive items are hidden from the shop</span></span> Active <span class="text-base-content/60">— inactive items are hidden from the shop</span>
</label> </label>
<div class="modal-action justify-between"> <div class="modal-action justify-between">

View file

@ -19,7 +19,7 @@ export const actions: Actions = {
return fail(400, { email, message: 'Invalid email or password.' }); return fail(400, { email, message: 'Invalid email or password.' });
} }
throw redirect(303, '/'); throw redirect(303, '/pages');
}, },
logout: async ({ locals }) => { logout: async ({ locals }) => {
locals.pb.authStore.clear(); locals.pb.authStore.clear();

View file

@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
let { form } = $props(); let { form } = $props();
let submitting = $state(false); let submitting = $state(false);
let showPassword = $state(false);
</script> </script>
<svelte:head><title>Sign in | CMS</title></svelte:head> <svelte:head><title>Sign in | CMS</title></svelte:head>
@ -24,16 +23,10 @@
<!-- svelte-ignore a11y_autofocus --> <!-- svelte-ignore a11y_autofocus -->
<input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus /> <input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus />
</label> </label>
<div class="flex flex-col gap-1"> <label class="flex flex-col gap-1">
<label class="fieldset-legend p-0" for="password">Password</label> <span class="fieldset-legend p-0">Password</span>
<!-- DaisyUI's input wrapper: the field and the Show button share one box. --> <input class="input w-full" name="password" type="password" autocomplete="current-password" required />
<div class="input w-full pr-1"> </label>
<input class="grow" id="password" name="password" type={showPassword ? 'text' : 'password'} autocomplete="current-password" required />
<button class="btn btn-ghost btn-xs" type="button" aria-controls="password" aria-pressed={showPassword} onclick={() => (showPassword = !showPassword)}>
{showPassword ? 'Hide' : 'Show'}
</button>
</div>
</div>
</fieldset> </fieldset>
<button class="btn btn-primary w-full" type="submit" disabled={submitting}> <button class="btn btn-primary w-full" type="submit" disabled={submitting}>
{#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if} {#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if}

View file

@ -1,6 +1,5 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { sendOrderEmails, type EmailKind } from '$lib/server/email'; import { sendOrderEmails, type EmailKind } from '$lib/server/email';
import { formatCode } from '$shared/items';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
@ -9,20 +8,13 @@ export const load: PageServerLoad = async ({ locals }) => {
// can't be ordered chronologically). // can't be ordered chronologically).
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []); const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
// All lines in one request (previously one request per order), with the // All lines in one request (previously one request per order).
// code that paid each; and the codes each order bought. const lineRecords = records.length
const [lineRecords, passRecords] = records.length ? await locals.pb
? await Promise.all([ .collection('order_lines')
locals.pb .getFullList({ sort: 'start' })
.collection('order_lines') .catch(() => [])
.getFullList({ sort: 'start', expand: 'pass' }) : [];
.catch(() => []),
locals.pb
.collection('passes')
.getFullList({ filter: "order != ''", sort: 'created', fields: 'order,code,name,recipientName' })
.catch(() => [])
])
: [[], []];
const linesByOrder = new Map<string, typeof lineRecords>(); const linesByOrder = new Map<string, typeof lineRecords>();
for (const line of lineRecords) { for (const line of lineRecords) {
const list = linesByOrder.get(line.order) ?? []; const list = linesByOrder.get(line.order) ?? [];
@ -47,13 +39,8 @@ export const load: PageServerLoad = async ({ locals }) => {
price: Number(line.price) || 0, price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1, quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'), lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : '', start: line.start ? String(line.start) : ''
minutes: Number(line.minutes) || 0, }))
passCode: line.expand?.pass?.code ? formatCode(String(line.expand.pass.code)) : ''
})),
passes: passRecords
.filter((pass) => pass.order === record.id)
.map((pass) => ({ code: formatCode(String(pass.code)), name: String(pass.name || ''), recipientName: String(pass.recipientName || '') }))
})); }));
return { orders }; return { orders };

View file

@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { formatDateTime } from '$lib/calendar'; import { formatDateTime } from '$lib/calendar';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let orders = $derived(data.orders || []); let orders = $derived(data.orders || []);
@ -73,20 +72,11 @@
<li> <li>
{line.quantity}× {line.name} — {money.format(line.price)} {line.quantity}× {line.name} — {money.format(line.price)}
{#if line.lineType === 'slot' && line.start} {#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</span> <span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}</span>
{/if}
{#if line.passCode}
<span class="block text-sm text-base-content/60">Paid with code <a class="link font-mono" href="/passes?q={encodeURIComponent(line.passCode)}">{line.passCode}</a></span>
{/if} {/if}
</li> </li>
{/each} {/each}
</ul> </ul>
{#if order.passes.length}
<p class="mt-2 text-sm">
{order.passes.length === 1 ? 'Code' : 'Codes'} bought:
{#each order.passes as pass, i (pass.code)}{i ? ', ' : ''}<a class="link font-mono" href="/passes?q={encodeURIComponent(pass.code)}">{pass.code}</a>{pass.recipientName ? ` (for ${pass.recipientName})` : ''}{/each}
</p>
{/if}
{#if order.customerDetails?.notes} {#if order.customerDetails?.notes}
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p> <p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>

View file

@ -24,45 +24,7 @@
<div class="alert alert-error mb-4" role="alert">{form.message}</div> <div class="alert alert-error mb-4" role="alert">{form.message}</div>
{/if} {/if}
{#snippet actions(page: (typeof data.pages)[number])} <div class="overflow-x-auto rounded-box bg-base-100 shadow">
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
{#if siteUrl && page.published}
<a class="btn btn-sm" href={publicUrl(page.slug)} target="_blank" rel="noopener" title="Open on the live site">View</a>
{/if}
<form method="POST" action="?/toggle">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="published" value={page.published} />
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
</form>
<form method="POST" action="?/delete" onsubmit={confirmSubmit(`Delete the page "${page.title}"? This cannot be undone.`)}>
<input type="hidden" name="id" value={page.id} />
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
</form>
{/snippet}
{#snippet status(page: (typeof data.pages)[number])}
<span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span>
{/snippet}
<!-- Phones: one card per page, buttons under the title (a four-column table didn't fit). -->
<ul class="divide-y divide-base-200 rounded-box bg-base-100 shadow md:hidden">
{#each data.pages as page (page.id)}
<li class="p-4">
<div class="flex items-start justify-between gap-3">
<a class="min-w-0" href={`/pages/${page.slug}`}>
<span class="block font-semibold break-words">{page.title}</span>
<span class="block font-mono text-sm break-all text-base-content/60">/{page.slug}</span>
</a>
<span class="shrink-0">{@render status(page)}</span>
</div>
<div class="mt-3 flex flex-wrap gap-2">{@render actions(page)}</div>
</li>
{:else}
<li class="py-10 text-center text-base-content/60">No pages yet — create your first one.</li>
{/each}
</ul>
<div class="hidden overflow-x-auto rounded-box bg-base-100 shadow md:block">
<table class="table"> <table class="table">
<thead> <thead>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr> <tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
@ -72,9 +34,23 @@
<tr> <tr>
<td class="font-mono">{page.slug}</td> <td class="font-mono">{page.slug}</td>
<td>{page.title}</td> <td>{page.title}</td>
<td>{@render status(page)}</td> <td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<td> <td>
<div class="flex flex-wrap justify-end gap-2 xl:flex-nowrap">{@render actions(page)}</div> <div class="flex flex-wrap justify-end gap-2">
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
{#if siteUrl && page.published}
<a class="btn btn-sm" href={publicUrl(page.slug)} target="_blank" rel="noopener" title="Open on the live site">View</a>
{/if}
<form method="POST" action="?/toggle">
<input type="hidden" name="id" value={page.id} />
<input type="hidden" name="published" value={page.published} />
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
</form>
<form method="POST" action="?/delete" onsubmit={confirmSubmit(`Delete the page "${page.title}"? This cannot be undone.`)}>
<input type="hidden" name="id" value={page.id} />
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
</form>
</div>
</td> </td>
</tr> </tr>
{:else} {:else}

View file

@ -1,7 +1,6 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import BlockList from '$lib/admin/BlockList.svelte'; import BlockList from '$lib/admin/BlockList.svelte';
import SaveStatus from '$lib/admin/SaveStatus.svelte';
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults'; import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte'; import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte'; import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
@ -107,7 +106,9 @@
</div> </div>
</div> </div>
<SaveStatus result={form} /> {#if form?.message}
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok} role="status">{form.message}</div>
{/if}
<div class="grid gap-4 rounded-box bg-base-100 p-5 shadow md:grid-cols-2"> <div class="grid gap-4 rounded-box bg-base-100 p-5 shadow md:grid-cols-2">
<label class="fieldset py-0"> <label class="fieldset py-0">

View file

@ -1,71 +0,0 @@
import { env } from '$env/dynamic/private';
import { fail } from '@sveltejs/kit';
import { zonedInputToIso } from '$lib/calendar';
import { hookError, issuePass, listPasses, updatePass } from '$lib/server/passes';
import type { Actions, PageServerLoad } from './$types';
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
export const load: PageServerLoad = async ({ locals, url }) => {
const q = url.searchParams.get('q')?.trim() ?? '';
const [passes, bundles] = await Promise.all([
listPasses(locals.pb, q).catch((e) => {
console.error('[passes] could not list codes', e);
return null;
}),
locals.pb
.collection('items')
.getFullList({ filter: "type = 'bundle'", sort: 'name', fields: 'id,name,validMonths,active' })
.catch(() => [])
]);
return {
q,
passes: passes ?? [],
passesError: passes === null,
bundles: bundles.map((b) => ({ id: b.id, name: String(b.name), validMonths: Number(b.validMonths) || null, active: b.active !== false }))
};
};
export const actions: Actions = {
/** Void or reactivate a code. */
status: async ({ request, locals }) => {
const data = await request.formData();
const status = String(data.get('status')) === 'void' ? 'void' : 'active';
try {
await updatePass(locals.pb, { id: String(data.get('id') || ''), status });
} catch (e) {
return fail(400, { message: hookError(e, 'Could not change the code.') });
}
return { ok: true };
},
/** Change when a code expires (empty date: never). */
expiry: async ({ request, locals }) => {
const data = await request.formData();
const date = data.get('never') ? '' : String(data.get('expiresAt') || '');
// The end of that day in the site's timezone.
const expiresAt = date ? zonedInputToIso(`${date}T23:59`, siteTimezone()) : '';
if (date && !expiresAt) return fail(400, { message: 'Invalid date.' });
try {
await updatePass(locals.pb, { id: String(data.get('id') || ''), expiresAt });
} catch (e) {
return fail(400, { message: hookError(e, 'Could not change the expiry date.') });
}
return { ok: true };
},
/** Issue a code without a purchase (a gift from the studio, a replacement). */
issue: async ({ request, locals }) => {
const data = await request.formData();
try {
const { pass } = await issuePass(locals.pb, {
itemId: String(data.get('itemId') || ''),
email: String(data.get('email') || ''),
recipientName: String(data.get('recipientName') || ''),
message: String(data.get('message') || ''),
months: String(data.get('months') ?? '')
});
return { issued: pass.code };
} catch (e) {
return fail(400, { message: hookError(e, 'Could not issue the code.') });
}
}
};

View file

@ -1,278 +0,0 @@
<script lang="ts">
import { enhance } from '$app/forms';
import type { SubmitFunction } from '@sveltejs/kit';
import type { PassPart } from '$lib/types';
import { formatDateTime, toZonedDatetimeInput } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
import { formatDuration } from '$shared/items';
let { data, form } = $props();
let passes = $derived(data.passes || []);
type Pass = (typeof passes)[number];
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
const dateOnly = (iso: string) => (iso ? toZonedDatetimeInput(iso, data.timezone).slice(0, 10) : '');
const expired = (pass: Pass) => !!pass.expiresAt && Date.parse(pass.expiresAt) <= Date.now();
const bookable = (pass: Pass) => pass.parts.filter((p) => p.redeemable);
const partLabel = (p: Pass['parts'][number]) => `${p.name}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`;
function passStatus(pass: Pass): { label: string; badge: string } {
if (pass.status === 'void') return { label: 'Void', badge: 'badge-ghost' };
if (expired(pass)) return { label: 'Expired', badge: 'badge-warning' };
if (bookable(pass).every((p) => p.left === 0 && p.held === 0)) return { label: 'Used up', badge: 'badge-info badge-soft' };
return { label: 'Active', badge: 'badge-success' };
}
// ── Manage one code ──
let managing = $state<Pass | null>(null);
let showManage = $state(false);
let manageError = $state('');
let expiryDraft = $state('');
function manage(pass: Pass) {
managing = pass;
expiryDraft = dateOnly(pass.expiresAt);
manageError = '';
showManage = true;
}
// Errors stay in the open modal; a success closes it and reloads the list.
const submitManage: SubmitFunction = () => {
manageError = '';
return async ({ result, update }) => {
if (result.type === 'failure') {
manageError = String(result.data?.message || 'Could not save.');
return;
}
showManage = false;
await update();
};
};
// ── Issue a code ──
let showIssue = $state(false);
let issueError = $state('');
let issueBundle = $state('');
let issueMonths = $state('');
let issued = $derived(form && 'issued' in form ? String(form.issued) : '');
function openIssue() {
issueError = '';
issueBundle = data.bundles[0]?.id ?? '';
issueMonths = String(data.bundles[0]?.validMonths ?? '');
showIssue = true;
}
const submitIssue: SubmitFunction = () => {
issueError = '';
return async ({ result, update }) => {
if (result.type === 'failure') {
issueError = String(result.data?.message || 'Could not issue the code.');
return;
}
showIssue = false;
await update();
};
};
</script>
<svelte:head><title>Vouchers & codes | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Vouchers & codes</h1>
<p class="max-w-3xl text-base-content/60">
A code is made for every bundle or voucher bought (set them up under Services & products). Whoever has the code enters it in the basket, and the sessions it includes are then already paid for. Places used and left are counted from bookings; a refunded booking gives its place back.
</p>
</div>
<button class="btn btn-primary" type="button" disabled={!data.bundles.length} onclick={openIssue}>Issue a code</button>
</div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
{#if issued}<div class="alert alert-success" role="status">Code <strong class="font-mono">{issued}</strong> issued — send it to whoever it’s for.</div>{/if}
{#if data.passesError}<div class="alert alert-error" role="alert">Could not load the codes — is the database reachable?</div>{/if}
{#if !data.bundles.length}<div class="alert" role="status">No bundles yet — add one under Services & products (type “Bundle / voucher”).</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow">
<form method="GET" class="mb-4 flex gap-2">
<input class="input min-w-0 flex-1 sm:w-80 sm:flex-none" type="search" name="q" placeholder="Code, email, name or bundle" aria-label="Search codes" value={data.q} />
<button class="btn" type="submit">Search</button>
{#if data.q}<a class="btn btn-ghost" href="/passes">Show all</a>{/if}
</form>
{#snippet buyer(pass: (typeof passes)[number])}
<span class="block">{pass.email || (pass.anonymisedAt ? 'Anonymised' : pass.order ? '—' : 'Issued here')}</span>
{#if pass.recipientName}<span class="block text-sm text-base-content/60">for {pass.recipientName}</span>{/if}
{/snippet}
{#snippet leftToBook(pass: (typeof passes)[number])}
{#each bookable(pass) as part (`${part.item}|${part.minutes}`)}
<span class="block">{part.left}/{part.count} {partLabel(part)}{part.held ? ` · ${part.held} in a basket` : ''}</span>
{/each}
{/snippet}
<!-- Phones and tablets: one card per code (seven columns didn't fit). -->
<ul class="-mx-5 divide-y divide-base-200 border-t border-base-200 lg:hidden">
{#each passes as pass (pass.id)}
{@const s = passStatus(pass)}
<li class="px-5 py-4">
<div class="flex items-start gap-3">
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<span class="font-mono font-semibold tracking-wider">{pass.code}</span>
<span class="badge {s.badge}">{s.label}</span>
</div>
<span class="mt-1 block font-medium break-words">{pass.name}</span>
<div class="mt-1 text-sm break-words">{@render buyer(pass)}</div>
<div class="mt-2 text-sm text-base-content/70">{@render leftToBook(pass)}</div>
<span class="mt-1 block text-sm text-base-content/60">Expires {pass.expiresAt ? dateOnly(pass.expiresAt) : 'never'}</span>
</div>
<button class="btn btn-sm shrink-0" type="button" onclick={() => manage(pass)}>Manage</button>
</div>
</li>
{:else}
<li class="py-10 text-center text-base-content/60">{data.q ? 'No codes match that search.' : 'No codes yet — they appear here when a bundle is bought.'}</li>
{/each}
</ul>
<div class="hidden overflow-x-auto lg:block">
<table class="table">
<thead><tr><th>Code</th><th>Bundle</th><th>Bought by / for</th><th>Left to book</th><th>Expires</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each passes as pass (pass.id)}
{@const s = passStatus(pass)}
<tr>
<td class="font-mono font-semibold tracking-wider whitespace-nowrap">{pass.code}</td>
<td>{pass.name}</td>
<td>{@render buyer(pass)}</td>
<td class="whitespace-nowrap">{@render leftToBook(pass)}</td>
<td class="whitespace-nowrap">{pass.expiresAt ? dateOnly(pass.expiresAt) : 'Never'}</td>
<td><span class="badge {s.badge}">{s.label}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => manage(pass)}>Manage</button></td>
</tr>
{:else}
<tr><td colspan="7" class="py-10 text-center text-base-content/60">{data.q ? 'No codes match that search.' : 'No codes yet — they appear here when a bundle is bought.'}</td></tr>
{/each}
</tbody>
</table>
</div>
{#if passes.length === 200}<p class="mt-2 text-sm text-base-content/60">Showing the newest 200 — search to find older codes.</p>{/if}
</div>
</div>
<Modal bind:open={showManage} title={managing ? `Code ${managing.code}` : 'Code'} wide>
{#if managing}
{#if manageError}<div class="alert alert-error mb-3 text-sm" role="alert">{manageError}</div>{/if}
<p class="font-semibold">{managing.name}{managing.recipientName ? ` · for ${managing.recipientName}` : ''}</p>
{#if managing.message}<p class="mt-1 text-sm italic text-base-content/70">“{managing.message}”</p>{/if}
<p class="mt-1 text-sm text-base-content/60">
{managing.created ? `Created ${formatDateTime(managing.created, data.timezone)}` : ''}{managing.order ? ` · order ${managing.order}` : ' · issued here'}
</p>
{#snippet share(part: PassPart)}{money.format(part.value)}{part.count > 1 ? ` (${money.format(part.value / part.count)} each)` : ''}{/snippet}
<!-- Phones: one row per part (five columns didn't fit). -->
<ul class="mt-3 divide-y divide-base-200 sm:hidden">
{#each managing.parts as part (`${part.item}|${part.minutes}`)}
<li class="flex items-start justify-between gap-3 py-2 text-sm">
<span class="min-w-0">
<span class="block font-medium">{part.count}× {partLabel(part)}</span>
<span class="block text-base-content/60">{part.redeemable ? `${part.left} left · ${part.used} used${part.held ? ` · ${part.held} in a basket` : ''}` : 'Handed over with the purchase'}</span>
</span>
<span class="shrink-0 text-right">{@render share(part)}</span>
</li>
{/each}
</ul>
<!-- Hidden through a wrapper: the table's own "table" class also sets display: table, which beats "hidden". -->
<div class="mt-3 hidden sm:block">
<table class="table table-sm">
<thead><tr><th>Part</th><th>Used</th><th>In a basket</th><th>Left</th><th class="text-right">Share of the price</th></tr></thead>
<tbody>
{#each managing.parts as part (`${part.item}|${part.minutes}`)}
<tr>
<td>{part.count}× {partLabel(part)}</td>
{#if part.redeemable}
<td>{part.used}</td><td>{part.held}</td><td>{part.left}</td>
{:else}
<td colspan="3" class="text-base-content/60">Handed over with the purchase</td>
{/if}
<td class="text-right">{@render share(part)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
<p class="mt-1 text-xs text-base-content/60">The share of the price is what each part is worth for a partial refund (refund in Stripe, then mark the booking’s order refunded to give its place back).</p>
<form method="POST" action="?/expiry" use:enhance={submitManage} class="mt-4 flex flex-wrap items-end gap-2">
<input type="hidden" name="id" value={managing.id} />
<label class="fieldset py-0">
<span class="fieldset-legend">Expires ({data.timezone})</span>
<input class="input w-48" type="date" name="expiresAt" bind:value={expiryDraft} />
</label>
<button class="btn" type="submit">Save expiry</button>
<button class="btn btn-ghost" type="submit" name="never" value="1">Never expires</button>
</form>
<div class="modal-action justify-between">
<form method="POST" action="?/status" use:enhance={submitManage}>
<input type="hidden" name="id" value={managing.id} />
{#if managing.status === 'void'}
<input type="hidden" name="status" value="active" />
<button class="btn btn-outline" type="submit">Reactivate</button>
{:else}
<input type="hidden" name="status" value="void" />
<button class="btn btn-error btn-outline" type="submit" onclick={confirmSubmit(`Void ${managing.code}? It can no longer be used (bookings already made stay).`)}>Void code</button>
{/if}
</form>
<button class="btn" type="button" onclick={() => (showManage = false)}>Close</button>
</div>
{/if}
</Modal>
<Modal bind:open={showIssue} title="Issue a code">
<form method="POST" action="?/issue" use:enhance={submitIssue} class="space-y-1">
{#if issueError}<div class="alert alert-error mb-2 text-sm" role="alert">{issueError}</div>{/if}
<p class="text-sm text-base-content/70">A code without a purchase — a gift from you, or a replacement. Nothing is charged.</p>
<label class="fieldset">
<span class="fieldset-legend">Bundle</span>
<select
class="select w-full"
name="itemId"
required
value={issueBundle}
onchange={(e) => {
issueBundle = e.currentTarget.value;
issueMonths = String(data.bundles.find((b) => b.id === issueBundle)?.validMonths ?? '');
}}
>
{#each data.bundles as bundle (bundle.id)}<option value={bundle.id}>{bundle.name}{bundle.active ? '' : ' (inactive)'}</option>{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Valid for (months)</span>
<input class="input w-32" type="number" min="0" max="120" step="1" name="months" bind:value={issueMonths} />
<span class="label">0 = no expiry.</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">For <span class="font-normal text-base-content/50">(optional)</span></span>
<input class="input w-full" name="recipientName" maxlength="180" />
</label>
<label class="fieldset">
<span class="fieldset-legend">Email <span class="font-normal text-base-content/50">(optional, to find it again)</span></span>
<input class="input w-full" type="email" name="email" maxlength="320" />
</label>
<label class="fieldset">
<span class="fieldset-legend">Note <span class="font-normal text-base-content/50">(optional)</span></span>
<input class="input w-full" name="message" maxlength="1000" />
</label>
<div class="modal-action">
<button class="btn" type="button" onclick={() => (showIssue = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Issue code</button>
</div>
</form>
</Modal>

View file

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

View file

@ -22,12 +22,12 @@
<svelte:head> <svelte:head>
<title>Preview</title> <title>Preview</title>
<!-- Full site colours and style so the draft looks like the public site. --> <!-- Full site colours so the draft looks like the public site. -->
{@html rootStyleTag(siteThemeVars(data.colors, data.style))} {@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head> </svelte:head>
{#if blocks.length} {#if blocks.length}
<BlockRenderer {blocks} items={data.items} calendarEvents={data.calendarEvents} /> <BlockRenderer {blocks} items={data.items} slots={data.slots} calendarEvents={data.calendarEvents} />
{:else} {:else}
<section class="mx-auto max-w-3xl px-6 py-20 text-center"> <section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1> <h1 class="text-4xl">No preview content</h1>

View file

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

View file

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

View file

@ -13,25 +13,12 @@
"@tailwindcss/vite": "^4.3.0", "@tailwindcss/vite": "^4.3.0",
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.28.2", "pocketbase": "^0.26.9",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
"@fontsource-variable/cormorant-garamond": "^5.3.0", "@fontsource/dm-sans": "^5.3.0",
"@fontsource-variable/dm-sans": "^5.3.0", "@fontsource/playfair-display": "^5.3.0",
"@fontsource-variable/eb-garamond": "^5.3.0",
"@fontsource-variable/fraunces": "^5.3.0",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/josefin-sans": "^5.3.0",
"@fontsource-variable/libre-baskerville": "^5.3.0",
"@fontsource-variable/lora": "^5.3.0",
"@fontsource-variable/manrope": "^5.3.0",
"@fontsource-variable/montserrat": "^5.3.0",
"@fontsource-variable/nunito": "^5.3.0",
"@fontsource-variable/outfit": "^5.3.0",
"@fontsource-variable/playfair-display": "^5.3.0",
"@fontsource-variable/raleway": "^5.3.0",
"@fontsource-variable/work-sans": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -42,150 +29,20 @@
"vite": "^8.0.7" "vite": "^8.0.7"
} }
}, },
"node_modules/@fontsource-variable/cormorant-garamond": { "node_modules/@fontsource/dm-sans": {
"version": "5.3.0", "version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/cormorant-garamond/-/cormorant-garamond-5.3.0.tgz", "resolved": "https://registry.npmjs.org/@fontsource/dm-sans/-/dm-sans-5.3.0.tgz",
"integrity": "sha512-rgZJ/5w3hi60swAPnrOXpZf5wEH6NTrvm4H8D9Y4b1QIFUqlX14eM3QTMU/eAznjfh0eXpO1QUqsFhiy58aoMg==", "integrity": "sha512-lYJtMXXO28q1z+yz+z8XKd0s4hXaa9QdkETzkyD760sidCv5heI86weYA0sx0Nc4pAMAQTUuyf4gO44cYKKS9g==",
"dev": true, "dev": true,
"license": "OFL-1.1", "license": "OFL-1.1",
"funding": { "funding": {
"url": "https://github.com/sponsors/ayuhito" "url": "https://github.com/sponsors/ayuhito"
} }
}, },
"node_modules/@fontsource-variable/dm-sans": { "node_modules/@fontsource/playfair-display": {
"version": "5.3.0", "version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/dm-sans/-/dm-sans-5.3.0.tgz", "resolved": "https://registry.npmjs.org/@fontsource/playfair-display/-/playfair-display-5.3.0.tgz",
"integrity": "sha512-BpUG5bqePiDFMBM4ZtLSlPdAIOM990uB1dlXzIf4aw21yQR7BmykedLXXXMqGWsR18aMLOsbWccwJNh3ztTQaA==", "integrity": "sha512-uJSABalvdWc10fEPppQjQocamT21LEyRfzzWfRfqbkPz+sRv+kKpYDKyluBUskvJREkJTos9epj1WjQROGu99Q==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/eb-garamond": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/eb-garamond/-/eb-garamond-5.3.0.tgz",
"integrity": "sha512-656OJsA9Vv24yhqRZFEzXnzS2AYgKdEILLgHJYLzzXndgcWFKfSXFqzbRI5/6Yk1Yt7UfWrUeppE5nRQPQMwlQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/fraunces": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/fraunces/-/fraunces-5.3.0.tgz",
"integrity": "sha512-9BYGySn4AHEJdgp9Z28tQ3X+laJMEOITXkQarZXeloWQZDq5oOvXJ3kDA8c7MGIfpogIaZfjrQBqmda8POOCKA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/josefin-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/josefin-sans/-/josefin-sans-5.3.0.tgz",
"integrity": "sha512-duVgkuzE/co4iuIfJ7jM2qX0ED3b6qdY+SlSjNMs6zfhz7EE7kJxV0qF65hQCv1kN0A20j4FwsGAYJvfpU+iSg==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/libre-baskerville": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/libre-baskerville/-/libre-baskerville-5.3.0.tgz",
"integrity": "sha512-lIjXwDhcdr0OxSdzlAU4G7Tnny1LhgAiPFdp3/PjwRMqYt2JLU6pQiLwz/M5lRBs/kRtHwxknPUqRt37AnqPFg==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/lora": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/lora/-/lora-5.3.0.tgz",
"integrity": "sha512-2ph8KiZ8Bn141hWuC3ErtpJ+Ui8p2MJQn8TJNRSRmLmnCIOCtHfiBM9R7WLRPeUG/q6hXyHOxWQ8DvRSX+ixvQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/manrope": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/manrope/-/manrope-5.3.0.tgz",
"integrity": "sha512-6D5dgokHsWDDMtmXHznKa0hK229NN+1a4BLPmUCLqcO1Pw5EEhWY5RFt0AcXnVRAljFFPfRtLkJePQj6LSsV6g==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/montserrat": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/montserrat/-/montserrat-5.3.0.tgz",
"integrity": "sha512-7PaZoxaxrWLAyrhO46v65An9LhUhfkTExWLhfbywYZCnZEgg/W1rEHnlNmZKjNZ3nJTVYyicqxlJt10z/26yTA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/nunito": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito/-/nunito-5.3.0.tgz",
"integrity": "sha512-tw0ch7evIDSwoeUy+0XzocYHfbRWLeCRPJy22KgbrLjDLAbNw/fErBiil10Ssrs3Sjr55zaZrr36a975j8cBkQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/outfit": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/outfit/-/outfit-5.3.0.tgz",
"integrity": "sha512-fPb5XnYK0k7SbR++HEmm4+ZqDszmLKQ+sPRUr8oQ/KNC0vy6r6hazJFe8iYozv4cqlHbvJ/JECkJWrfDodUMVQ==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/playfair-display": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/playfair-display/-/playfair-display-5.3.0.tgz",
"integrity": "sha512-IHdzTvE8eGIXHteZql7KXoqdc3Gfm+Zs1u4XlSC3MeplkwviT3sx/P6gI0tLwg/xIYLF4ZJYveZ5V+bl9cnDwA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/raleway": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/raleway/-/raleway-5.3.0.tgz",
"integrity": "sha512-aSV2k+V6Zz+od0dHpBOzkVxEzmgEdiXcxDfant39jLOx+T89dielQRrZylukwK3Fp+FY255gPqz67ruOfs1rqA==",
"dev": true,
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/work-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/work-sans/-/work-sans-5.3.0.tgz",
"integrity": "sha512-le8h/OIIuhm5Z7TdvuMw0yKg2gaCZUiMec8zaumsVVjzeJRBPEF0bQI/MkaZDHCVzZDvZoP/O2LiGOSfDLSbaw==",
"dev": true, "dev": true,
"license": "OFL-1.1", "license": "OFL-1.1",
"funding": { "funding": {
@ -1964,9 +1821,9 @@
} }
}, },
"node_modules/pocketbase": { "node_modules/pocketbase": {
"version": "0.28.2", "version": "0.26.9",
"resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.28.2.tgz", "resolved": "https://registry.npmjs.org/pocketbase/-/pocketbase-0.26.9.tgz",
"integrity": "sha512-5lS4g7iDZi90LxLai8kyUK4r5u1GkEAoZ3yuzTEFX97FyDQAoEmXWbTqf+pYA1hz5e/icBQu1MCUjM/9V8mitg==", "integrity": "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/postcss": { "node_modules/postcss": {

View file

@ -10,21 +10,8 @@
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}, },
"devDependencies": { "devDependencies": {
"@fontsource-variable/cormorant-garamond": "^5.3.0", "@fontsource/dm-sans": "^5.3.0",
"@fontsource-variable/dm-sans": "^5.3.0", "@fontsource/playfair-display": "^5.3.0",
"@fontsource-variable/eb-garamond": "^5.3.0",
"@fontsource-variable/fraunces": "^5.3.0",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/josefin-sans": "^5.3.0",
"@fontsource-variable/libre-baskerville": "^5.3.0",
"@fontsource-variable/lora": "^5.3.0",
"@fontsource-variable/manrope": "^5.3.0",
"@fontsource-variable/montserrat": "^5.3.0",
"@fontsource-variable/nunito": "^5.3.0",
"@fontsource-variable/outfit": "^5.3.0",
"@fontsource-variable/playfair-display": "^5.3.0",
"@fontsource-variable/raleway": "^5.3.0",
"@fontsource-variable/work-sans": "^5.3.0",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
@ -40,7 +27,7 @@
"@tailwindcss/vite": "^4.3.0", "@tailwindcss/vite": "^4.3.0",
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.28.2", "pocketbase": "^0.26.9",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
} }
} }

View file

@ -3,28 +3,9 @@
themes: light --default; themes: light --default;
} }
/* Site design → Style sets the --site-* variables (siteStyleVars in
$shared/theme) on the public site and the admin preview; without them
(the admin's own pages) every token below is its usual value. Corners,
shadows and widths are scaled here, so blocks just use rounded-xl,
shadow-sm, max-w-6xl… Buttons and chips use rounded-button (a pill when
Round); dots and avatars stay rounded-full. */
@theme { @theme {
--font-sans: var(--site-font-body, 'DM Sans Variable', ui-sans-serif, system-ui, sans-serif); --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
--font-serif: var(--site-font-heading, 'Playfair Display Variable', Georgia, serif); --font-serif: 'Playfair Display', Georgia, serif;
--radius-lg: calc(0.5rem * var(--site-corners, 1));
--radius-xl: calc(0.75rem * var(--site-corners, 1));
--radius-2xl: calc(1rem * var(--site-corners, 1));
--radius-card: calc(1.25rem * var(--site-corners, 1));
--radius-panel: calc(2rem * var(--site-corners, 1));
--radius-button: var(--site-button-radius, 9999px);
--shadow-sm: 0 1px 3px 0 rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 1px 2px -1px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 2px 4px -2px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 4px 6px -4px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--shadow-xl: 0 20px 25px -5px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1))), 0 8px 10px -6px rgb(0 0 0 / calc(0.1 * var(--site-shadow, 1)));
--container-3xl: calc(48rem * var(--site-width, 1));
--container-6xl: calc(72rem * var(--site-width, 1));
--container-7xl: calc(80rem * var(--site-width, 1));
--color-warm: var(--color-bg, #faf8f5); --color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c); --color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b); --color-sage: var(--color-primary, #8a9a7b);
@ -63,9 +44,7 @@
--fg-body: var(--color-text, #2c2c2c); --fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5); background: var(--color-bg, #faf8f5);
color: var(--fg-body); color: var(--fg-body);
font-family: var(--font-sans); font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
/* Site design → Style → Text size; rem-sized spacing grows with it. */
font-size: var(--site-text-size, 100%);
} }
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ /* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
@ -95,7 +74,7 @@ h1,
h2, h2,
h3, h3,
h4 { h4 {
font-family: var(--font-serif); font-family: 'Playfair Display', Georgia, serif;
color: var(--fg-heading, #2c2c2c); color: var(--fg-heading, #2c2c2c);
} }
@ -120,36 +99,6 @@ h4 {
padding-left: 1.5rem; padding-left: 1.5rem;
} }
/* The visual editor wraps list items in <p>. */
.prose-wellness li > p {
margin: 0;
}
.prose-wellness ol {
list-style: decimal;
padding-left: 1.5rem;
}
/* Pull quote: a "Quote" in the visual editor. */
.prose-wellness blockquote {
margin: 0.75rem 0;
padding-left: 1.25rem;
border-left: 3px solid var(--color-primary, #8a9a7b);
font-family: var(--font-serif);
font-size: 1.35rem;
font-style: italic;
}
.prose-wellness.text-center blockquote {
border-left: 0;
padding-left: 0;
}
.prose-wellness hr {
margin: 2rem 0;
border-color: color-mix(in srgb, currentColor 20%, transparent);
}
.prose-wellness a { .prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline; text-decoration: underline;
@ -157,13 +106,12 @@ h4 {
} }
/* ── Scroll-reveal animations ── */ /* ── Scroll-reveal animations ── */
/* Kept short: blocks fading in while someone scrolls are what slows scrolling down. */
.reveal { .reveal {
opacity: 0; opacity: 0;
transform: translateY(16px); transform: translateY(30px);
transition: transition:
opacity 0.4s cubic-bezier(0.25, 0.1, 0.25, 1), opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 0.4s cubic-bezier(0.25, 0.1, 0.25, 1); transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
} }
.reveal-visible { .reveal-visible {
@ -174,8 +122,8 @@ h4 {
/* ── Hero fade-in stagger ── */ /* ── Hero fade-in stagger ── */
.animate-fade-in { .animate-fade-in {
opacity: 0; opacity: 0;
transform: translateY(12px); transform: translateY(20px);
animation: fadeInUp 0.5s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
} }
@keyframes fadeInUp { @keyframes fadeInUp {
@ -189,27 +137,3 @@ h4 {
html { html {
scroll-behavior: smooth; scroll-behavior: smooth;
} }
/* No animations on devices that can't keep up (scrollReveal.ts adds .plain-motion
to <html>) or for people whose device asks for less motion. */
html.plain-motion .reveal,
html.plain-motion .animate-fade-in {
opacity: 1;
transform: none;
transition: none;
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.reveal,
.animate-fade-in {
opacity: 1;
transform: none;
transition: none;
animation: none;
}
html {
scroll-behavior: auto;
}
}

View file

@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import { afterNavigate } from '$app/navigation'; import { afterNavigate } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import { shopLinks, type HeaderGlobal } from '$lib/types'; import type { HeaderGlobal } from '$lib/types';
import { getBasketContext } from '$lib/basket.svelte'; import { getBasketContext } from '$lib/basket.svelte';
import { DEFAULT_CURRENCY, formatPrice } from '$shared/calendar'; import { DEFAULT_CURRENCY, formatPrice } from '$shared/calendar';
@ -9,7 +9,6 @@
const basket = getBasketContext(); const basket = getBasketContext();
let hasItems = $derived(basket.count > 0); let hasItems = $derived(basket.count > 0);
let links = $derived(shopLinks(header));
// Phone menu: a native modal <dialog> sliding in from the right, so focus // Phone menu: a native modal <dialog> sliding in from the right, so focus
// trapping, Escape and the inert page behind come from the browser. // trapping, Escape and the inert page behind come from the browser.
@ -40,7 +39,7 @@
</svg> </svg>
{/snippet} {/snippet}
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/95"> <header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur">
<div class="mx-auto flex max-w-6xl items-center justify-between gap-3 px-4 py-3 sm:px-6 md:gap-4 md:py-4"> <div class="mx-auto flex max-w-6xl items-center justify-between gap-3 px-4 py-3 sm:px-6 md:gap-4 md:py-4">
<a class="flex min-w-0 items-center gap-3" href="/" aria-label="Home"> <a class="flex min-w-0 items-center gap-3" href="/" aria-label="Home">
{#if header.logo?.url} {#if header.logo?.url}
@ -64,8 +63,8 @@
<div class="flex shrink-0 items-center gap-2 md:gap-3"> <div class="flex shrink-0 items-center gap-2 md:gap-3">
{#if hasItems} {#if hasItems}
<a <a
class="relative flex items-center gap-2 rounded-button border border-charcoal/10 px-3 py-2 text-sm font-semibold text-charcoal/80 transition hover:border-sage hover:text-sage-dark md:px-4" class="relative flex items-center gap-2 rounded-full border border-charcoal/10 px-3 py-2 text-sm font-semibold text-charcoal/80 transition hover:border-sage hover:text-sage-dark md:px-4"
href={links.basket} href="/book"
aria-label="View your basket ({basket.count})" aria-label="View your basket ({basket.count})"
> >
{@render basketIcon()} {@render basketIcon()}
@ -74,10 +73,10 @@
</a> </a>
{/if} {/if}
{#if header.ctaButton?.label} {#if header.ctaButton?.label}
<a class="cta btn hidden rounded-button border-0 px-6 hover:opacity-90 md:inline-flex" href={links.booking}>{header.ctaButton.label}</a> <a class="cta btn hidden rounded-full border-0 px-6 hover:opacity-90 md:inline-flex" href={header.ctaButton.href}>{header.ctaButton.label}</a>
{/if} {/if}
<button <button
class="grid h-10 w-10 place-items-center rounded-button text-charcoal/80 transition hover:bg-charcoal/5 md:hidden" class="grid h-10 w-10 place-items-center rounded-full text-charcoal/80 transition hover:bg-charcoal/5 md:hidden"
type="button" type="button"
aria-label="Open menu" aria-label="Open menu"
aria-haspopup="dialog" aria-haspopup="dialog"
@ -98,7 +97,7 @@
<div class="flex h-full flex-col"> <div class="flex h-full flex-col">
<div class="flex items-center justify-between border-b border-charcoal/10 px-6 py-4"> <div class="flex items-center justify-between border-b border-charcoal/10 px-6 py-4">
<span class="font-serif text-xl font-bold text-charcoal">Menu</span> <span class="font-serif text-xl font-bold text-charcoal">Menu</span>
<button class="grid h-10 w-10 place-items-center rounded-button text-charcoal/80 transition hover:bg-charcoal/5" type="button" aria-label="Close menu" onclick={closeMenu}> <button class="grid h-10 w-10 place-items-center rounded-full text-charcoal/80 transition hover:bg-charcoal/5" type="button" aria-label="Close menu" onclick={closeMenu}>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true"> <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8" aria-hidden="true">
<path stroke-linecap="round" d="M6 6l12 12M18 6L6 18" /> <path stroke-linecap="round" d="M6 6l12 12M18 6L6 18" />
</svg> </svg>
@ -119,7 +118,7 @@
</ul> </ul>
{#if hasItems} {#if hasItems}
<a class="mx-1 mt-6 flex items-center gap-3 rounded-xl border border-charcoal/10 px-4 py-3 font-semibold text-charcoal/80 transition hover:border-sage" href={links.basket}> <a class="mx-1 mt-6 flex items-center gap-3 rounded-xl border border-charcoal/10 px-4 py-3 font-semibold text-charcoal/80 transition hover:border-sage" href="/book">
{@render basketIcon()} {@render basketIcon()}
<span class="flex-1">Basket ({basket.count})</span> <span class="flex-1">Basket ({basket.count})</span>
<span class="text-charcoal/60">{formatTotal(basket.total)}</span> <span class="text-charcoal/60">{formatTotal(basket.total)}</span>
@ -129,7 +128,7 @@
{#if header.ctaButton?.label} {#if header.ctaButton?.label}
<div class="border-t border-charcoal/10 p-6"> <div class="border-t border-charcoal/10 p-6">
<a class="cta btn btn-block rounded-button border-0 hover:opacity-90" href={links.booking}>{header.ctaButton.label}</a> <a class="cta btn btn-block rounded-full border-0 hover:opacity-90" href={header.ctaButton.href}>{header.ctaButton.label}</a>
</div> </div>
{/if} {/if}
</div> </div>

View file

@ -1,19 +0,0 @@
// The fonts Site design → Style offers (SITE_FONTS in $shared/theme), bundled
// and served by this app, not loaded from Google: a Google Fonts request sends
// every visitor's IP address to Google (GDPR). Each import only declares the
// font; a browser downloads the files of the fonts a page actually uses.
import '@fontsource-variable/playfair-display';
import '@fontsource-variable/cormorant-garamond';
import '@fontsource-variable/eb-garamond';
import '@fontsource-variable/libre-baskerville';
import '@fontsource-variable/lora';
import '@fontsource-variable/fraunces';
import '@fontsource-variable/dm-sans';
import '@fontsource-variable/inter';
import '@fontsource-variable/manrope';
import '@fontsource-variable/montserrat';
import '@fontsource-variable/nunito';
import '@fontsource-variable/outfit';
import '@fontsource-variable/raleway';
import '@fontsource-variable/work-sans';
import '@fontsource-variable/josefin-sans';

View file

@ -1,7 +1,7 @@
import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit'; import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit';
import { env } from '$env/dynamic/private'; import { env } from '$env/dynamic/private';
import { getFileUrl } from '$lib/pb'; import { getFileUrl } from '$lib/pb';
import type { Basket, BasketLine, OrderRecord, PassSummary } from '$lib/types'; import type { Basket, BasketLine, OrderRecord } from '$lib/types';
import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email'; import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email';
// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All // Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All
@ -51,15 +51,12 @@ export function postJson<T>(path: string, data: unknown): Promise<T> {
}); });
} }
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[]; pass?: PassSummary | null } | null; type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null;
/** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */ /** Map the API's raw basket records to the `Basket` type used by the UI. */
const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString();
/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */
export function mapBasket(payload: BasketPayload): Basket | null { export function mapBasket(payload: BasketPayload): Basket | null {
if (!payload) return null; if (!payload) return null;
const { record, lines, pass } = payload; const { record, lines } = payload;
const mappedLines: BasketLine[] = lines.map((line) => { const mappedLines: BasketLine[] = lines.map((line) => {
const item = line.expand?.item; const item = line.expand?.item;
const slot = line.expand?.slot; const slot = line.expand?.slot;
@ -71,19 +68,13 @@ export function mapBasket(payload: BasketPayload): Basket | null {
slot: line.slot || null, slot: line.slot || null,
quantity: line.quantity, quantity: line.quantity,
lineType: line.lineType, lineType: line.lineType,
start: line.start ? pbInstant(line.start) : undefined,
end: line.end || undefined,
minutes: line.minutes || undefined,
itemName: item?.name, itemName: item?.name,
itemPrice: line.unitPrice ?? null, itemPrice: item?.price,
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
slotKind: slot?.kind, slotStart: slot?.start,
slotEnd: slot?.end,
slotCapacity: slot?.capacity, slotCapacity: slot?.capacity,
passCovered: !!line.pass, heldUntil: line.heldUntil ? new Date(String(line.heldUntil).replace(' ', 'T')).toISOString() : undefined
giftTo: line.giftTo || '',
giftMessage: line.giftMessage || '',
bundle: line.bundle || undefined,
heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined
}; };
}); });
return { return {
@ -94,7 +85,6 @@ export function mapBasket(payload: BasketPayload): Basket | null {
customerDetails: record.customerDetails || null, customerDetails: record.customerDetails || null,
stripePaymentIntentId: record.stripePaymentIntentId || null, stripePaymentIntentId: record.stripePaymentIntentId || null,
lines: mappedLines, lines: mappedLines,
pass: pass ?? null,
serverNow: Date.now() serverNow: Date.now()
}; };
} }
@ -107,7 +97,7 @@ export async function getBasket(basketId: string | undefined): Promise<Basket |
return mapBasket(basket); return mapBasket(basket);
} }
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[], passes: PassSummary[] = []): OrderRecord { export function mapOrder(order: Record<string, any>, lines: Record<string, any>[]): OrderRecord {
return { return {
id: order.id, id: order.id,
basket: order.basket, basket: order.basket,
@ -126,11 +116,8 @@ export function mapOrder(order: Record<string, any>, lines: Record<string, any>[
lineType: l.lineType, lineType: l.lineType,
name: l.name, name: l.name,
price: l.price, price: l.price,
start: l.start || null, start: l.start || null
minutes: l.minutes || null, }))
passCode: l.passCode || ''
})),
passes
}; };
} }

View file

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

View file

@ -1,18 +1,21 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
import '$lib/fonts'; // Fonts are bundled and served by this app, not loaded from Google: a
// Google Fonts request sends every visitor's IP address to Google (GDPR).
import '@fontsource/dm-sans/400.css';
import '@fontsource/dm-sans/500.css';
import '@fontsource/dm-sans/600.css';
import '@fontsource/dm-sans/700.css';
import '@fontsource/playfair-display/600.css';
import '@fontsource/playfair-display/700.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte'; import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte'; import Footer from '$lib/components/Footer.svelte';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { rootStyleTag, siteThemeVars } from '$shared/theme'; import { rootStyleTag, siteThemeVars } from '$shared/theme';
import { thumbUrl } from '$shared/pb';
let { children, data } = $props(); let { children, data } = $props();
// The logo from Site design is the tab icon (a 300×300 thumbnail, not the full upload).
let icon = $derived(data.header?.logo?.url ? thumbUrl(data.header.logo.url) : favicon);
// One basket store per public layout instance — provided to all children // One basket store per public layout instance — provided to all children
// (Header indicator, ShopBlock, CheckoutBlock). Never module-level state. // (Header indicator, ShopBlock, CheckoutBlock). Never module-level state.
const basketStore = createBasketStore(data.basket ?? null); const basketStore = createBasketStore(data.basket ?? null);
@ -24,13 +27,11 @@
</script> </script>
<svelte:head> <svelte:head>
<link rel="icon" href={icon} /> <link rel="icon" href={favicon} />
<!-- Home-screen icon on phones; iOS ignores SVG, so only for an uploaded logo. -->
{#if icon !== favicon}<link rel="apple-touch-icon" href={icon} />{/if}
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Site colours and style, rendered server-side (previously applied in onMount, which <!-- Site colours, rendered server-side (previously applied in onMount, which
flashed the defaults on every page load). Values are sanitised. --> flashed the defaults on every page load). Values are sanitised. -->
{@html rootStyleTag(siteThemeVars(data.colors, data.style))} {@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head> </svelte:head>
<Header header={data.header} /> <Header header={data.header} />

View file

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

View file

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

View file

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

View file

@ -1,15 +1,9 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { BASKET_COOKIE, jsonErrors, postJson, sendAndRecordOrderEmails } from '$lib/server/shop'; import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
import type { OrderEmailData } from '$lib/server/email';
type CheckoutResult = { clientSecret: string } | { free: true; orderId: string; orderEmail: OrderEmailData };
// Starts payment: PocketBase re-validates the basket, extends slot holds and // Starts payment: PocketBase re-validates the basket, extends slot holds and
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). When codes // creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop).
// cover the whole basket there is nothing to pay: PocketBase creates the
// order straight away, and the booking emails are sent from here (as the
// Stripe webhook route does after a payment).
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
let body: Record<string, unknown>; let body: Record<string, unknown>;
try { try {
@ -18,16 +12,12 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body'); throw error(400, 'Invalid JSON body');
} }
const result = await postJson<CheckoutResult>('/checkout', { const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
basketId: cookies.get(BASKET_COOKIE) || '', basketId: cookies.get(BASKET_COOKIE) || '',
name: body.name, name: body.name,
email: body.email, email: body.email,
phone: body.phone, phone: body.phone,
notes: body.notes notes: body.notes
}); });
if ('free' in result) { return json({ clientSecret });
void sendAndRecordOrderEmails(result.orderEmail);
return json({ free: true, orderId: result.orderId });
}
return json({ clientSecret: result.clientSecret });
}); });

View file

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

View file

@ -1,27 +1,19 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop'; import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
import type { PassSummary } from '$lib/types';
type OrderStatus = type OrderStatus =
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' } | { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[]; passes: PassSummary[] }; | { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
export const load: PageServerLoad = async ({ url, cookies }) => { export const load: PageServerLoad = async ({ url, cookies }) => {
// After a Stripe payment: ?payment_intent=… (checked with Stripe by
// PocketBase; the webhook may not have created the order yet). An order
// paid entirely with codes: ?order=…, which PocketBase only shows to the
// basket it came from (this visitor's cookie).
const intentId = url.searchParams.get('payment_intent'); const intentId = url.searchParams.get('payment_intent');
const orderId = url.searchParams.get('order'); if (!intentId) return { state: 'missing' as const };
let query: string;
if (intentId) query = `payment_intent=${encodeURIComponent(intentId)}`;
else if (orderId) query = `order=${encodeURIComponent(orderId)}&basket=${encodeURIComponent(cookies.get(BASKET_COOKIE) || '')}`;
else return { state: 'missing' as const };
const status = await shopFetch<OrderStatus>(`/order?${query}`); // PocketBase checks the intent with Stripe and looks up the order (the
// webhook is the source of truth and may not have landed yet).
const status = await shopFetch<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`);
if (status.state !== 'paid') return { state: status.state }; if (status.state !== 'paid') return { state: status.state };
// Keep the cookie for a code-paid order: it is what lets this page show it on reload. cookies.delete(BASKET_COOKIE, { path: '/' });
if (intentId) cookies.delete(BASKET_COOKIE, { path: '/' }); return { state: 'paid' as const, order: mapOrder(status.order, status.lines) };
return { state: 'paid' as const, order: mapOrder(status.order, status.lines, status.passes) };
}; };

View file

@ -1,11 +1,8 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { formatInstant, formatPrice } from '$shared/calendar'; import { formatInstant, formatPrice } from '$shared/calendar';
import { formatDuration } from '$shared/items';
import { shopLinks } from '$lib/types';
let { data } = $props(); let { data } = $props();
let links = $derived(shopLinks(data.header));
// "Friday 15 January, 10:00" in the studio's timezone. // "Friday 15 January, 10:00" in the studio's timezone.
function formatSlotDate(iso?: string | null) { function formatSlotDate(iso?: string | null) {
@ -25,7 +22,7 @@
Your booking is confirmed. A receipt was sent to <strong>{data.order.email}</strong>. Your booking is confirmed. A receipt was sent to <strong>{data.order.email}</strong>.
</p> </p>
<div class="mt-8 rounded-2xl border border-charcoal/10 bg-white/60 p-6 text-left"> <div class="mt-8 rounded-box border border-charcoal/10 bg-white/60 p-6 text-left">
<h2 class="font-serif text-xl">Your order</h2> <h2 class="font-serif text-xl">Your order</h2>
<ul class="mt-4 space-y-3"> <ul class="mt-4 space-y-3">
{#each data.order.lines ?? [] as line} {#each data.order.lines ?? [] as line}
@ -35,9 +32,6 @@
{#if line.start} {#if line.start}
<div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div> <div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div>
{/if} {/if}
{#if line.passCode}
<div class="text-sm text-charcoal/60">Paid with code {line.passCode}</div>
{/if}
</div> </div>
<span>{formatPrice(line.price * line.quantity, data.currency)}</span> <span>{formatPrice(line.price * line.quantity, data.currency)}</span>
</li> </li>
@ -48,29 +42,7 @@
</div> </div>
</div> </div>
{#if data.order.passes?.length} <a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Book another</a>
<!-- Bundles bought: their codes (also in the confirmation email). -->
<div class="mt-6 rounded-2xl border border-sage/40 bg-sage/10 p-6 text-left">
<h2 class="font-serif text-xl">Your {data.order.passes.length === 1 ? 'code' : 'codes'}</h2>
<p class="mt-1 text-sm text-charcoal/70">Enter a code in the basket when you book — the sessions it includes are then already paid for.</p>
{#each data.order.passes as pass (pass.id)}
<div class="mt-4 rounded-xl bg-white p-4">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<span class="font-mono text-2xl font-semibold tracking-widest">{pass.code}</span>
<span class="text-sm text-charcoal/60">{pass.expiresAt ? `Valid until ${formatInstant(pass.expiresAt, data.timezone, { day: 'numeric', month: 'long', year: 'numeric' })}` : 'No expiry'}</span>
</div>
<p class="mt-1 font-semibold">{pass.name}{pass.recipientName ? ` · for ${pass.recipientName}` : ''}</p>
<ul class="mt-1 text-sm text-charcoal/70">
{#each pass.parts as part (`${part.item}|${part.minutes}`)}
<li>{part.count}× {part.name}{part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with your order'}</li>
{/each}
</ul>
</div>
{/each}
</div>
{/if}
<a class="btn mt-8 rounded-button border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href={links.booking}>Book another</a>
{:else if data.state === 'processing'} {:else if data.state === 'processing'}
<h1 class="font-serif text-4xl">Processing your payment…</h1> <h1 class="font-serif text-4xl">Processing your payment…</h1>
<p class="mt-3 text-charcoal/70"> <p class="mt-3 text-charcoal/70">
@ -82,10 +54,10 @@
{:else if data.state === 'canceled' || data.state === 'failed'} {:else if data.state === 'canceled' || data.state === 'failed'}
<h1 class="font-serif text-4xl">Payment not completed</h1> <h1 class="font-serif text-4xl">Payment not completed</h1>
<p class="mt-3 text-charcoal/70">Your payment didn't go through — no money was captured. Please try again.</p> <p class="mt-3 text-charcoal/70">Your payment didn't go through — no money was captured. Please try again.</p>
<a class="btn mt-8 rounded-button border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href={links.basket}>Back to your basket</a> <a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a>
{:else} {:else}
<h1 class="font-serif text-4xl">Nothing to see here</h1> <h1 class="font-serif text-4xl">Nothing to see here</h1>
<p class="mt-3 text-charcoal/70">This link is missing a payment reference.</p> <p class="mt-3 text-charcoal/70">This link is missing a payment reference.</p>
<a class="btn mt-8 rounded-button border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href={links.booking}>Back to the shop</a> <a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a>
{/if} {/if}
</section> </section>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View file

@ -50,13 +50,6 @@ Same text and photos, plus:
and an FAQ. The FAQ answers come only from what the site already says and an FAQ. The FAQ answers come only from what the site already says
(boundaries, no intercourse, the first session is a talk, prices). Each (boundaries, no intercourse, the first session is a talk, prices). Each
article ends with a booking prompt and "Read next". article ends with a booking prompt and "Read next".
- **No HTML in text**: the cards, steps, "Read next" and programme prices are
Cards blocks, the FAQs are FAQ blocks, pull quotes are quotes and article
references are small (footnote) text, so everything is editable in the
visual editor. `#prices`, `#buy` and `#book` are block anchors.
Older export files (with HTML layouts inside text blocks) still import: those
text blocks become HTML blocks that look the same.
Both versions fix obvious typos ("Complete Cirсle" with a Cyrillic с, "Cirle", Both versions fix obvious typos ("Complete Cirсle" with a Cyrillic с, "Cirle",
"advansed") and the broken "More about sessions" link (`http://`), which now "advansed") and the broken "More about sessions" link (`http://`), which now
goes to `/sessions`. goes to `/sessions`.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 301 KiB

View file

@ -3,17 +3,12 @@ services:
# Pinned: schema (pb_schema.json) and migrations target this version's # Pinned: schema (pb_schema.json) and migrations target this version's
# format/JS API. Upgrade deliberately — read the PocketBase changelog, # format/JS API. Upgrade deliberately — read the PocketBase changelog,
# back up pb_data, then bump the tag and test migrations locally. # back up pb_data, then bump the tag and test migrations locally.
# Digest-pinned too, so a re-pushed tag can't change what runs. image: docker.io/spectado/pocketbase:0.23.12
# This image runs as a non-root `pocketbase` user (uid 100) on port 8090
# and finds /pb_migrations and /pb_hooks next to /pb_data by default.
# Data written by the old root-run image (spectado/pocketbase, now gone)
# must be chown'ed once — see the README's "Switching PocketBase image".
image: docker.io/elestio/pocketbase:v0.40.6@sha256:936756ccefb13cedaf2e7c49745412455bc81f2d1a511132f4012e411b970437
container_name: massage-pocketbase container_name: massage-pocketbase
restart: unless-stopped restart: unless-stopped
# Internal only — accessed via the caddy reverse proxy # Internal only — accessed via the caddy reverse proxy
expose: expose:
- "8090" - "80"
volumes: volumes:
- pocketbase:/pb_data - pocketbase:/pb_data
# Versioned schema changes; PocketBase applies pending ones on start. # Versioned schema changes; PocketBase applies pending ones on start.
@ -38,7 +33,7 @@ services:
- pocketbase - pocketbase
environment: environment:
PORT: 3001 PORT: 3001
POCKETBASE_INTERNAL_URL: http://pocketbase:8090 POCKETBASE_INTERNAL_URL: http://pocketbase:80
# Browser-facing URLs. They must match the address bar exactly, or # Browser-facing URLs. They must match the address bar exactly, or
# SvelteKit rejects logins/forms ("Cross-site POST form submissions are # SvelteKit rejects logins/forms ("Cross-site POST form submissions are
# forbidden"). Behind a TLS proxy: URL_SCHEME=https and URL_PORT= (empty). # forbidden"). Behind a TLS proxy: URL_SCHEME=https and URL_PORT= (empty).
@ -69,7 +64,7 @@ services:
- pocketbase - pocketbase
environment: environment:
PORT: 3000 PORT: 3000
POCKETBASE_INTERNAL_URL: http://pocketbase:8090 POCKETBASE_INTERNAL_URL: http://pocketbase:80
PUBLIC_POCKETBASE_URL: ${URL_SCHEME:-http}://db.${DOMAIN:-localhost}${URL_PORT-:8080} PUBLIC_POCKETBASE_URL: ${URL_SCHEME:-http}://db.${DOMAIN:-localhost}${URL_PORT-:8080}
ORIGIN: ${URL_SCHEME:-http}://www.${DOMAIN:-localhost}${URL_PORT-:8080} ORIGIN: ${URL_SCHEME:-http}://www.${DOMAIN:-localhost}${URL_PORT-:8080}
# No PocketBase or Stripe secrets here: shop writes happen in PocketBase # No PocketBase or Stripe secrets here: shop writes happen in PocketBase

View file

@ -19,7 +19,7 @@
"dependencies": { "dependencies": {
"@stripe/stripe-js": "^9.12.1", "@stripe/stripe-js": "^9.12.1",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.28.2" "pocketbase": "^0.26.9"
}, },
"devDependencies": { "devDependencies": {
"@types/nodemailer": "^8.0.2" "@types/nodemailer": "^8.0.2"

View file

@ -9,7 +9,6 @@ export type BasketStore = ReturnType<typeof createBasketStore>;
export function createBasketStore(initial: Basket | null) { export function createBasketStore(initial: Basket | null) {
let lines = $state<BasketLine[]>(initial?.lines ?? []); let lines = $state<BasketLine[]>(initial?.lines ?? []);
let status = $state<Basket['status']>(initial?.status ?? 'active'); let status = $state<Basket['status']>(initial?.status ?? 'active');
let pass = $state<Basket['pass']>(initial?.pass ?? null);
// Browser clock minus server clock, so hold countdowns survive a wrong clock. // Browser clock minus server clock, so hold countdowns survive a wrong clock.
let clockOffset = $state(clockOffsetOf(initial)); let clockOffset = $state(clockOffsetOf(initial));
@ -41,7 +40,6 @@ export function createBasketStore(initial: Basket | null) {
function applyBasket(basket: Basket | null) { function applyBasket(basket: Basket | null) {
lines = basket?.lines ?? []; lines = basket?.lines ?? [];
status = basket?.status ?? 'active'; status = basket?.status ?? 'active';
pass = basket?.pass ?? null;
clockOffset = clockOffsetOf(basket); clockOffset = clockOffsetOf(basket);
} }
@ -74,12 +72,8 @@ export function createBasketStore(initial: Basket | null) {
applyBasket(await callApi({ action: 'add_item', itemId, quantity })); applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
} }
/** async function addSlotLine(slotId: string) {
* Book a time: in a window, `slotId` plus the service, length and start await applySlotChange(await callApi({ action: 'add_slot', slotId }));
* picked; for a group session, `slotId` alone (one place).
*/
async function addSlotLine(slotId: string, booking: { itemId: string; minutes: number; start: string } | null = null) {
await applySlotChange(await callApi({ action: 'add_slot', slotId, ...booking }));
} }
async function updateQuantity(lineId: string, quantity: number) { async function updateQuantity(lineId: string, quantity: number) {
@ -95,20 +89,6 @@ export function createBasketStore(initial: Basket | null) {
await applySlotChange(await callApi({ action: 'renew_holds' })); await applySlotChange(await callApi({ action: 'renew_holds' }));
} }
/** Apply a bundle/voucher code: the bookings it covers cost nothing. */
async function applyCode(code: string) {
applyBasket(await callApi({ action: 'apply_code', code }));
}
async function removeCode() {
applyBasket(await callApi({ action: 'remove_code' }));
}
/** Who a bundle in the basket is for (empty: not a gift). */
async function setGift(lineId: string, giftTo: string, giftMessage: string) {
applyBasket(await callApi({ action: 'set_gift', lineId, giftTo, giftMessage }));
}
return { return {
get lines() { get lines() {
return lines; return lines;
@ -125,19 +105,13 @@ export function createBasketStore(initial: Basket | null) {
get holdDeadline() { get holdDeadline() {
return holdDeadline; return holdDeadline;
}, },
get pass() {
return pass;
},
refresh, refresh,
syncFrom, syncFrom,
addItemLine, addItemLine,
addSlotLine, addSlotLine,
updateQuantity, updateQuantity,
removeLine, removeLine,
renewHolds, renewHolds
applyCode,
removeCode,
setGift
}; };
} }

View file

@ -4,13 +4,10 @@
let { let {
background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground, background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground,
foreground = {} as BlockForeground, foreground = {} as BlockForeground,
anchor = '',
children children
} = $props<{ } = $props<{
background?: BlockBackground; background?: BlockBackground;
foreground?: BlockForeground; foreground?: BlockForeground;
/** Block setting: lets links like "#prices" jump here. */
anchor?: string;
children?: import('svelte').Snippet; children?: import('svelte').Snippet;
}>(); }>();
@ -44,8 +41,7 @@
} }
</script> </script>
<!-- scroll-mt keeps an #anchor target clear of the sticky header. --> <div style={bgStyle() + ' ' + fgStyle()} class="relative">
<div id={anchor || undefined} style={bgStyle() + ' ' + fgStyle()} class="relative scroll-mt-20">
{#if background.type === 'image' && background.overlay && background.imageUrl} {#if background.type === 'image' && background.overlay && background.imageUrl}
<div <div
class="pointer-events-none absolute inset-0" class="pointer-events-none absolute inset-0"

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord } from '$shared/types'; import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord, SlotRecord } from '$shared/types';
import BackgroundWrapper from './BackgroundWrapper.svelte'; import BackgroundWrapper from './BackgroundWrapper.svelte';
import TextBlock from './TextBlock.svelte'; import TextBlock from './TextBlock.svelte';
import ImageTextBlock from './ImageTextBlock.svelte'; import ImageTextBlock from './ImageTextBlock.svelte';
@ -11,14 +11,12 @@
import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte'; import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte';
import ShopBlock from './ShopBlock.svelte'; import ShopBlock from './ShopBlock.svelte';
import CheckoutBlock from './CheckoutBlock.svelte'; import CheckoutBlock from './CheckoutBlock.svelte';
import CardsBlock from './CardsBlock.svelte';
import FaqBlock from './FaqBlock.svelte';
import HtmlBlock from './HtmlBlock.svelte';
let { blocks = [], calendarEvents = [], items = [] } = $props<{ let { blocks = [], calendarEvents = [], items = [], slots = [] } = $props<{
blocks: ContentBlock[]; blocks: ContentBlock[];
calendarEvents?: CalendarEventRecord[]; calendarEvents?: CalendarEventRecord[];
items?: ItemRecord[]; items?: ItemRecord[];
slots?: SlotRecord[];
}>(); }>();
function getBg(block: ContentBlock): BlockBackground { function getBg(block: ContentBlock): BlockBackground {
@ -31,7 +29,7 @@
</script> </script>
{#each blocks as block (block.id)} {#each blocks as block (block.id)}
<BackgroundWrapper background={getBg(block)} foreground={getFg(block)} anchor={block.data._anchor}> <BackgroundWrapper background={getBg(block)} foreground={getFg(block)}>
{#if block.type === 'text'} {#if block.type === 'text'}
<TextBlock data={block.data} /> <TextBlock data={block.data} />
{:else if block.type === 'image_text'} {:else if block.type === 'image_text'}
@ -49,15 +47,9 @@
{:else if block.type === 'upcoming_calendar'} {:else if block.type === 'upcoming_calendar'}
<UpcomingCalendarBlock data={block.data} events={calendarEvents} /> <UpcomingCalendarBlock data={block.data} events={calendarEvents} />
{:else if block.type === 'shop'} {:else if block.type === 'shop'}
<ShopBlock data={block.data} {items} /> <ShopBlock data={block.data} {items} {slots} />
{:else if block.type === 'checkout'} {:else if block.type === 'checkout'}
<CheckoutBlock data={block.data} /> <CheckoutBlock data={block.data} />
{:else if block.type === 'cards'}
<CardsBlock data={block.data} />
{:else if block.type === 'faq'}
<FaqBlock data={block.data} />
{:else if block.type === 'html'}
<HtmlBlock data={block.data} />
{/if} {/if}
</BackgroundWrapper> </BackgroundWrapper>
{/each} {/each}

View file

@ -7,13 +7,6 @@
right: 'justify-end' right: 'justify-end'
}; };
// Whole class names, not `btn-${variant}`: Tailwind only generates classes
// it finds written out, so a built-up name rendered as a plain grey button.
const variantClasses: Record<string, string> = {
primary: 'btn-primary',
secondary: 'btn-secondary'
};
const sizeClasses: Record<string, string> = { const sizeClasses: Record<string, string> = {
xs: 'btn-xs', xs: 'btn-xs',
sm: 'btn-sm', sm: 'btn-sm',
@ -25,7 +18,7 @@
<div class="flex {alignmentClasses[data.alignment] || 'justify-center'}"> <div class="flex {alignmentClasses[data.alignment] || 'justify-center'}">
<a <a
href={data.href || '#'} href={data.href || '#'}
class="btn rounded-button {variantClasses[data.variant] || 'btn-primary'} {sizeClasses[data.size] || ''}" class="btn btn-{data.variant || 'primary'} {sizeClasses[data.size] || ''}"
style={data.color ? `background-color: ${data.color}; border-color: ${data.color};` : ''} style={data.color ? `background-color: ${data.color}; border-color: ${data.color};` : ''}
> >
{data.label || 'Button'} {data.label || 'Button'}

View file

@ -1,54 +0,0 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
type Card = { imageUrl?: string; imageAlt?: string; title?: string; subtitle?: string; text?: string; href?: string; linkLabel?: string };
let { data } = $props<{
data: { heading?: string; intro?: string; align?: 'left' | 'center'; style?: 'image' | 'numbered'; items?: Card[] };
}>();
let numbered = $derived(data.style === 'numbered');
</script>
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
{#if data.heading || data.intro}
<div class="prose-wellness text-lg text-fg-body/85" class:text-center={data.align === 'center'}>
{#if data.heading}<h2>{data.heading}</h2>{/if}
{#if data.intro}<p>{data.intro}</p>{/if}
</div>
{/if}
<div class="mt-6 grid gap-6 grid-cols-[repeat(auto-fit,minmax(200px,1fr))]">
{#each data.items || [] as card, i (i)}
<!-- Cards are white whatever the block's colours, so they use the site's own text colour. -->
<div class="relative overflow-hidden rounded-card bg-white text-[color-mix(in_srgb,var(--color-text,#2c2c2c)_85%,transparent)] shadow-sm transition-shadow {card.href ? 'hover:shadow-lg' : ''}">
{#if !numbered && card.imageUrl}
<img class="block aspect-[4/3] w-full object-cover" src={card.imageUrl} alt={card.imageAlt || ''} />
{/if}
<div class={numbered ? 'p-6' : 'px-5 pt-4 pb-5'}>
{#if numbered}
<span class="inline-grid size-9 place-items-center rounded-full bg-sage font-semibold text-[var(--color-primary-content,#fff)]">{i + 1}</span>
{/if}
<!-- Not an h3: the site's h1–h4 rule (serif, heading colour) would override these classes. -->
<strong class="block text-[1.15rem]" class:mt-3={numbered}>
<!-- The title's link covers the whole card (::after), so the card is one click target. -->
{#if card.href}<a class="after:absolute after:inset-0" href={card.href}>{card.title}</a>{:else}{card.title}{/if}
</strong>
{#if card.subtitle}<p class="mt-1 text-[0.95rem] opacity-75">{card.subtitle}</p>{/if}
{#if card.text}<div class="card-text mt-1 text-[0.95rem]">{@html card.text}</div>{/if}
{#if card.href && card.linkLabel}
<p class="mt-3 font-semibold text-sage-dark underline underline-offset-4">{card.linkLabel}</p>
{/if}
</div>
</div>
{/each}
</div>
</section>
<style>
/* Card text comes from the visual editor; links inside it stay clickable above the card's own link. */
.card-text :global(p) { margin: 0.35rem 0 0; }
.card-text :global(ul) { list-style: disc; padding-left: 1.25rem; margin: 0.5rem 0; }
.card-text :global(ol) { list-style: decimal; padding-left: 1.25rem; margin: 0.5rem 0; }
.card-text :global(li > p) { margin: 0; }
.card-text :global(a) { position: relative; z-index: 1; text-decoration: underline; }
.card-text :global(strong) { font-weight: 700; }
</style>

View file

@ -3,10 +3,9 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { page } from '$app/state'; import { page } from '$app/state';
import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, shopLinks, type BasketLine, type CheckoutBlockData } from '$shared/types'; import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type BasketLine, type CheckoutBlockData } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar';
import { formatDuration } from '$shared/items';
import { loadStripe } from '$shared/stripe-client'; import { loadStripe } from '$shared/stripe-client';
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js'; import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
@ -15,9 +14,6 @@
const basket = getBasketContext(); const basket = getBasketContext();
// Not set in the admin preview, which has no footer data. // Not set in the admin preview, which has no footer data.
const privacyPage = $derived(page.data.footer?.privacyPage || ''); const privacyPage = $derived(page.data.footer?.privacyPage || '');
// On its own basket page there is no shop above, so point to the booking page.
const bookingHref = $derived(shopLinks(page.data.header).booking);
const shopAbove = $derived(page.url.pathname === bookingHref);
const customer = $state({ name: '', email: '', phone: '', notes: '' }); const customer = $state({ name: '', email: '', phone: '', notes: '' });
let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle'); let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle');
@ -50,64 +46,14 @@
// Prices in the shop currency (STRIPE_CURRENCY, via layout data). // Prices in the shop currency (STRIPE_CURRENCY, via layout data).
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY); const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
/** Codes cover everything: the order is confirmed without a payment step. */
const nothingToPay = $derived(basket.lines.length > 0 && basket.total === 0);
const payLabel = $derived( const payLabel = $derived(
payState === 'confirming' payState === 'confirming'
? 'Confirming…' ? 'Confirming…'
: payState === 'creating' : payState === 'creating'
? nothingToPay ? 'Preparing payment…'
? 'Confirming…' : `Pay ${formatPrice(basket.total, currency)}`
: 'Preparing payment…'
: nothingToPay
? 'Confirm booking'
: `Pay ${formatPrice(basket.total, currency)}`
); );
// ── Bundle/voucher code ──
let codeInput = $state('');
let codeError = $state('');
let codeBusy = $state(false);
async function applyCode() {
if (!codeInput.trim() || codeBusy) return;
codeBusy = true;
codeError = '';
try {
await basket.applyCode(codeInput.trim());
codeInput = '';
} catch (e) {
codeError = e instanceof Error ? e.message : 'Could not apply the code.';
} finally {
codeBusy = false;
}
}
async function removeCode() {
codeBusy = true;
codeError = '';
try {
await basket.removeCode();
} catch (e) {
codeError = e instanceof Error ? e.message : 'Could not remove the code.';
} finally {
codeBusy = false;
}
}
// ── Gifts (bundle lines) ──
let giftOpen = $state<Record<string, boolean>>({});
async function saveGift(line: BasketLine, giftTo: string, giftMessage: string) {
if (giftTo === (line.giftTo ?? '') && giftMessage === (line.giftMessage ?? '')) return;
try {
await basket.setGift(line.id, giftTo, giftMessage);
} catch (e) {
errorMsg = e instanceof Error ? e.message : 'Could not save the gift details.';
}
}
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE); const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
/** "Fri 15 Jan, 10:00" in the studio's timezone. */ /** "Fri 15 Jan, 10:00" in the studio's timezone. */
@ -144,7 +90,7 @@
} }
function describeLine(line: BasketLine) { function describeLine(line: BasketLine) {
return [line.itemName ?? 'A time slot', line.start ? formatSlotTime(line.start) : ''].filter(Boolean).join(', '); return [line.itemName ?? 'A time slot', line.slotStart ? formatSlotTime(line.slotStart) : ''].filter(Boolean).join(', ');
} }
// At zero, reload the basket: the server drops the lapsed line. Retry every // At zero, reload the basket: the server drops the lapsed line. Retry every
@ -232,13 +178,7 @@
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.` `Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
); );
} }
const result = await res.json(); const { clientSecret } = await res.json();
if (result.free) {
// Paid in full with a code: the order exists, no payment step.
goto('/checkout/return?order=' + encodeURIComponent(result.orderId));
return;
}
const { clientSecret } = result;
// Starting payment holds the slots longer; show the new countdown. // Starting payment holds the slots longer; show the new countdown.
await basket.refresh(); await basket.refresh();
@ -355,11 +295,7 @@
{#if basket.lines.length === 0} {#if basket.lines.length === 0}
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center"> <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="font-serif text-xl">Your basket is empty</p>
{#if shopAbove} <p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
{:else}
<a class="mt-6 inline-flex rounded-button bg-sage px-6 py-2.5 text-sm font-medium text-primary-content transition hover:bg-sage-dark" href={bookingHref}>Book a session</a>
{/if}
</div> </div>
{:else} {:else}
{#if holdLeftMs !== null && slotLineCount} {#if holdLeftMs !== null && slotLineCount}
@ -380,7 +316,7 @@
{#if ending && payState !== 'confirming'} {#if ending && payState !== 'confirming'}
<button <button
type="button" type="button"
class="rounded-button border border-charcoal/20 bg-white px-4 py-1.5 font-medium transition hover:bg-charcoal/5 disabled:opacity-60" 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} disabled={renewing}
onclick={renewHolds} onclick={renewHolds}
> >
@ -394,8 +330,7 @@
<ul class="{holdLeftMs !== null && slotLineCount ? 'mt-4' : 'mt-8'} space-y-4"> <ul class="{holdLeftMs !== null && slotLineCount ? 'mt-4' : 'mt-8'} space-y-4">
{#each basket.lines as line (line.id)} {#each basket.lines as line (line.id)}
{@const pending = pendingLines.has(line.id)} {@const pending = pendingLines.has(line.id)}
<!-- On a phone the quantity, price and remove button go on a row of their own under the description. --> <li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
<li class="flex flex-wrap items-center gap-x-4 gap-y-3 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
{#if line.itemImageUrl} {#if line.itemImageUrl}
<img <img
src={line.itemImageUrl} src={line.itemImageUrl}
@ -409,91 +344,51 @@
{/if} {/if}
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<p class="break-words font-medium">{line.itemName ?? 'Item'}</p> <p class="truncate font-medium">{line.itemName ?? 'Item'}</p>
{#if line.lineType === 'slot' && line.start} {#if line.lineType === 'slot' && line.slotStart}
<p class="text-sm text-fg-body/70">{formatSlotTime(line.start)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</p> <p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
{/if}
{#if line.passCovered}
<p class="text-sm font-medium text-sage-dark">Paid with your code</p>
{:else if line.itemPrice == null}
<p class="text-sm text-terracotta">No longer offered at this length — please remove it and pick again.</p>
{:else}
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice, currency)}</p>
{/if}
{#if line.bundle}
<p class="text-sm text-fg-body/70">
{line.bundle.parts.map((p) => `${p.count}× ${p.name}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', ')}{line.bundle.validMonths
? ` · valid ${line.bundle.validMonths} months`
: ''}
</p>
{#if giftOpen[line.id] || line.giftTo}
<div class="mt-2 grid gap-2 sm:grid-cols-2">
<input
type="text"
maxlength="180"
placeholder="For (their name)"
aria-label="Who the gift is for"
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
value={line.giftTo ?? ''}
onchange={(e) => saveGift(line, e.currentTarget.value.trim(), line.giftMessage ?? '')}
/>
<input
type="text"
maxlength="1000"
placeholder="Message (optional)"
aria-label="Gift message"
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
value={line.giftMessage ?? ''}
onchange={(e) => saveGift(line, line.giftTo ?? '', e.currentTarget.value.trim())}
/>
</div>
<p class="mt-1 text-xs text-fg-body/60">Shown with the code in your confirmation email — forward it to them, or print it.</p>
{:else}
<button type="button" class="mt-1 text-sm text-sage-dark underline underline-offset-2" onclick={() => (giftOpen[line.id] = true)}>This is a gift</button>
{/if}
{/if} {/if}
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice ?? 0, currency)}</p>
</div> </div>
<div class="flex w-full items-center gap-3 sm:w-auto"> <!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. --> {#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1}
{#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1} <div class="flex items-center gap-2">
<div class="flex items-center gap-2"> <button
<button type="button"
type="button" class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
class="flex h-8 w-8 items-center justify-center rounded-button border border-charcoal/15 text-lg leading-none disabled:opacity-40" disabled={pending || line.quantity <= 1}
disabled={pending || line.quantity <= 1} aria-label="Decrease quantity"
aria-label="Decrease quantity" onclick={() => changeQuantity(line.id, line.quantity, -1)}
onclick={() => changeQuantity(line.id, line.quantity, -1)} >
> −
− </button>
</button> <span class="w-6 text-center">{line.quantity}</span>
<span class="w-6 text-center">{line.quantity}</span> <button
<button type="button"
type="button" class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
class="flex h-8 w-8 items-center justify-center rounded-button border border-charcoal/15 text-lg leading-none disabled:opacity-40" disabled={pending}
disabled={pending} aria-label="Increase quantity"
aria-label="Increase quantity" onclick={() => changeQuantity(line.id, line.quantity, 1)}
onclick={() => changeQuantity(line.id, line.quantity, 1)} >
> +
+ </button>
</button> </div>
</div> {/if}
{/if}
<p class="ml-auto shrink-0 whitespace-nowrap text-right font-medium sm:min-w-20"> <p class="w-20 shrink-0 text-right font-medium">
{formatPrice((line.itemPrice ?? 0) * line.quantity, currency)} {formatPrice((line.itemPrice ?? 0) * line.quantity, currency)}
</p> </p>
<button <button
type="button" type="button"
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-button text-charcoal/50 transition-colors hover:bg-terracotta/10 hover:text-terracotta disabled:opacity-40" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-charcoal/50 transition-colors hover:bg-terracotta/10 hover:text-terracotta disabled:opacity-40"
disabled={pending} disabled={pending}
aria-label="Remove {line.itemName ?? 'item'}" aria-label="Remove {line.itemName ?? 'item'}"
onclick={() => removeLine(line.id)} onclick={() => removeLine(line.id)}
> >
✕ ✕
</button> </button>
</div>
</li> </li>
{/each} {/each}
</ul> </ul>
@ -506,50 +401,6 @@
</div> </div>
</div> </div>
<!-- Bundle / voucher code: covers bookings of the same service and length. -->
<div class="mt-4 rounded-2xl border border-charcoal/10 bg-white p-5">
{#if basket.pass}
{@const left = basket.pass.parts.filter((p) => p.redeemable)}
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<p class="font-medium">Code <span class="font-mono tracking-wider">{basket.pass.code}</span> · {basket.pass.name}</p>
<p class="text-sm text-fg-body/70">
{left.map((p) => `${p.left} × ${p.name} (${formatDuration(p.minutes ?? 0)})`).join(', ')} left after this basket{basket.pass.expiresAt
? ` · valid until ${formatInstant(basket.pass.expiresAt, timezone, { day: 'numeric', month: 'long', year: 'numeric' })}`
: ''}.
</p>
{#if !basket.lines.some((l) => l.passCovered)}
<p class="mt-1 text-sm text-terracotta">Nothing in your basket matches this code — book one of the sessions above, at the same length.</p>
{/if}
</div>
<button type="button" class="text-sm text-fg-body/70 underline underline-offset-2 disabled:opacity-50" disabled={codeBusy} onclick={removeCode}>Remove code</button>
</div>
{:else}
<form
class="flex flex-wrap items-center gap-2"
onsubmit={(e) => {
e.preventDefault();
applyCode();
}}
>
<label class="text-sm font-medium" for="checkout-code">Have a bundle or voucher code?</label>
<input
id="checkout-code"
type="text"
autocomplete="off"
spellcheck="false"
placeholder="ABCD-2345"
class="w-36 rounded-xl border border-charcoal/15 bg-white px-3 py-2 font-mono tracking-wider uppercase focus:ring-2 focus:ring-sage/50 focus:outline-none"
bind:value={codeInput}
/>
<button type="submit" class="rounded-button border border-charcoal/20 px-4 py-2 text-sm font-medium transition hover:bg-charcoal/5 disabled:opacity-50" disabled={codeBusy || !codeInput.trim()}>
{codeBusy ? 'Checking…' : 'Apply'}
</button>
</form>
{/if}
{#if codeError}<p class="mt-2 text-sm text-terracotta" role="alert">{codeError}</p>{/if}
</div>
<div class="mt-10 grid gap-10 md:grid-cols-2"> <div class="mt-10 grid gap-10 md:grid-cols-2">
<!-- Customer details --> <!-- Customer details -->
<form <form
@ -617,7 +468,7 @@
{#if payState === 'idle' || payState === 'creating'} {#if payState === 'idle' || payState === 'creating'}
<button <button
type="submit" type="submit"
class="btn w-full rounded-button border-0 text-primary-content" class="btn w-full rounded-full border-0 text-primary-content"
style="background-color: var(--color-primary, #8a9a7b);" style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'creating'} disabled={payState === 'creating'}
> >
@ -652,7 +503,7 @@
{#if payState === 'ready' || payState === 'confirming'} {#if payState === 'ready' || payState === 'confirming'}
<button <button
type="button" type="button"
class="btn mt-4 w-full rounded-button border-0 text-primary-content" class="btn mt-4 w-full rounded-full border-0 text-primary-content"
style="background-color: var(--color-primary, #8a9a7b);" style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'confirming'} disabled={payState === 'confirming'}
onclick={confirmPayment} onclick={confirmPayment}
@ -663,9 +514,7 @@
{#if payState === 'idle' && !errorMsg} {#if payState === 'idle' && !errorMsg}
<p class="mt-4 text-sm text-fg-body/70"> <p class="mt-4 text-sm text-fg-body/70">
{nothingToPay Fill in your details and press Pay to continue to secure payment.
? 'Nothing to pay — your code covers everything. Fill in your details and press Confirm booking.'
: 'Fill in your details and press Pay to continue to secure payment.'}
</p> </p>
{/if} {/if}
</div> </div>

View file

@ -1,21 +0,0 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
type Question = { question?: string; answer?: string };
let { data } = $props<{ data: { heading?: string; items?: Question[] } }>();
</script>
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
<div class="prose-wellness text-lg text-fg-body/85">
{#if data.heading}<h2>{data.heading}</h2>{/if}
{#each data.items || [] as item, i (i)}
<details class="group border-b border-current/15 py-3.5">
<summary class="flex cursor-pointer list-none items-center justify-between gap-4 text-[1.1rem] font-semibold [&::-webkit-details-marker]:hidden">
{item.question}
<span class="shrink-0 text-2xl leading-none font-light transition-transform group-open:rotate-45" aria-hidden="true">+</span>
</summary>
{@html item.answer || ''}
</details>
{/each}
</div>
</section>

View file

@ -1,7 +1,4 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state';
import { shopLinks } from '$shared/types';
let { data } = $props<{ let { data } = $props<{
data: { data: {
heading?: string; heading?: string;
@ -14,17 +11,17 @@
<section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]"> <section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]">
<div class="relative z-10 mx-auto max-w-4xl text-center"> <div class="relative z-10 mx-auto max-w-4xl text-center">
<h1 class="animate-fade-in text-5xl leading-tight text-fg-heading md:text-7xl lg:text-8xl"> <h1 class="animate-fade-in text-5xl leading-tight text-fg-heading md:text-7xl lg:text-8xl" style="font-family: 'Playfair Display', Georgia, serif;">
{data.heading || 'Holistic and Experiential Learning about Happiness'} {data.heading || 'Holistic and Experiential Learning about Happiness'}
</h1> </h1>
{#if data.subheading} {#if data.subheading}
<p class="animate-fade-in mx-auto mt-6 max-w-2xl text-lg leading-relaxed text-fg-subheading/70 md:text-xl" style="animation-delay: 0.1s;"> <p class="animate-fade-in mx-auto mt-6 max-w-2xl text-lg leading-relaxed text-fg-subheading/70 md:text-xl" style="animation-delay: 0.15s;">
{data.subheading} {data.subheading}
</p> </p>
{/if} {/if}
{#if data.buttonLabel} {#if data.buttonLabel}
<div class="animate-fade-in mt-10" style="animation-delay: 0.2s;"> <div class="animate-fade-in mt-10" style="animation-delay: 0.3s;">
<a class="btn rounded-button border-0 bg-sage px-10 py-3 text-lg text-primary-content shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || shopLinks(page.data.header).booking}> <a class="btn rounded-full border-0 bg-sage px-10 py-3 text-lg text-primary-content shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || '/book'}>
{data.buttonLabel} {data.buttonLabel}
</a> </a>
</div> </div>

View file

@ -1,14 +0,0 @@
<script lang="ts">
import { scrollReveal } from '$shared/scrollReveal';
let { data } = $props<{ data: { html?: string } }>();
</script>
<!-- Written by an admin as-is, for embeds and one-off layouts. Same frame and text styles as a
Text block (old text blocks with layout HTML became HTML blocks and must look unchanged).
Tailwind classes in it get no styles (only classes found in this repo are generated). -->
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
<div class="prose-wellness text-lg text-fg-body/85">
{@html data.html || ''}
</div>
</section>

View file

@ -8,7 +8,7 @@
<section use:scrollReveal class="reveal mx-auto max-w-6xl px-6 py-14 md:py-20"> <section use:scrollReveal class="reveal mx-auto max-w-6xl px-6 py-14 md:py-20">
<div class="grid items-center gap-10 md:grid-cols-2"> <div class="grid items-center gap-10 md:grid-cols-2">
<div class:md:order-2={data.imagePosition === 'right'} class="overflow-hidden rounded-panel bg-sage/10 shadow-sm"> <div class:md:order-2={data.imagePosition === 'right'} class="overflow-hidden rounded-[2rem] bg-sage/10 shadow-sm">
{#if data.url} {#if data.url}
<img class="aspect-[4/5] w-full object-cover" src={data.url} alt={data.alt || ''} /> <img class="aspect-[4/5] w-full object-cover" src={data.url} alt={data.alt || ''} />
{:else} {:else}

View file

@ -1,14 +1,14 @@
<script lang="ts"> <script lang="ts">
import { page } from '$app/state'; import { page } from '$app/state';
import { shopLinks, type BasketLine, type BookableTime, type ShopBlockData, type ShopSort, type ItemRecord } from '$shared/types'; import type { BasketLine, ShopBlockData, ItemRecord, SlotRecord } from '$shared/types';
import { getBasketContext } from '$shared/basket.svelte'; import { getBasketContext } from '$shared/basket.svelte';
import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey, zonedInputToIso } from '$shared/calendar'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, addMonths, createCalendarMonth, formatInstant, formatPrice, startOfMonth, zonedDateKey } from '$shared/calendar';
import { SHOP_SORTS, bundleListPrice, formatDuration, lowestPrice, sortItems } from '$shared/items'; import { formatDateKey } from '$shared/slots';
import { addDaysToKey, formatDateKey } from '$shared/slots';
let { data = {}, items = [] } = $props<{ let { data = {}, items = [], slots = [] } = $props<{
data: ShopBlockData; data: ShopBlockData;
items?: ItemRecord[]; items?: ItemRecord[];
slots?: SlotRecord[];
}>(); }>();
const basket = getBasketContext(); const basket = getBasketContext();
@ -16,74 +16,74 @@
// Per-card interaction state. Instances are created per component instance // Per-card interaction state. Instances are created per component instance
// (never shared at module level); keyed by item id so each card is independent. // (never shared at module level); keyed by item id so each card is independent.
class CardState { class CardState {
/** Index into the service's durations (the slider). */
durationIndex = $state(0);
pickerOpen = $state(false); pickerOpen = $state(false);
selectedDayKey = $state<string | null>(null); selectedDayKey = $state<string | null>(null);
adding = $state(false); adding = $state(false);
errorMsg = $state<string | null>(null); errorMsg = $state<string | null>(null);
justAdded = $state(false); justAdded = $state(false);
/** `slot|start` of the time being added or changed. */ pendingSlotId = $state<string | null>(null);
pendingKey = $state<string | null>(null);
/** Months from the current one to the first month shown in the picker. */ /** Months from the current one to the first month shown in the picker. */
monthOffset = $state(0); monthOffset = $state(0);
// Bookable times for the selected duration in the months shown (GET /api/slots).
times = $state<BookableTime[]>([]);
next = $state<string | null>(null);
loading = $state(false);
loadError = $state<string | null>(null);
/** What `times` was loaded for; a reload starts when this differs. */
loadedKey = $state('');
requestId = 0;
} }
let cardStates = $state<Record<string, CardState>>({}); let cardStates = $state<Record<string, CardState>>({});
/** The picker shows this many months side by side; the arrows move one month. */ /** The picker shows this many months side by side; the arrows move one month. */
const MONTHS_SHOWN = 2; const MONTHS_SHOWN = 2;
/** How far ahead the picker goes (the shop hook lists up to a year). */
const MAX_MONTH_OFFSET = 12;
const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; const weekdayLetters = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE); const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY); const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
const basketHref = $derived(shopLinks(page.data.header).basket);
let visibleItems: ItemRecord[] = $derived.by(() => { let visibleItems: ItemRecord[] = $derived.by(() => {
let result: ItemRecord[] = items; let result: ItemRecord[] = items;
if (data.itemTypeFilter && data.itemTypeFilter !== 'all') { if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
result = result.filter((i) => i.type === data.itemTypeFilter); result = result.filter((i) => i.type === data.itemTypeFilter);
} }
if (data.itemIds?.length) { if (data.itemIds?.length) {
const wanted = new Set(data.itemIds); const wanted = new Set(data.itemIds);
result = result.filter((i) => wanted.has(i.id)); result = result
.filter((i) => wanted.has(i.id))
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
} }
return sortItems(result, sort); return result;
}); });
/** What the visitor picked in "Sort by" (only while the menu is shown); else the block's own order. */ // The listing leaves out full slots — including ones whose last places are
let pickedSort = $state<ShopSort | null>(null); // in this visitor's own basket. Add those back (no places left) so the
// "Most popular" needs recent sales to go by; without any it would only repeat Recommended, so it's left out. // visitor still sees their times and can change or drop their places.
let hasSales = $derived(items.some((item: ItemRecord) => item.popularRank !== null)); let shownSlots = $derived.by<SlotRecord[]>(() => {
let sort = $derived.by<ShopSort>(() => { const listed = new Set(slots.map((s: SlotRecord) => s.id));
const wanted = (data.showSort && pickedSort) || data.sort || 'recommended'; const own = basket.lines
return wanted === 'popular' && !hasSales ? 'recommended' : wanted; .filter((l) => l.lineType === 'slot' && l.slot && !listed.has(l.slot) && l.slotStart && Date.parse(l.slotStart) > Date.now())
.map((l) => ({ id: l.slot!, item: l.item, start: l.slotStart!, end: l.slotEnd ?? l.slotStart!, capacity: l.slotCapacity ?? 1, free: 0 }));
return own.length ? [...slots, ...own] : slots;
});
// item id -> day key ('YYYY-MM-DD', in the studio's timezone) -> slots on that day, sorted by start time
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
const map = new Map<string, Map<string, SlotRecord[]>>();
for (const slot of shownSlots) {
const key = zonedDateKey(slot.start, timezone);
if (!key) continue;
let itemMap = map.get(slot.item);
if (!itemMap) {
itemMap = new Map();
map.set(slot.item, itemMap);
}
const list = itemMap.get(key);
if (list) list.push(slot);
else itemMap.set(key, [slot]);
}
for (const itemMap of map.values()) {
for (const list of itemMap.values()) {
list.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
}
}
return map;
}); });
let sortChoices = $derived(SHOP_SORTS.filter((choice) => choice.value !== 'popular' || hasSales));
let showSortMenu = $derived(!!data.showSort && visibleItems.length > 1);
let isList = $derived(data.layout === 'list'); let isList = $derived(data.layout === 'list');
/** Item id → name, for what bundles contain. */
let itemNames = $derived(new Map(items.map((item: ItemRecord) => [item.id, item.name])));
/** Changes whenever the basket's bookings do, so open pickers reload (a booking blocks other times). */
let basketBookingsKey = $derived(
basket.lines
.filter((l) => l.lineType === 'slot')
.map((l) => `${l.id}:${l.quantity}`)
.join(',')
);
/** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */ /** `2027-01-15` → months from the current month (browser's calendar) to January 2027. */
function monthOffsetOf(key: string) { function monthOffsetOf(key: string) {
const today = new Date(); const today = new Date();
@ -96,19 +96,6 @@
return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1)); return Array.from({ length: MONTHS_SHOWN }, (_, i) => createCalendarMonth(addMonths(first, i), new Date(), 1));
} }
/** First and last date key of the months shown at `offset`. */
function shownRange(offset: number) {
const months = pickerMonths(offset);
return {
from: months[0].days.find((d) => d.inMonth)!.dateKey,
to: months[months.length - 1].days.findLast((d) => d.inMonth)!.dateKey
};
}
function selectedDuration(item: ItemRecord, state: CardState | undefined) {
return item.durations[Math.min(state?.durationIndex ?? 0, item.durations.length - 1)] ?? null;
}
// Lazily create card state for whatever items are rendered. // Lazily create card state for whatever items are rendered.
$effect(() => { $effect(() => {
for (const item of visibleItems) { for (const item of visibleItems) {
@ -116,78 +103,6 @@
} }
}); });
// Load the bookable times for every open picker: again when the duration,
// the months shown or the basket's bookings change.
$effect(() => {
for (const item of visibleItems) {
const state = cardStates[item.id];
const duration = selectedDuration(item, state);
if (!state?.pickerOpen || !duration) continue;
const range = shownRange(state.monthOffset);
const key = [item.id, duration.minutes, range.from, range.to, timezone, basketBookingsKey].join('|');
if (key !== state.loadedKey) void loadTimes(state, item.id, duration.minutes, range, key);
}
});
async function loadTimes(state: CardState, itemId: string, minutes: number, range: { from: string; to: string }, key: string) {
const requestId = ++state.requestId;
state.loadedKey = key;
state.loading = true;
state.loadError = null;
const params = new URLSearchParams({
item: itemId,
minutes: String(minutes),
from: zonedInputToIso(`${range.from}T00:00`, timezone),
to: zonedInputToIso(`${addDaysToKey(range.to, 1)}T00:00`, timezone)
});
try {
const res = await fetch(`/api/slots?${params}`);
const body = await res.json().catch(() => ({}));
if (requestId !== state.requestId) return; // a newer request is under way
if (!res.ok) throw new Error(body?.message || 'Could not load the available times.');
state.times = body.times ?? [];
state.next = body.next ?? null;
} catch (e) {
if (requestId !== state.requestId) return;
state.times = [];
state.next = null;
state.loadError = errorMessage(e, 'Could not load the available times.');
state.loadedKey = ''; // try again on the next change
} finally {
if (requestId === state.requestId) state.loading = false;
}
}
type DayEntry = { time: BookableTime | null; line: BasketLine | null; start: string; end: string; slot: string };
/**
* Day key → what to show that day: the bookable times, plus this
* visitor's own bookings of this service and length (a time they hold
* is no longer listed as bookable, but they should still see it).
*/
function entriesByDay(item: ItemRecord, state: CardState, minutes: number) {
const own = basket.lines.filter(
(l) => l.lineType === 'slot' && l.item === item.id && l.minutes === minutes && l.start && Date.parse(l.start) > Date.now()
);
const entries: DayEntry[] = state.times.map((time) => ({
time,
line: own.find((l) => l.slot === time.slot && l.start && Date.parse(l.start) === Date.parse(time.start)) ?? null,
start: time.start,
end: time.end,
slot: time.slot
}));
for (const line of own) {
if (entries.some((e) => e.line === line)) continue;
entries.push({ time: null, line, start: line.start!, end: line.end ?? line.start!, slot: line.slot ?? '' });
}
const byDay = new Map<string, DayEntry[]>();
for (const entry of entries.sort((a, b) => Date.parse(a.start) - Date.parse(b.start))) {
const key = zonedDateKey(entry.start, timezone);
if (key) byDay.set(key, [...(byDay.get(key) ?? []), entry]);
}
return byDay;
}
function togglePicker(itemId: string) { function togglePicker(itemId: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state) return; if (!state) return;
@ -198,21 +113,11 @@
state.monthOffset = 0; state.monthOffset = 0;
} }
function selectDuration(itemId: string, index: number) { /** Show the month of the first available day and select it. */
function showFirstAvailable(itemId: string, key: string) {
const state = cardStates[itemId]; const state = cardStates[itemId];
if (!state || state.durationIndex === index) return; if (!state) return;
state.durationIndex = index; state.monthOffset = Math.max(0, monthOffsetOf(key));
state.selectedDayKey = null;
state.justAdded = false;
state.errorMsg = null;
}
/** Show the month of `iso`'s day and select that day. */
function showDay(itemId: string, iso: string) {
const state = cardStates[itemId];
const key = zonedDateKey(iso, timezone);
if (!state || !key) return;
state.monthOffset = Math.min(MAX_MONTH_OFFSET, Math.max(0, monthOffsetOf(key)));
state.selectedDayKey = key; state.selectedDayKey = key;
} }
@ -234,32 +139,31 @@
} }
} }
async function addTime(item: ItemRecord, minutes: number, time: BookableTime) { async function addSlot(itemId: string, slotId: string) {
const state = cardStates[item.id]; const state = cardStates[itemId];
if (!state || state.adding) return; if (!state || state.adding) return;
state.adding = true; state.adding = true;
state.pendingKey = `${time.slot}|${time.start}`; state.pendingSlotId = slotId;
state.errorMsg = null; state.errorMsg = null;
try { try {
// The picker reloads afterwards (basketBookingsKey changes): this // The store reloads the listing afterwards: a booking can block other
// booking takes its time, plus get-ready time, out of the day. // times (one practitioner) or fill a group session.
await basket.addSlotLine(time.slot, time.kind === 'window' ? { itemId: item.id, minutes, start: time.start } : null); await basket.addSlotLine(slotId);
state.justAdded = true; state.justAdded = true;
} catch (e) { } catch (e) {
state.errorMsg = errorMessage(e, 'Could not book this time.'); state.errorMsg = errorMessage(e, 'Could not book this time slot.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingKey = null; state.pendingSlotId = null;
} }
} }
/** One place more or fewer in a group session already in the basket (0 removes it). */ /** One place more or fewer in a group session already in the basket (0 removes it). */
async function changeSeats(itemId: string, entry: DayEntry, delta: number) { async function changeSeats(itemId: string, line: BasketLine, delta: number) {
const state = cardStates[itemId]; const state = cardStates[itemId];
const line = entry.line; if (!state || state.adding) return;
if (!state || !line || state.adding) return;
state.adding = true; state.adding = true;
state.pendingKey = `${entry.slot}|${entry.start}`; state.pendingSlotId = line.slot;
state.errorMsg = null; state.errorMsg = null;
try { try {
const seats = line.quantity + delta; const seats = line.quantity + delta;
@ -269,7 +173,7 @@
state.errorMsg = errorMessage(e, 'Could not change the number of places.'); state.errorMsg = errorMessage(e, 'Could not change the number of places.');
} finally { } finally {
state.adding = false; state.adding = false;
state.pendingKey = null; state.pendingSlotId = null;
} }
} }
@ -280,30 +184,11 @@
function placesLeft(free: number) { function placesLeft(free: number) {
return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left'; return free > 0 ? `${free} ${free === 1 ? 'place' : 'places'} left` : 'no places left';
} }
const longDate = (key: string) => formatDateKey(key, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
</script> </script>
<section class="mx-auto max-w-6xl px-6 py-16"> <section class="mx-auto max-w-6xl px-6 py-16">
{#if data.title} {#if data.title}
<h2 class={showSortMenu ? 'mb-8 text-center font-serif text-3xl text-charcoal md:text-4xl' : 'mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl'}>{data.title}</h2> <h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
{/if}
{#if showSortMenu}
<div class="mb-6 flex justify-end">
<label class="inline-flex items-center gap-2 text-sm text-charcoal/70">
Sort by
<select
class="rounded-button border border-charcoal/15 bg-white py-1.5 pr-8 pl-3.5 text-sm text-charcoal"
value={sort}
onchange={(e) => (pickedSort = e.currentTarget.value as ShopSort)}
>
{#each sortChoices as choice (choice.value)}
<option value={choice.value}>{choice.label}</option>
{/each}
</select>
</label>
</div>
{/if} {/if}
{#if !visibleItems.length} {#if !visibleItems.length}
@ -317,14 +202,13 @@
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}> <div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}>
{#each visibleItems as item (item.id)} {#each visibleItems as item (item.id)}
{@const ui = cardStates[item.id]} {@const ui = cardStates[item.id]}
{@const itemSlotsByDay = slotsByDay.get(item.id)}
{@const isService = item.type === 'item_with_time'} {@const isService = item.type === 'item_with_time'}
{@const duration = isService ? selectedDuration(item, ui) : null} {@const soldOut = !isService && item.stock === 0}
{@const bookable = !isService || !!duration}
{@const soldOut = item.type === 'item' && item.stock === 0}
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)} {@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
<article <article
class={isList class={isList
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:flex-wrap sm:gap-6' ? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6'
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'} : 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
> >
{#if item.imageUrl} {#if item.imageUrl}
@ -349,45 +233,19 @@
{#if item.description} {#if item.description}
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p> <p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
{/if} {/if}
{#if item.type === 'bundle'}
<!-- What the bundle contains; its code books the sessions later. -->
<ul class="mt-2 space-y-0.5 text-sm text-charcoal/80">
{#each item.bundleParts as part (`${part.item}|${part.minutes}`)}
<li>{part.count}× {itemNames.get(part.item) ?? 'Item'}{part.minutes ? ` (${formatDuration(part.minutes)})` : ''}</li>
{/each}
</ul>
<p class="mt-1 text-xs text-charcoal/60">
You get a code to book the sessions whenever suits you{item.validMonths ? ` — valid ${item.validMonths} months` : ''}. It can be given as a gift.
</p>
{/if}
<div class="mt-auto pt-3"> <div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
{#if isService && item.durations.length > 1} <span class="text-lg font-semibold text-sage-dark">{formatPrice(item.price, currency)}</span>
<!-- Several lengths: the length is picked (slider) after pressing Book. --> {#if isService && item.duration != null}
<div class="flex flex-wrap items-center gap-x-3 gap-y-1"> <span class="text-xs text-charcoal/60">{item.duration} min</span>
<span class="text-lg font-semibold text-sage-dark">from {formatPrice(lowestPrice(item.durations) ?? item.price, currency)}</span> {:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
<span class="text-xs text-charcoal/60">{formatDuration(item.durations[0].minutes)} – {formatDuration(item.durations[item.durations.length - 1].minutes)}</span> <span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
</div> Only {item.stock} left
{:else} </span>
{@const listPrice = item.type === 'bundle' ? bundleListPrice(item.bundleParts, items) : null} {:else if soldOut}
<div class="flex flex-wrap items-center gap-x-3 gap-y-1"> <span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
<span class="text-lg font-semibold text-sage-dark">{formatPrice(duration?.price ?? lowestPrice(item.durations) ?? item.price, currency)}</span> Sold out
{#if listPrice != null && listPrice > item.price} </span>
<!-- What the parts cost one by one: the bundle is a saving. -->
<s class="text-sm text-charcoal/50"><span class="sr-only">Bought separately: </span>{formatPrice(listPrice, currency)}</s>
{/if}
{#if duration}
<span class="text-xs text-charcoal/60">{formatDuration(duration.minutes)}</span>
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
<span class="rounded-button bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Only {item.stock} left
</span>
{:else if soldOut}
<span class="rounded-button bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
Sold out
</span>
{/if}
</div>
{/if} {/if}
</div> </div>
@ -412,21 +270,20 @@
{#if isService} {#if isService}
<button <button
type="button" type="button"
class="inline-flex items-center justify-center gap-2 rounded-button px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5' ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
: bookable : itemSlotsByDay?.size
? 'bg-sage text-primary-content hover:bg-sage-dark' ? 'bg-sage text-primary-content hover:bg-sage-dark'
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}" : 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
disabled={!bookable && !ui?.pickerOpen} disabled={!itemSlotsByDay?.size && !ui?.pickerOpen}
aria-expanded={!!ui?.pickerOpen}
onclick={() => togglePicker(item.id)} onclick={() => togglePicker(item.id)}
> >
{bookable ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'} {itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
</button> </button>
{:else} {:else}
<button <button
type="button" type="button"
class="inline-flex items-center justify-center gap-2 rounded-button bg-sage px-6 py-2.5 text-sm font-medium text-primary-content transition hover:bg-sage-dark disabled:cursor-not-allowed disabled:bg-charcoal/10 disabled:text-charcoal/50" class="inline-flex items-center justify-center gap-2 rounded-full bg-sage px-6 py-2.5 text-sm font-medium text-primary-content transition hover:bg-sage-dark disabled:cursor-not-allowed disabled:bg-charcoal/10 disabled:text-charcoal/50"
disabled={soldOut || ui?.adding} disabled={soldOut || ui?.adding}
onclick={() => addItem(item.id)} onclick={() => addItem(item.id)}
> >
@ -435,7 +292,7 @@
</button> </button>
{#if itemInBasket} {#if itemInBasket}
<a <a
href={basketHref} href="/book"
class="inline-flex items-center gap-1 text-sm font-medium text-sage-dark underline-offset-2 hover:underline" class="inline-flex items-center gap-1 text-sm font-medium text-sage-dark underline-offset-2 hover:underline"
>✓ In basket</a >✓ In basket</a
> >
@ -444,85 +301,51 @@
</div> </div>
</div> </div>
{#if isService && ui?.pickerOpen && duration} {#if isService && ui?.pickerOpen && itemSlotsByDay}
{@const byDay = entriesByDay(item, ui, duration.minutes)} {@const availableKeys = [...itemSlotsByDay.keys()].sort()}
{@const availableKeys = [...byDay.keys()].sort()}
{@const months = pickerMonths(ui.monthOffset)} {@const months = pickerMonths(ui.monthOffset)}
{@const shown = shownRange(ui.monthOffset)} {@const shownFrom = months[0].days.find((d) => d.inMonth)!.dateKey}
{@const anyShown = availableKeys.some((key) => key >= shown.from && key <= shown.to)} {@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'}> <div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
{#if item.durations.length > 1}
<!-- Several lengths: a slider steps through them and the price follows. -->
<div class="mb-5">
<label class="block">
<span class="flex items-baseline justify-between gap-3">
<span class="text-sm font-medium text-charcoal">Length · {formatDuration(duration.minutes)}</span>
<span class="text-lg font-semibold text-sage-dark">{formatPrice(duration.price, currency)}</span>
</span>
<input
type="range"
class="mt-2 w-full cursor-pointer accent-sage"
min="0"
max={item.durations.length - 1}
step="1"
value={ui.durationIndex}
aria-label="Length of {item.name}"
aria-valuetext="{formatDuration(duration.minutes)}, {formatPrice(duration.price, currency)}"
oninput={(e) => selectDuration(item.id, Number(e.currentTarget.value))}
/>
</label>
<div class="mt-1 flex justify-between text-xs text-charcoal/50" aria-hidden="true">
{#each item.durations as option, i (option.minutes)}
<button type="button" tabindex="-1" class="hover:text-charcoal {i === ui.durationIndex ? 'font-semibold text-charcoal' : ''}" onclick={() => selectDuration(item.id, i)}>
{formatDuration(option.minutes)}
</button>
{/each}
</div>
</div>
{/if}
<div class="mb-3 flex items-center justify-between gap-2"> <div class="mb-3 flex items-center justify-between gap-2">
<button <button
type="button" type="button"
class="flex h-8 w-8 items-center justify-center rounded-button border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30" class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
aria-label="Previous month" aria-label="Previous month"
disabled={ui.monthOffset <= 0} disabled={ui.monthOffset <= 0}
onclick={() => ui.monthOffset--} onclick={() => ui.monthOffset--}
> >
‹ ‹
</button> </button>
<p class="flex items-center gap-2 text-sm font-medium text-charcoal/70"> <p class="text-sm font-medium text-charcoal/70">Select a date</p>
{#if ui.loading}<span class="loading loading-spinner loading-xs" aria-label="Loading times"></span>{/if}
Select a date · {formatDuration(duration.minutes)}
</p>
<button <button
type="button" type="button"
class="flex h-8 w-8 items-center justify-center rounded-button border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30" class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none text-charcoal transition hover:bg-charcoal/5 disabled:cursor-default disabled:opacity-30"
aria-label="Next month" aria-label="Next month"
disabled={ui.monthOffset >= MAX_MONTH_OFFSET} disabled={ui.monthOffset >= lastOffset}
onclick={() => ui.monthOffset++} onclick={() => ui.monthOffset++}
> >
› ›
</button> </button>
</div> </div>
{#if ui.loadError} {#if !anyShown && availableKeys.length}
<p class="mb-4 rounded-xl border border-terracotta/30 bg-terracotta/10 px-4 py-3 text-sm text-charcoal" role="alert">{ui.loadError}</p>
{:else if !ui.loading && !anyShown}
<!-- Nothing in the months on screen: say when the next date is, so <!-- Nothing in the months on screen: say when the next date is, so
nobody books January thinking it is this month. --> nobody books January thinking it is this month. -->
<div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal"> <div class="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm text-charcoal">
{#if ui.next} <span>
<span>The next available date for {formatDuration(duration.minutes)} is <strong>{longDate(zonedDateKey(ui.next, timezone))}</strong>.</span> {availableKeys[0] > shownTo ? 'The first available date is' : 'The next available date is'}
<button <strong>{formatDateKey(availableKeys.find((key) => key > shownTo) ?? availableKeys[0], { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</strong>.
type="button" </span>
class="rounded-button bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark" <button
onclick={() => showDay(item.id, ui.next!)} type="button"
> class="rounded-full bg-sage px-4 py-1.5 font-medium text-primary-content transition hover:bg-sage-dark"
Go to next available date → onclick={() => showFirstAvailable(item.id, availableKeys.find((key) => key > shownTo) ?? availableKeys[0])}
</button> >
{:else} Go to {availableKeys[0] > shownTo ? 'first' : 'next'} available date →
<span>No times are available for {formatDuration(duration.minutes)} in these months{item.durations.length > 1 ? ' — try another length' : ''}.</span> </button>
{/if}
</div> </div>
{/if} {/if}
@ -535,14 +358,14 @@
<span class="py-1 text-xs text-charcoal/40">{letter}</span> <span class="py-1 text-xs text-charcoal/40">{letter}</span>
{/each} {/each}
{#each month.days as day (day.dateKey)} {#each month.days as day (day.dateKey)}
{@const selectable = day.inMonth && byDay.has(day.dateKey)} {@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)}
{@const selected = selectable && ui.selectedDayKey === day.dateKey} {@const selected = selectable && ui.selectedDayKey === day.dateKey}
<button <button
type="button" type="button"
disabled={!selectable} disabled={!selectable}
aria-pressed={selected} aria-pressed={selected}
onclick={() => (ui.selectedDayKey = day.dateKey)} onclick={() => (ui.selectedDayKey = day.dateKey)}
class="aspect-square rounded-button text-sm transition {selected class="aspect-square rounded-full text-sm transition {selected
? 'bg-sage font-semibold text-primary-content' ? 'bg-sage font-semibold text-primary-content'
: selectable : selectable
? 'cursor-pointer bg-sage/15 font-medium text-charcoal hover:bg-sage/35' ? 'cursor-pointer bg-sage/15 font-medium text-charcoal hover:bg-sage/35'
@ -559,40 +382,40 @@
{/each} {/each}
</div> </div>
{#if ui.selectedDayKey && byDay.has(ui.selectedDayKey)} {#if ui.selectedDayKey}
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70"> <p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">
Available times · {longDate(ui.selectedDayKey)} Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
</p> </p>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
{#each byDay.get(ui.selectedDayKey) ?? [] as entry (`${entry.slot}|${entry.start}`)} {#each daySlots as slot (slot.id)}
{@const isGroup = (entry.time?.capacity ?? entry.line?.slotCapacity ?? 1) > 1} {@const line = basket.lines.find((l) => l.slot === slot.id)}
{@const free = entry.time?.free ?? 0} {@const isGroup = slot.capacity > 1}
{@const pending = ui.pendingKey === `${entry.slot}|${entry.start}`} {@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
{@const label = `${formatTime(entry.start)}–${formatTime(entry.end)}`} {#if isGroup && line}
{#if isGroup && entry.line}
<!-- Places in a group session already in the basket: − / + --> <!-- Places in a group session already in the basket: − / + -->
<div class="inline-flex items-center gap-2 rounded-button bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark"> <div class="inline-flex items-center gap-2 rounded-full bg-sage/15 py-1 pr-1 pl-3.5 text-sm text-sage-dark">
<span>{label} · {placesLeft(free)}</span> <span>{label} · {placesLeft(slot.free)}</span>
<span class="inline-flex items-center gap-1 rounded-button bg-white px-1 py-0.5"> <span class="inline-flex items-center gap-1 rounded-full bg-white px-1 py-0.5">
<button <button
type="button" type="button"
class="flex h-6 w-6 items-center justify-center rounded-button leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40" class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
aria-label="One place fewer" aria-label="One place fewer"
disabled={ui.adding} disabled={ui.adding}
onclick={() => changeSeats(item.id, entry, -1)} onclick={() => changeSeats(item.id, line, -1)}
> >
− −
</button> </button>
<span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite"> <span class="min-w-5 text-center font-semibold text-charcoal tabular-nums" aria-live="polite">
{#if pending}<span class="loading loading-spinner loading-xs"></span>{:else}{entry.line.quantity}{/if} {#if ui.pendingSlotId === slot.id}<span class="loading loading-spinner loading-xs"></span>{:else}{line.quantity}{/if}
<span class="sr-only">{entry.line.quantity === 1 ? 'place' : 'places'} in your basket</span> <span class="sr-only">{line.quantity === 1 ? 'place' : 'places'} in your basket</span>
</span> </span>
<button <button
type="button" type="button"
class="flex h-6 w-6 items-center justify-center rounded-button leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40" class="flex h-6 w-6 items-center justify-center rounded-full leading-none text-charcoal transition hover:bg-charcoal/10 disabled:opacity-40"
aria-label="One place more" aria-label="One place more"
disabled={ui.adding || free <= 0} disabled={ui.adding || slot.free <= 0}
onclick={() => changeSeats(item.id, entry, 1)} onclick={() => changeSeats(item.id, line, 1)}
> >
+ +
</button> </button>
@ -601,30 +424,32 @@
{:else} {:else}
<button <button
type="button" type="button"
disabled={!!entry.line || !entry.time || ui.adding} disabled={!!line || ui.adding}
onclick={() => entry.time && addTime(item, duration.minutes, entry.time)} onclick={() => addSlot(item.id, slot.id)}
class="inline-flex items-center gap-1.5 rounded-button border px-3.5 py-1.5 text-sm transition {entry.line 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' ? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding && : 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
!entry.line !line
? 'cursor-wait' ? 'cursor-wait'
: ''}" : ''}"
> >
{#if pending} {#if ui.pendingSlotId === slot.id}
<span class="loading loading-spinner loading-xs"></span> <span class="loading loading-spinner loading-xs"></span>
{/if} {/if}
{label}{isGroup ? ` · ${placesLeft(free)}` : ''}{entry.line ? ' · In basket' : ''} {label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
</button> </button>
{/if} {/if}
{/each} {/each}
</div> </div>
{:else if anyShown} {:else if anyShown}
<p class="mt-4 text-sm text-charcoal/60">Days with availability are highlighted.</p> <p class="mt-4 text-sm text-charcoal/60">
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
</p>
{/if} {/if}
{#if ui.justAdded} {#if ui.justAdded}
<p class="mt-3 text-sm font-medium text-sage-dark"> <p class="mt-3 text-sm font-medium text-sage-dark">
Added ✓ — <a href={basketHref} class="underline underline-offset-2 hover:no-underline">view basket</a> Added ✓ — <a href="/book" class="underline underline-offset-2 hover:no-underline">view basket</a>
</p> </p>
{/if} {/if}
</div> </div>

View file

@ -52,7 +52,7 @@
<button <button
type="button" type="button"
onclick={prev} onclick={prev}
class="w-10 h-10 rounded-button flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]" class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
aria-label="Previous slide" aria-label="Previous slide"
> >
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5"> <svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
@ -75,7 +75,7 @@
<button <button
type="button" type="button"
onclick={next} onclick={next}
class="w-10 h-10 rounded-button flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]" class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
aria-label="Next slide" aria-label="Next slide"
> >
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5"> <svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">

View file

@ -1,15 +1,11 @@
<script lang="ts"> <script lang="ts">
import { scrollReveal } from '$shared/scrollReveal'; import { scrollReveal } from '$shared/scrollReveal';
let { data } = $props<{ data: { content?: string; align?: 'left' | 'center'; size?: 'normal' | 'small' } }>(); let { data } = $props<{ data: { content?: string } }>();
</script> </script>
<!-- Small text is a footnote to the block above (references, terms), so it sits right under it. --> <section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 {data.size === 'small' ? 'pb-12 md:pb-16' : 'py-12 md:py-16'}"> <div class="prose-wellness text-lg text-fg-body/85">
<div
class="prose-wellness {data.size === 'small' ? 'text-base text-fg-body/75' : 'text-lg text-fg-body/85'}"
class:text-center={data.align === 'center'}
>
{@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'} {@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'}
</div> </div>
</section> </section>

View file

@ -6,9 +6,8 @@
let items = $derived(data.items?.length ? data.items : [ let items = $derived(data.items?.length ? data.items : [
{ title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' } { title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' }
]); ]);
// Desktop only: cards alternate sides and overlap a little; on a phone they stack in one column.
let widths = $derived(items.map((_: TimelineItem, i: number) => { let widths = $derived(items.map((_: TimelineItem, i: number) => {
const opts = ['md:w-[78%]', 'md:w-[85%]', 'md:w-[90%]', 'md:w-[95%]', 'md:w-[98%]']; const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]'];
return opts[(i * 7 + 3) % opts.length]; return opts[(i * 7 + 3) % opts.length];
})); }));
</script> </script>
@ -20,9 +19,9 @@
</div> </div>
<div class="relative md:before:absolute md:before:left-1/2 md:before:top-0 md:before:h-full md:before:w-px md:before:bg-sage/30"> <div class="relative md:before:absolute md:before:left-1/2 md:before:top-0 md:before:h-full md:before:w-px md:before:bg-sage/30">
{#each items as item, index} {#each items as item, index}
<div use:scrollReveal class="reveal relative mb-4 grid gap-4 md:mb-[-1rem] md:grid-cols-2 md:gap-8"> <div use:scrollReveal class="reveal relative mb-[-1rem] grid gap-4 md:grid-cols-2 md:gap-8">
<div class="hidden md:block" class:md:order-2={index % 2 === 0}></div> <div class="hidden md:block" class:md:order-2={index % 2 === 0}></div>
<article class="rounded-2xl bg-white/75 p-5 shadow-sm ring-1 ring-charcoal/5 md:-mt-4 {widths[index]} {index % 2 === 0 ? 'md:ml-auto md:text-right' : ''}"> <article class="rounded-2xl bg-white/75 p-5 shadow-sm ring-1 ring-charcoal/5 -mt-4 {widths[index]} {index % 2 === 0 ? 'md:ml-auto md:text-right' : ''}">
<h3 class="text-xl">{item.title}</h3> <h3 class="text-xl">{item.title}</h3>
<p class="mt-2 text-sm leading-6 text-fg-body/70">{item.description}</p> <p class="mt-2 text-sm leading-6 text-fg-body/70">{item.description}</p>
</article> </article>

View file

@ -4,7 +4,6 @@
dateKey, dateKey,
eventMatchesCategories, eventMatchesCategories,
eventOverlapsDay, eventOverlapsDay,
eventOverlapsRange,
eventRange, eventRange,
formatEventDateRange, formatEventDateRange,
getCurrentAndNextMonths, getCurrentAndNextMonths,
@ -27,12 +26,6 @@
return visibleEvents.filter((event) => eventOverlapsDay(event, date)); return visibleEvents.filter((event) => eventOverlapsDay(event, date));
} }
// On a phone the grid only shows coloured bars; this list under it says what they are.
function eventsInMonth(days: { date: Date; inMonth: boolean }[]) {
const inMonth = days.filter((day) => day.inMonth);
return visibleEvents.filter((event) => eventOverlapsRange(event, inMonth[0].date, inMonth[inMonth.length - 1].date));
}
function eventStyle(event: CalendarEventRecord) { function eventStyle(event: CalendarEventRecord) {
return `--event-color: ${event.color || '#8a9a7b'};`; return `--event-color: ${event.color || '#8a9a7b'};`;
} }
@ -49,11 +42,10 @@
return { return {
showLabel: visualStart, showLabel: visualStart,
classes: [ classes: [
// Continuing bars reach across the cell padding and the gap (p-1/p-2 + gap-1). visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3',
visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-2 sm:-ml-3', visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3',
visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-2 sm:-mr-3',
visualStart && visualEnd ? 'mx-0' : '', visualStart && visualEnd ? 'mx-0' : '',
!visualStart && !visualEnd ? '-mx-2 sm:-mx-3' : '' !visualStart && !visualEnd ? '-mx-3' : ''
].filter(Boolean).join(' ') ].filter(Boolean).join(' ')
}; };
} }
@ -65,20 +57,20 @@
</div> </div>
{#if visibleEvents.length === 0} {#if visibleEvents.length === 0}
<div class="mx-auto max-w-2xl rounded-panel border border-sage/20 bg-white/70 p-8 text-center shadow-sm"> <div class="mx-auto max-w-2xl rounded-[2rem] border border-sage/20 bg-white/70 p-8 text-center shadow-sm">
<p class="text-charcoal/70">No upcoming events are available for the selected categories.</p> <p class="text-charcoal/70">No upcoming events are available for the selected categories.</p>
</div> </div>
{:else} {:else}
<div class="isolate grid gap-8 lg:grid-cols-2"> <div class="isolate grid gap-8 lg:grid-cols-2">
{#each months as month} {#each months as month}
<div class="relative z-0 overflow-visible rounded-panel border border-sage/15 bg-white/90 p-3 shadow-sm sm:p-5 hover:z-[9000] focus-within:z-[9000]"> <div class="relative z-0 overflow-visible rounded-[2rem] border border-sage/15 bg-white/80 p-5 shadow-sm backdrop-blur hover:z-[9000] focus-within:z-[9000]">
<h3 class="font-display mb-5 text-center text-3xl text-charcoal">{month.label}</h3> <h3 class="font-display mb-5 text-center text-3xl text-charcoal">{month.label}</h3>
<div class="mb-2 grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-charcoal/45"> <div class="mb-2 grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-charcoal/45">
{#each weekdays as weekday}<div>{weekday}</div>{/each} {#each weekdays as weekday}<div>{weekday}</div>{/each}
</div> </div>
<div class="grid grid-cols-7 gap-1 overflow-visible"> <div class="grid grid-cols-7 gap-1 overflow-visible">
{#each month.days as day} {#each month.days as day}
<div class="relative min-h-14 overflow-visible rounded-xl border p-1 sm:min-h-28 sm:rounded-2xl sm:p-2 {day.inMonth ? 'border-sage/10 bg-warm/60' : 'border-sage/5 bg-warm/25'}" class:ring-2={day.isToday} class:ring-sage={day.isToday}> <div class="relative min-h-28 overflow-visible rounded-2xl border p-2 {day.inMonth ? 'border-sage/10 bg-warm/60' : 'border-sage/5 bg-warm/25'}" class:ring-2={day.isToday} class:ring-sage={day.isToday}>
<div class="mb-1 flex items-center justify-between"> <div class="mb-1 flex items-center justify-between">
<span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span> <span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span>
</div> </div>
@ -89,7 +81,7 @@
{@const segment = segmentMeta(event, day.date)} {@const segment = segmentMeta(event, day.date)}
{#if href} {#if href}
<a <a
class="group/event relative z-10 block h-2 px-2 text-left text-[0.7rem] sm:h-auto sm:py-1 font-semibold leading-tight text-white shadow-sm hover:z-[9999] hover:shadow-md focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}" class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] hover:shadow-md focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
href={href} href={href}
target={isExternalLink(href) ? '_blank' : undefined} target={isExternalLink(href) ? '_blank' : undefined}
rel={isExternalLink(href) ? 'noreferrer' : undefined} rel={isExternalLink(href) ? 'noreferrer' : undefined}
@ -97,8 +89,8 @@
aria-label={label} aria-label={label}
> >
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span> <span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
<span class="relative hidden truncate sm:block">{segment.showLabel ? event.name : '\u00a0'}</span> <span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
<span class="pointer-events-none absolute bottom-full z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl sm:group-hover/event:block sm:group-focus/event:block {day.date.getDay() >= 4 ? 'right-0' : 'left-0'}"> <span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
<strong class="block">{event.name}</strong> <strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span> <span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if} {#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
@ -106,15 +98,15 @@
</a> </a>
{:else} {:else}
<span <span
class="group/event relative z-10 block h-2 px-2 text-left text-[0.7rem] sm:h-auto sm:py-1 font-semibold leading-tight text-white shadow-sm hover:z-[9999] focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}" class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
style={eventStyle(event)} style={eventStyle(event)}
tabindex="0" tabindex="0"
role="button" role="button"
aria-label={label} aria-label={label}
> >
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span> <span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
<span class="relative hidden truncate sm:block">{segment.showLabel ? event.name : '\u00a0'}</span> <span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
<span class="pointer-events-none absolute bottom-full z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl sm:group-hover/event:block sm:group-focus/event:block {day.date.getDay() >= 4 ? 'right-0' : 'left-0'}"> <span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
<strong class="block">{event.name}</strong> <strong class="block">{event.name}</strong>
<span class="block opacity-80">{formatEventDateRange(event)}</span> <span class="block opacity-80">{formatEventDateRange(event)}</span>
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if} {#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
@ -126,25 +118,6 @@
</div> </div>
{/each} {/each}
</div> </div>
{#if eventsInMonth(month.days).length}
<ul class="mt-4 space-y-3 sm:hidden">
{#each eventsInMonth(month.days) as event}
{@const href = normalizeLink(event.link)}
<li class="flex gap-3 text-sm" style={eventStyle(event)}>
<span class="mt-1 h-3 w-3 shrink-0 rounded-full bg-[var(--event-color)]" aria-hidden="true"></span>
<div class="min-w-0">
{#if href}
<a class="font-semibold text-charcoal underline underline-offset-2" {href} target={isExternalLink(href) ? '_blank' : undefined} rel={isExternalLink(href) ? 'noreferrer' : undefined}>{event.name}</a>
{:else}
<span class="font-semibold text-charcoal">{event.name}</span>
{/if}
<span class="text-charcoal/60"> · {formatEventDateRange(event)}</span>
{#if event.description}<p class="break-words text-charcoal/70">{event.description}</p>{/if}
</div>
</li>
{/each}
</ul>
{/if}
</div> </div>
{/each} {/each}
</div> </div>

Some files were not shown because too many files have changed in this diff Show more