Compare commits

..

No commits in common. "130a21b221b689492ec623cc12fd3838ec67842d" and "fd1afc5f3afdad0a61cc1a394b344bafa792f188" have entirely different histories.

75 changed files with 3317 additions and 4491 deletions

View file

@ -1,17 +1,15 @@
# Secrets read by docker-compose.yml via ${VAR:-} substitution. # Secrets read by docker-compose.yml via ${VAR:-} substitution.
# Copy to .env at the project root and fill in. # Copy to .env at the project root and fill in.
# Stripe. The secret key and webhook secret go to PocketBase only (the shop # Stripe
# API in pocketbase/pb_hooks); the public app gets just the publishable key.
STRIPE_SECRET_KEY=sk_test_... STRIPE_SECRET_KEY=sk_test_...
PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_... PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_CURRENCY=eur STRIPE_CURRENCY=eur
# Shared by PocketBase and the public app so the public app can record # PocketBase superuser credentials (used by server-side basket/checkout/webhook APIs)
# booking-email status on orders (its only write). Generate a long random POCKETBASE_ADMIN_EMAIL=admin@example.com
# value, e.g.: openssl rand -hex 32 POCKETBASE_ADMIN_PASSWORD=changeme
INTERNAL_API_SECRET=
# Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP). # Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP).
# Leave SMTP_HOST empty in development: emails are then written to the # Leave SMTP_HOST empty in development: emails are then written to the

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.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). - **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage.
- **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).
@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb,
app-admin/ # SvelteKit admin app (serves admin.<domain>) app-admin/ # SvelteKit admin app (serves admin.<domain>)
├── src/ ├── src/
│ ├── lib/ │ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers) │ │ ├── admin/ # Admin UI components (BlockList, editors)
│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) │ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared)
│ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia │ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia
│ │ ├── types.ts # Re-exports from $shared │ │ ├── types.ts # Re-exports from $shared
@ -22,18 +22,17 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
│ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── scrollReveal.ts # Re-exports from $shared
│ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared
│ │ ├── basket.svelte.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared
│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts) │ │ └── server/ # Re-exports from $shared/server (pb-admin, basket)
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) │ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout)
│ │ ├── 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
│ │ ├── items/ # Service/product CRUD (menu label: Services & products) │ │ ├── items/ # Service/product CRUD
│ │ ├── slots/ # Bookable time slot CRUD │ │ ├── slots/ # Bookable time slot CRUD
│ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── orders/ # Order list + booking-email status/resend
│ │ ├── emails/ # Block-based booking email editor (live preview, test send) │ │ ├── emails/ # Block-based booking email editor (live preview, test send)
│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) │ │ ├── globals/ # Header/footer/colors editor
│ │ ├── backup/ # Export/import UI (calls api/export, api/import)
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin) │ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
│ │ └── api/ # upload, export, import endpoints │ │ └── api/ # upload, export, import endpoints
│ ├── hooks.server.ts # Auth guard — all routes except /login │ ├── hooks.server.ts # Auth guard — all routes except /login
@ -54,7 +53,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
│ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── scrollReveal.ts # Re-exports from $shared
│ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared
│ │ ├── basket.svelte.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared
│ │ └── server/ # shop.ts (client for PocketBase's /api/shop routes, basket cookie) + $shared/server re-exports │ │ └── server/ # Re-exports from $shared/server (pb-admin, basket); stripe.server.ts is public-only
│ ├── routes/ │ ├── routes/
│ │ ├── +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)
@ -68,8 +67,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
├── svelte.config.js # Adapter-node, runes mode forced, $shared alias ├── svelte.config.js # Adapter-node, runes mode forced, $shared alias
├── vite.config.ts # Tailwind v4 + SvelteKit plugins ├── vite.config.ts # Tailwind v4 + SvelteKit plugins
└── package.json └── package.json
pocketbase/pb_migrations/ # JS migrations, mounted at /pb_migrations; applied on PocketBase start pocketbase/pb_data/ # PocketBase data (volume-mounted)
pocketbase/pb_hooks/ # JS hooks, mounted at /pb_hooks: the shop API (/api/shop/*) + hold-sweeping cron
docker-compose.yml # app-admin + app-public + pocketbase + caddy services docker-compose.yml # app-admin + app-public + pocketbase + caddy services
Caddyfile # Subdomain-based routing Caddyfile # Subdomain-based routing
``` ```
@ -126,25 +124,14 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- `$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) - 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).
- **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.
- **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: `DM Sans` (body), `Playfair Display` (headings). - **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings).
- **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 utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.)
- 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">`.
- Setting rows in editors: `SegmentedControl` (choices) and `ColorField` (colours) — label column on the left, like the block Background picker.
- Create/edit forms open in `$lib/admin/Modal.svelte`; destructive submits use `confirmSubmit()` from `$lib/admin/confirm` (returning `false` from a handler does not cancel).
- Server actions wrap PocketBase writes in `attempt()` from `$lib/server/actions` so failures show as an error banner, not a 500.
- Editors with unsaved state use `use:enhance` + `warnOnUnsavedChanges()`.
- **Dates/times 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 - **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`. The root layout renders the admin shell (navbar, export/import, logout). 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.
- `+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
@ -159,9 +146,7 @@ DOMAIN=localhost docker compose up --build
# Public app: http://www.localhost:8080 # Public app: http://www.localhost:8080
# PocketBase: http://db.localhost:8080/_/ # PocketBase: http://db.localhost:8080/_/
# Type checking (needs node_modules in packages/shared too, or every shared # Type checking (can run on the host with node_modules present)
# file that imports a package fails with "Cannot find module")
cd packages/shared && npm install # no lockfile here, so not `npm ci`
cd app-admin && npm run check cd app-admin && npm run check
cd app-public && npm run check cd app-public && npm run check
@ -179,6 +164,4 @@ cd app-public && npm run build
- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`http://www.${DOMAIN}:8080`). - `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`http://www.${DOMAIN}:8080`).
- `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.
- `SITE_TIMEZONE` — IANA timezone for booking times in emails (default `Europe/Oslo`). - `SITE_TIMEZONE` — IANA timezone for booking times in emails (default `Europe/Oslo`).
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. - Stripe + PocketBase admin secrets are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`); if a Shop block has nothing to show it says "Nothing is available".

View file

@ -77,12 +77,6 @@ The app containers use two PocketBase URLs:
If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them.
### Migrations
`pocketbase/pb_migrations/` is mounted into the PocketBase container, which applies any new migration once when it starts (`docker compose up` / restart). The first one (`1791244800_lock_rules_dates_unique.js`) closes public sign-up on the `users` collection, makes order/basket writes superuser-only, adds `created`/`updated` dates and unique slug/key indexes. On an existing install, check the PocketBase log after restarting — if duplicate page slugs or global keys exist, the unique index is skipped with a log line. `1791331200_lock_order_lines.js` makes `order_lines` writes superuser-only (they were public).
> **Security:** every CMS collection allows writes to *any* signed-in user, so the `users` collection must not allow public sign-up. The migration enforces this; if you manage PocketBase by hand, keep `users` → API rules → Create set to superuser-only.
### Manual collection fields fallback ### Manual collection fields fallback
If schema import fails because of a PocketBase version mismatch, create these collections manually: If schema import fails because of a PocketBase version mismatch, create these collections manually:
@ -136,12 +130,10 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client). The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client).
**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that releases expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
Setup: Setup:
1. Add the Stripe vars and `INTERNAL_API_SECRET` (e.g. `openssl rand -hex 32`) from `.env.example` to `.env` at the project root. docker-compose gives the Stripe secret key and webhook secret to **PocketBase only**. 1. Add the Stripe + PocketBase-admin vars from `.env.example` to `.env` at the project root.
2. Hook changes apply on PocketBase restart (the directory is mounted read-only at `/pb_hooks`). 2. `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are the credentials of the PocketBase superuser you created — the basket/checkout/webhook APIs use a server-side admin client so collection rules can stay admin-only.
3. For local webhook testing, forward Stripe events with the CLI: 3. For local webhook testing, forward Stripe events with the CLI:
```sh ```sh
stripe listen --forward-to www.localhost:8080/api/webhooks/stripe stripe listen --forward-to www.localhost:8080/api/webhooks/stripe
@ -152,7 +144,7 @@ Setup:
## Booking emails (Brevo) ## Booking emails (Brevo)
After the Stripe webhook creates an order (in PocketBase, which hands the order data back to the public app's webhook route) the public app sends two emails through an SMTP relay (Brevo) with `nodemailer`: After the Stripe webhook creates an order it sends two emails through an SMTP relay (Brevo) with `nodemailer`:
- **Booking confirmation** to the customer, with a `booking.ics` calendar attachment for booked time slots. Reply-To is the footer email. - **Booking confirmation** to the customer, with a `booking.ics` calendar attachment for booked time slots. Reply-To is the footer email.
- **New booking alert** to the studio (the template's recipients, or the footer email). Reply-To is the customer. - **New booking alert** to the studio (the template's recipients, or the footer email). Reply-To is the customer.

View file

@ -1,150 +1,140 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap'); @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
@import 'tailwindcss'; @import 'tailwindcss';
@plugin 'daisyui' { @plugin 'daisyui' {
themes: light --default; themes: light --default;
} }
/* Admin primary/secondary come from the site's colours (Site design → @theme {
Colors) via $shared/theme, rendered in the root layout's <head> with an --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
automatically readable text colour. */ --font-serif: 'Playfair Display', Georgia, serif;
--color-warm: var(--color-bg, #faf8f5);
/* Hint text under form fields: DaisyUI's .label is nowrap, which stretched --color-charcoal: var(--color-heading, #2c2c2c);
fields to fit long hints. */ --color-sage: var(--color-primary, #8a9a7b);
.fieldset .label { --color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
white-space: normal; --color-terracotta: var(--color-accent, #c9825f);
} }
@theme { @keyframes shrink {
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif; from { scale: 0 1; }
--font-serif: 'Playfair Display', Georgia, serif; to { scale: 1 1; }
--color-warm: var(--color-bg, #faf8f5); }
--color-charcoal: var(--color-heading, #2c2c2c);
--color-sage: var(--color-primary, #8a9a7b); .delete-fill {
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000); position: absolute;
--color-terracotta: var(--color-accent, #c9825f); inset: 0;
} background: transparent;
transform-origin: left;
@keyframes shrink { }
from { scale: 0 1; }
to { scale: 1 1; } .delete-fill.animating {
} animation: shrink 1s ease-in-out forwards;
background: var(--error, #f43f5e);
.delete-fill { }
position: absolute;
inset: 0; .btn.delete-holding {
background: transparent; color: white !important;
transform-origin: left; }
}
.btn.delete-holding .text-error {
.delete-fill.animating { color: white !important;
animation: shrink 1s ease-in-out forwards; }
background: var(--error, #f43f5e);
} :root {
--fg-heading: var(--color-heading, #2c2c2c);
.btn.delete-holding { --fg-subheading: var(--color-subheading, #4a4a4a);
color: white !important; --fg-body: var(--color-text, #2c2c2c);
} background: var(--color-bg, #faf8f5);
color: var(--fg-body);
.btn.delete-holding .text-error { font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
color: white !important; }
}
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
:root { .text-fg-body { color: var(--fg-body, #2c2c2c); }
--fg-heading: var(--color-heading, #2c2c2c); .text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
--fg-subheading: var(--color-subheading, #4a4a4a); .text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
--fg-body: var(--color-text, #2c2c2c); .text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
background: var(--color-bg, #faf8f5); .text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); }
color: var(--fg-body); .text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif; .text-fg-heading { color: var(--fg-heading, #2c2c2c); }
} .text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ .text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
.text-fg-body { color: var(--fg-body, #2c2c2c); } .text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); }
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); } .text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); } .text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); } body {
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); } min-height: 100vh;
.text-fg-heading { color: var(--fg-heading, #2c2c2c); } margin: 0;
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); } background:
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); } radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); } var(--color-bg, #faf8f5);
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); } }
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); } h1,
h2,
body { h3,
min-height: 100vh; h4 {
margin: 0; font-family: 'Playfair Display', Georgia, serif;
background: color: var(--fg-heading, #2c2c2c);
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem), }
var(--color-bg, #faf8f5);
} .prose-wellness p {
margin: 0.75rem 0;
h1, line-height: 1.8;
h2, }
h3,
h4 { .prose-wellness h2 {
font-family: 'Playfair Display', Georgia, serif; margin: 1.25rem 0 0.5rem;
color: var(--fg-heading, #2c2c2c); font-size: clamp(2rem, 4vw, 3.25rem);
} line-height: 1.05;
}
.prose-wellness p {
margin: 0.75rem 0; .prose-wellness h3 {
line-height: 1.8; margin: 1rem 0 0.5rem;
} font-size: 1.6rem;
}
.prose-wellness h2 {
margin: 1.25rem 0 0.5rem; .prose-wellness ul {
font-size: clamp(2rem, 4vw, 3.25rem); list-style: disc;
line-height: 1.05; padding-left: 1.5rem;
} }
.prose-wellness h3 { .prose-wellness a {
margin: 1rem 0 0.5rem; color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
font-size: 1.6rem; text-decoration: underline;
} text-underline-offset: 3px;
}
.prose-wellness ul {
list-style: disc; /* ── Scroll-reveal animations ── */
padding-left: 1.5rem; .reveal {
} opacity: 0;
transform: translateY(30px);
.prose-wellness a { transition:
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
text-decoration: underline; transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
text-underline-offset: 3px; }
}
.reveal-visible {
/* ── Scroll-reveal animations ── */ opacity: 1;
.reveal { transform: translateY(0);
opacity: 0; }
transform: translateY(30px);
transition: /* ── Hero fade-in stagger ── */
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1), .animate-fade-in {
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1); opacity: 0;
} transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
.reveal-visible { }
opacity: 1;
transform: translateY(0); @keyframes fadeInUp {
} to {
opacity: 1;
/* ── Hero fade-in stagger ── */ transform: translateY(0);
.animate-fade-in { }
opacity: 0; }
transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; /* ── Smooth scroll ── */
} html {
scroll-behavior: smooth;
@keyframes fadeInUp { }
to {
opacity: 1;
transform: translateY(0);
}
}
/* ── Smooth scroll ── */
html {
scroll-behavior: smooth;
}

View file

@ -7,18 +7,6 @@ export const handle: Handle = async ({ event, resolve }) => {
event.request.headers.get('cookie') ?? '', event.request.headers.get('cookie') ?? '',
env.POCKETBASE_INTERNAL_URL env.POCKETBASE_INTERNAL_URL
); );
// `isValid` only checks the token's expiry locally. Refresh it against
// PocketBase so a revoked token (deleted user, changed password) logs the
// user out instead of failing later as a 500, and so active sessions slide.
if (event.locals.pb.authStore.isValid) {
const collection = event.locals.pb.authStore.record?.collectionName || '_superusers';
try {
await event.locals.pb.collection(collection).authRefresh();
} catch {
event.locals.pb.authStore.clear();
}
}
event.locals.user = event.locals.pb.authStore.record; event.locals.user = event.locals.pb.authStore.record;
const path = event.url.pathname; const path = event.url.pathname;
@ -29,17 +17,11 @@ export const handle: Handle = async ({ event, resolve }) => {
throw redirect(303, '/login'); throw redirect(303, '/login');
} }
if (isLoginRoute && isAuthed && event.request.method === 'GET') { if (isLoginRoute && isAuthed) {
throw redirect(303, '/pages'); throw redirect(303, '/pages');
} }
const response = await resolve(event); const response = await resolve(event);
// The SDK defaults to `Secure`, which browsers drop over plain HTTP — that response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
// would make login impossible with CADDY_SCHEME=http. Match the real scheme
// (event.url comes from ORIGIN behind the proxy).
response.headers.append(
'set-cookie',
event.locals.pb.authStore.exportToCookie({ sameSite: 'lax', secure: event.url.protocol === 'https:' }, 'pb_auth')
);
return response; return response;
}; };

View file

@ -1,117 +1,64 @@
<script lang="ts"> <script lang="ts">
import { onDestroy } from 'svelte'; import type { ContentBlock, EmailBlock } from '$lib/types';
import type { ContentBlock, EmailBlock } from '$lib/types'; import { blockLabels } from '$lib/admin/blockDefaults';
import { blockLabels } from '$lib/admin/blockDefaults';
let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{ blocks: (ContentBlock | EmailBlock)[];
blocks: (ContentBlock | EmailBlock)[]; labels?: Record<string, string>;
labels?: Record<string, string>; selectedId?: string;
selectedId?: string; onSelect?: (id: string) => void;
onSelect?: (id: string) => void; onDelete?: (id: string) => void;
onDelete?: (id: string) => void; onMove?: (from: number, to: number) => void;
onMove?: (from: number, to: number) => void; }>();
}>();
let dragIndex = $state<number | null>(null);
let dragIndex = $state<number | null>(null); let holdingId = $state('');
let dropIndex = $state<number | null>(null); let holdTimer: ReturnType<typeof setTimeout> | null = null;
let holdingId = $state('');
let holdTimer: ReturnType<typeof setTimeout> | null = null; function startHold(id: string) {
holdingId = id;
// Delete is press-and-hold (1s) so a stray click can't remove a block. holdTimer = setTimeout(() => {
// The parent picks the next selection. const idx = blocks.findIndex((b: ContentBlock | EmailBlock) => b.id === id);
function startHold(id: string) { onDelete(id);
endHold(); onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || '');
holdingId = id; holdingId = '';
holdTimer = setTimeout(() => { }, 1000);
holdTimer = null; }
holdingId = '';
onDelete(id); function endHold() {
}, 1000); if (holdTimer) clearTimeout(holdTimer);
} holdingId = '';
}
function endHold() { </script>
if (holdTimer) clearTimeout(holdTimer);
holdTimer = null; <div class="space-y-3">
holdingId = ''; {#each blocks as block, i (block.id)}
} <div
role="listitem"
onDestroy(endHold); class="rounded-box border bg-base-100 p-3 shadow-sm cursor-pointer"
class:border-primary={selectedId === block.id}
function drop(index: number) { draggable="true"
if (dragIndex !== null && dragIndex !== index) onMove(dragIndex, index); onclick={() => onSelect(block.id)}
dragIndex = null; ondragstart={() => (dragIndex = i)}
dropIndex = null; ondragover={(e) => e.preventDefault()}
} ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }}
>
function moveBy(index: number, delta: number) { <div class="flex items-center gap-2">
const to = index + delta; <span class="cursor-grab text-xl text-base-content/40">☰</span>
if (to >= 0 && to < blocks.length) onMove(index, to); <div class="flex-1 font-semibold">{labels[block.type] ?? block.type}</div>
} <button
</script> class="btn btn-xs btn-error btn-outline relative overflow-hidden"
class:btn-disabled={holdingId && holdingId !== block.id}
<!-- `isolate` on each row: the delete button's z-indexed layers must stay class:delete-holding={holdingId === block.id}
inside their row, or they paint over dropdowns like "Add block". --> type="button"
<ul class="space-y-2"> onpointerdown={() => startHold(block.id)}
{#each blocks as block, i (block.id)} onpointerup={endHold}
<li onpointerleave={endHold}
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:opacity-50={dragIndex === i} <span class="delete-fill" class:animating={holdingId === block.id}></span>
class:border-dashed={dropIndex === i && dragIndex !== i} <span class="relative z-10 text-error">Delete</span>
draggable="true" </button>
ondragstart={(e) => { </div>
dragIndex = i; </div>
// Firefox won't start a drag without data. {/each}
e.dataTransfer?.setData('text/plain', block.id); </div>
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
}}
ondragover={(e) => {
e.preventDefault();
dropIndex = i;
}}
ondragleave={() => dropIndex === i && (dropIndex = null)}
ondrop={(e) => {
e.preventDefault();
drop(i);
}}
ondragend={() => {
dragIndex = null;
dropIndex = null;
}}
>
<span class="cursor-grab select-none text-lg text-base-content/40" aria-hidden="true" title="Drag to reorder">⠿</span>
<button
type="button"
class="flex-1 truncate py-1 text-left font-semibold"
aria-current={selectedId === block.id ? 'true' : undefined}
onclick={() => onSelect(block.id)}
onkeydown={(e) => {
// Keyboard reordering: Alt + ↑/↓
if (e.altKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
e.preventDefault();
moveBy(i, e.key === 'ArrowUp' ? -1 : 1);
}
}}
>
{labels[block.type] ?? block.type}
</button>
<button
class="btn btn-xs btn-error btn-outline relative overflow-hidden"
class:btn-disabled={holdingId && holdingId !== block.id}
class:delete-holding={holdingId === block.id}
type="button"
title="Hold to delete"
onpointerdown={() => startHold(block.id)}
onpointerup={endHold}
onpointerleave={endHold}
onpointercancel={endHold}
onkeydown={(e) => (e.key === 'Enter' || e.key === ' ') && !e.repeat && startHold(block.id)}
onkeyup={endHold}
>
<span class="delete-fill" class:animating={holdingId === block.id}></span>
<span class="relative z-10 text-error">Delete</span>
</button>
</li>
{:else}
<li class="rounded-box border border-dashed border-base-300 p-4 text-center text-sm text-base-content/60">No blocks yet — use “Add block”.</li>
{/each}
</ul>

View file

@ -1,33 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
// Shared dialog for create/edit forms, on the native <dialog> (Escape and
// focus trapping for free). No click-outside-to-close: these hold forms,
// and a stray click shouldn't throw away what was typed.
let {
open = $bindable(false),
title,
wide = false,
children
}: { open?: boolean; title: string; wide?: boolean; children: Snippet } = $props();
let dialog: HTMLDialogElement | undefined = $state();
$effect(() => {
if (!dialog) return;
if (open && !dialog.open) dialog.showModal();
if (!open && dialog.open) dialog.close();
});
</script>
<dialog bind:this={dialog} class="modal modal-bottom sm:modal-middle" onclose={() => (open = false)}>
<div class={['modal-box', wide && 'sm:max-w-2xl']}>
<div class="mb-4 flex items-start justify-between gap-3">
<h2 class="text-2xl font-bold">{title}</h2>
<button class="btn btn-circle btn-ghost btn-sm" type="button" aria-label="Close" onclick={() => (open = false)}>✕</button>
</div>
{#if open}
{@render children()}
{/if}
</div>
</dialog>

View file

@ -1,13 +0,0 @@
/**
* `onsubmit` / `onclick` handler that asks for confirmation and cancels the
* submit if declined. (Returning `false` from a handler does NOT cancel the
* event — it has to call preventDefault.)
*
* <form onsubmit={confirmSubmit('Delete this page?')}>
* <button formaction="?/delete" onclick={confirmSubmit('Delete this event?')}>
*/
export function confirmSubmit(message: string) {
return (event: Event) => {
if (!confirm(message)) event.preventDefault();
};
}

View file

@ -1,196 +1,301 @@
<script lang="ts"> <script lang="ts">
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 ImageUploader from './ImageUploader.svelte'; import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte'; import ShopBlockEditor from './ShopBlockEditor.svelte';
import ShopBlockEditor from './ShopBlockEditor.svelte'; import CheckoutBlockEditor from './CheckoutBlockEditor.svelte';
import CheckoutBlockEditor from './CheckoutBlockEditor.svelte';
let { block, eventCategories = [], items = [], onChange = (block: ContentBlock) => {} } = $props<{
let { block, eventCategories = [], items = [], onChange = (block: ContentBlock) => {} } = $props<{ block: ContentBlock | null;
block: ContentBlock | null; eventCategories?: string[];
eventCategories?: string[]; items?: { id: string; name: string; type: string }[];
items?: { id: string; name: string; type: string }[]; onChange?: (block: ContentBlock) => void;
onChange?: (block: ContentBlock) => void; }>();
}>();
function updateData(patch: Record<string, any>) {
function updateData(patch: Record<string, any>) { if (!block) return;
if (!block) return; block = { ...block, data: { ...block.data, ...patch } };
block = { ...block, data: { ...block.data, ...patch } }; onChange(block);
onChange(block); }
}
function updateArray(key: string, index: number, patch: Record<string, any>) {
function updateArray(key: string, index: number, patch: Record<string, any>) { if (!block) return;
if (!block) return; const items = [...(block.data[key] || [])];
const items = [...(block.data[key] || [])]; items[index] = { ...items[index], ...patch };
items[index] = { ...items[index], ...patch }; updateData({ [key]: items });
updateData({ [key]: items }); }
}
function addArrayItem(key: string, item: Record<string, any>) {
function addArrayItem(key: string, item: Record<string, any>) { if (!block) return;
if (!block) return; updateData({ [key]: [...(block.data[key] || []), item] });
updateData({ [key]: [...(block.data[key] || []), item] }); }
}
function removeArrayItem(key: string, index: number) {
function removeArrayItem(key: string, index: number) { if (!block) return;
if (!block) return; updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) });
updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) }); }
}
function toggleCategory(category: string) {
function toggleCategory(category: string) { if (!block) return;
if (!block) return; const categories = block.data.categories || [];
const categories = block.data.categories || []; updateData({
updateData({ categories: categories.includes(category)
categories: categories.includes(category) ? categories.filter((item: string) => item !== category)
? categories.filter((item: string) => item !== category) : [...categories, category]
: [...categories, category] });
}); }
}
function titleCase(value: string | number) {
function updateBackground(patch: Record<string, any>) { const text = String(value);
if (!block) return; return text.charAt(0).toUpperCase() + text.slice(1);
updateData({ _background: { ...(block.data._background || {}), ...patch } }); }
} </script>
function updateForeground(patch: Record<string, any>) { {#if !block}
if (!block) return; <div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div>
updateData({ _foreground: { ...(block.data._foreground || {}), ...patch } }); {:else}
} <div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">{blockLabels[block.type as BlockType]}</h2>
const sizeLabels: Record<string, string> = { xs: 'XS', sm: 'Small', md: 'Medium', lg: 'Large' };
</script> {#if block.type === 'text'}
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
{#snippet field(label: string, value: string, onInput: (value: string) => void, placeholder = '')} {:else if block.type === 'image_text'}
<label class="fieldset"> <ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
<span class="fieldset-legend">{label}</span> <div class="form-control mt-3">
<input class="input w-full" {placeholder} {value} oninput={(e) => onInput(e.currentTarget.value)} /> <label class="label cursor-pointer justify-start gap-3">
</label> <span class="label-text">Image position</span>
{/snippet} <input type="checkbox" class="toggle toggle-primary" checked={block.data.imagePosition === 'right'} onchange={(e) => updateData({ imagePosition: e.currentTarget.checked ? 'right' : 'left' })} />
<span class="text-sm text-base-content/60">{block.data.imagePosition === 'right' ? 'Right' : 'Left'}</span>
{#if !block} </label>
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div> </div>
{:else} <div class="mt-3"><RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /></div>
<div class="rounded-box bg-base-100 p-5 shadow"> {:else if block.type === 'timeline'}
<h2 class="mb-4 text-2xl font-bold">{blockLabels[block.type as BlockType]}</h2> {#each block.data.items || [] as item, i}
<div class="rounded-box mb-3 border border-base-300 p-3">
{#if block.type === 'text'} <input class="input input-bordered mb-2 w-full" placeholder="Title" value={item.title} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })} />
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> <textarea class="textarea textarea-bordered w-full" placeholder="Description" value={item.description} oninput={(e) => updateArray('items', i, { description: e.currentTarget.value })}></textarea>
{:else if block.type === 'image_text'} <button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
<div class="space-y-4"> </div>
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} /> {/each}
<SegmentedControl label="Image position" options={['left', 'right']} value={block.data.imagePosition === 'right' ? 'right' : 'left'} onChange={(v) => updateData({ imagePosition: v })} /> <button class="btn" type="button" onclick={() => addArrayItem('items', { title: '', description: '' })}>Add item</button>
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /> {:else if block.type === 'hero'}
</div> <label class="form-control w-full">
{:else if block.type === 'timeline'} <div class="label"><span class="label-text">Heading</span></div>
<div class="space-y-3"> <input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
{#each block.data.items || [] as item, i} </label>
<div class="rounded-box border border-base-300 p-3"> <label class="form-control w-full mt-3">
<div class="mb-2 flex items-center justify-between"> <div class="label"><span class="label-text">Subheading</span></div>
<span class="text-sm font-semibold text-base-content/60">Item {i + 1}</span> <input class="input input-bordered w-full" value={block.data.subheading || ''} oninput={(e) => updateData({ subheading: e.currentTarget.value })} />
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button> </label>
</div> <label class="form-control w-full mt-3">
<input class="input mb-2 w-full" aria-label="Title" placeholder="Title" value={item.title} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })} /> <div class="label"><span class="label-text">Button label</span></div>
<textarea class="textarea w-full" aria-label="Description" placeholder="Description" value={item.description} oninput={(e) => updateArray('items', i, { description: e.currentTarget.value })}></textarea> <input class="input input-bordered w-full" value={block.data.buttonLabel || ''} oninput={(e) => updateData({ buttonLabel: e.currentTarget.value })} />
</div> </label>
{/each} <label class="form-control w-full mt-3">
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { title: '', description: '' })}>Add item</button> <div class="label"><span class="label-text">Button URL</span></div>
</div> <input class="input input-bordered w-full" value={block.data.buttonUrl || ''} oninput={(e) => updateData({ buttonUrl: e.currentTarget.value })} />
{:else if block.type === 'hero'} </label>
{@render field('Heading', block.data.heading || '', (heading) => updateData({ heading }))} {:else if block.type === 'button'}
{@render field('Subheading', block.data.subheading || '', (subheading) => updateData({ subheading }))} <div class="space-y-4">
<div class="grid gap-x-4 md:grid-cols-2"> <label class="form-control w-full">
{@render field('Button label', block.data.buttonLabel || '', (buttonLabel) => updateData({ buttonLabel }))} <div class="label"><span class="label-text">Button label</span></div>
{@render field('Button URL', block.data.buttonUrl || '', (buttonUrl) => updateData({ buttonUrl }), '/page or https://…')} <input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
</div> </label>
{:else if block.type === 'button'} <label class="form-control w-full">
<div class="grid gap-x-4 md:grid-cols-2"> <div class="label"><span class="label-text">URL</span></div>
{@render field('Button label', block.data.label || '', (label) => updateData({ label }))} <input class="input input-bordered w-full" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
{@render field('URL', block.data.href || '', (href) => updateData({ href }), '/page or https://…')} </label>
</div> <div class="form-control mt-5">
<div class="mt-4 space-y-3"> <SegmentedControl
<SegmentedControl label="Variant" options={['primary', 'secondary']} value={block.data.variant || 'primary'} onChange={(v) => updateData({ variant: v })} /> label="Variant"
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'left'} onChange={(v) => updateData({ alignment: v })} /> options={['primary', 'secondary']}
<SegmentedControl label="Size" options={['xs', 'sm', 'md', 'lg']} value={block.data.size || 'md'} onChange={(v) => updateData({ size: v })} formatLabel={(v) => sizeLabels[String(v)] || String(v)} /> value={block.data.variant || 'primary'}
<ColorField label="Color" value={block.data.color || ''} fallback="#8a9a7b" placeholder="Site primary color" onChange={(color) => updateData({ color })} /> onChange={(v) => updateData({ variant: v })}
</div> />
{:else if block.type === 'spacer'} </div>
<label class="fieldset"> <div class="form-control">
<span class="fieldset-legend">Height (px)</span> <SegmentedControl
<input label="Alignment"
type="number" options={['left', 'center', 'right']}
min="0" value={block.data.alignment || 'left'}
step="8" onChange={(v) => updateData({ alignment: v })}
class="input w-full" formatLabel={titleCase}
value={block.data.height ?? 64} />
oninput={(e) => { </div>
const height = parseInt(e.currentTarget.value, 10); <div class="form-control">
if (!Number.isNaN(height) && height >= 0) updateData({ height }); <SegmentedControl
}} label="Size"
/> options={['xs', 'sm', 'md', 'lg']}
</label> value={block.data.size || 'md'}
{:else if block.type === 'testimonials'} onChange={(v) => updateData({ size: v })}
{@render field('Section title', block.data.title || '', (title) => updateData({ title }))} formatLabel={(v) => String({ xs: 'Extra Small', sm: 'Small', md: 'Medium', lg: 'Large' }[String(v)] || v)}
<div class="mt-3 space-y-3"> />
{#each block.data.items || [] as item, i} </div>
<div class="rounded-box border border-base-300 p-3"> <div class="form-control">
<div class="mb-2 flex items-center justify-between"> <div class="flex items-center justify-between">
<span class="text-sm font-semibold text-base-content/60">Testimonial {i + 1}</span> <span class="label-text w-24">Color</span>
<button class="btn btn-ghost btn-xs text-error" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button> <div class="flex flex-1 items-center gap-2">
</div> <input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data.color || 'var(--color-primary)'} oninput={(e) => updateData({ color: e.currentTarget.value })} />
<textarea class="textarea mb-2 w-full" aria-label="Testimonial text" placeholder="Testimonial text" rows="3" value={item.text} oninput={(e) => updateArray('items', i, { text: e.currentTarget.value })}></textarea> <input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
<input class="input w-full" aria-label="Author name" placeholder="Author name" value={item.title} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })} /> </div>
</div> </div>
{/each} </div>
<button class="btn btn-sm" type="button" onclick={() => addArrayItem('items', { text: '', title: '' })}>Add testimonial</button> </div>
</div> {:else if block.type === 'spacer'}
{:else if block.type === 'upcoming_calendar'} <div class="space-y-4">
{@render field('Section title', block.data.title || '', (title) => updateData({ title }))} <label class="form-control w-full">
<div class="mt-3 rounded-box border border-base-300 p-4"> <div class="label"><span class="label-text">Height (px)</span></div>
<h3 class="font-semibold">Category filters</h3> <input type="number" class="input input-bordered w-full" value={block.data.height || 64} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 64 })} />
<p class="mb-3 text-sm text-base-content/60">Choose categories to show in this block. Leave all unselected to show every published event.</p> </label>
{#if eventCategories?.length} </div>
<div class="flex flex-wrap gap-2"> {:else if block.type === 'testimonials'}
{#each eventCategories as category} <div class="space-y-4">
<button type="button" class="btn btn-xs" class:btn-primary={(block.data.categories || []).includes(category)} aria-pressed={(block.data.categories || []).includes(category)} onclick={() => toggleCategory(category)}>{category}</button> <label class="form-control w-full">
{/each} <div class="label"><span class="label-text">Section Title</span></div>
</div> <input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
{:else} </label>
<p class="text-sm text-base-content/60">No event categories exist yet. Add categories to events under Events first.</p>
{/if} {#each block.data.items || [] as item, i}
</div> <div class="rounded-box mb-3 border border-base-300 p-4">
{:else if block.type === 'shop'} <textarea
<ShopBlockEditor {block} {items} {onChange} /> class="textarea textarea-bordered w-full mb-2"
{:else if block.type === 'checkout'} placeholder="Testimonial text"
<CheckoutBlockEditor {block} {onChange} /> rows="3"
{/if} value={item.text}
oninput={(e) => updateArray('items', i, { text: e.currentTarget.value })}
<div class="mt-6 space-y-3 rounded-box border border-base-300 p-4"> ></textarea>
<SegmentedControl label="Background" strong options={['none', 'color', 'image']} value={block.data._background?.type || 'none'} onChange={(type) => updateBackground({ type })} /> <input
class="input input-bordered w-full"
{#if block.data._background?.type === 'color'} placeholder="Author name"
<ColorField label="Color" value={block.data._background?.color || ''} fallback="#66755d" placeholder="#66755d" onChange={(color) => updateBackground({ color })} /> value={item.title}
{:else if block.data._background?.type === 'image'} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })}
<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 })} /> <button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
<SegmentedControl </div>
label="Overlay" {/each}
options={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]} <button class="btn" type="button" onclick={() => addArrayItem('items', { text: '', title: '' })}>Add testimonial</button>
value={block.data._background?.overlay ? (block.data._background?.overlayOpacity ?? 40) : 0} </div>
onChange={(v) => updateBackground({ overlay: Number(v) > 0, overlayOpacity: Number(v) })} {:else if block.type === 'upcoming_calendar'}
formatLabel={(v) => (Number(v) === 0 ? 'None' : `${v}%`)} <div class="space-y-4">
/> <label class="form-control w-full">
{/if} <div class="label"><span class="label-text">Section title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
<hr class="border-base-300" /> </label>
<SegmentedControl label="Foreground" strong options={['default', 'custom']} value={block.data._foreground?.mode || 'default'} onChange={(mode) => updateForeground({ mode })} /> <div class="rounded-box border border-base-300 p-4">
<div class="mb-3">
{#if block.data._foreground?.mode === 'custom'} <h3 class="font-semibold">Category filters</h3>
<ColorField label="Heading" value={block.data._foreground?.headingColor || ''} fallback="#2c2c2c" onChange={(headingColor) => updateForeground({ headingColor })} /> <p class="text-sm text-base-content/60">Choose categories to show in this block. Leave all unchecked to show every published event.</p>
<ColorField label="Subheading" value={block.data._foreground?.subheadingColor || ''} fallback="#4a4a4a" onChange={(subheadingColor) => updateForeground({ subheadingColor })} /> </div>
<ColorField label="Text" value={block.data._foreground?.textColor || ''} fallback="#2c2c2c" onChange={(textColor) => updateForeground({ textColor })} /> {#if eventCategories?.length}
{/if} <div class="flex flex-wrap gap-2">
</div> {#each eventCategories as category}
</div> <label class="btn btn-sm" class:btn-primary={(block.data.categories || []).includes(category)}>
{/if} <input class="hidden" type="checkbox" checked={(block.data.categories || []).includes(category)} onchange={() => toggleCategory(category)} />
{category}
</label>
{/each}
</div>
{:else}
<p class="text-sm text-base-content/60">No event categories exist yet. Create events in the Calendar admin page first.</p>
{/if}
</div>
</div>
{:else if block.type === 'shop'}
<ShopBlockEditor {block} {items} {onChange} />
{:else if block.type === 'checkout'}
<CheckoutBlockEditor {block} {onChange} />
{/if}
<div class="rounded-box border border-base-300 p-4 mt-4">
<!-- Background Type Selector -->
<div class="mb-4">
<SegmentedControl
label="Background"
labelStyle="font-weight: 1000;"
options={['none', 'color', 'image']}
value={block.data._background?.type || 'none'}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), type: v } })}
/>
</div>
{#if block.data._background?.type === 'color'}
<div class="space-y-3">
<label class="form-control">
<span class="label-text text-sm">Color</span>
<div class="flex items-center gap-2">
<input class="input input-bordered w-12 h-10 p-1 cursor-pointer" type="color" value={block.data._background?.color || '#66755d'} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#66755d or sage" value={block.data._background?.color || ''} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
</div>
</label>
</div>
{/if}
{#if block.data._background?.type === 'image'}
<div class="space-y-4">
<ImageUploader url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateData({ _background: { ...(block.data._background || {}), imageUrl: image.url, imageAlt: image.alt } })} />
<SegmentedControl
label="Attachment"
options={['scroll', 'fixed']}
value={block.data._background?.attachment || 'scroll'}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), attachment: v } })}
/>
<SegmentedControl
label="Overlay"
options={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]}
value={block.data._background?.overlayOpacity ?? 0}
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), overlay: true, overlayOpacity: v } })}
formatLabel={(v) => `${v}%`}
/>
</div>
{/if}
<hr class="border-base-content/10 my-4" />
<SegmentedControl
label="Foreground"
labelStyle="font-weight: 1000;"
options={['default', 'custom']}
value={block.data._foreground?.mode || 'default'}
onChange={(v) => updateData({ _foreground: { ...(block.data._foreground || {}), mode: v } })}
/>
{#if block.data._foreground?.mode === 'custom'}
<div class="mt-4 space-y-3">
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Heading</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.headingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.headingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
</div>
</div>
</div>
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Sub heading</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.subheadingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.subheadingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
</div>
</div>
</div>
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Text</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.textColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.textColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
</div>
</div>
</div>
</div>
{/if}
</div>
</div>
{/if}

View file

@ -15,17 +15,17 @@
</script> </script>
<div class="space-y-4"> <div class="space-y-4">
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Title</span> <div class="label"><span class="label-text">Title</span></div>
<input class="input w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} /> <input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label> </label>
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Heading</span> <div class="label"><span class="label-text">Heading</span></div>
<input class="input w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} /> <input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
</label> </label>
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Notes label</span> <div class="label"><span class="label-text">Notes label</span></div>
<input class="input w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} /> <input class="input input-bordered w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} />
</label> </label>
<p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p> <p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p>
</div> </div>

View file

@ -1,37 +0,0 @@
<script lang="ts">
// Colour setting row: label column, swatch picker, free-text value (hex or
// any CSS colour) and a clear button. Empty = "use the default".
let {
label,
value = '',
fallback = '#000000',
placeholder = 'Default',
onChange
}: {
label: string;
value?: string;
/** Swatch colour shown while the value is empty or not a hex colour. */
fallback?: string;
placeholder?: string;
onChange: (value: string) => void;
} = $props();
const isHex = (v: string) => /^#[0-9a-f]{6}$/i.test(v);
</script>
<div class="flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-medium">{label}</span>
<div class="join flex-1">
<input
class="input join-item w-12 cursor-pointer p-1"
type="color"
aria-label="{label} picker"
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}
<button class="btn join-item" type="button" aria-label="Reset {label} to default" title="Reset to default" onclick={() => onChange('')}>✕</button>
{/if}
</div>
</div>

View file

@ -4,7 +4,6 @@
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte'; import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ColorField from './ColorField.svelte';
let { block, primaryColor = '#8a9a7b', onChange = (block: EmailBlock) => {} } = $props<{ let { block, primaryColor = '#8a9a7b', onChange = (block: EmailBlock) => {} } = $props<{
block: EmailBlock | null; block: EmailBlock | null;
@ -18,10 +17,15 @@
onChange(block); onChange(block);
} }
function titleCase(value: string | number) {
const text = String(value);
return text.charAt(0).toUpperCase() + text.slice(1);
}
const autoFilled: Record<string, string> = { const autoFilled: Record<string, string> = {
booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.', booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.',
customer_details: "Filled in automatically with the customer's name, email, phone and checkout notes.", customer_details: "Filled in automatically with the customer's name, email, phone and checkout notes.",
contact_info: 'Filled in automatically from the business name, address, phone and email in Site design → Footer.' contact_info: 'Filled in automatically from the business name, address, phone and email in Globals → Footer.'
}; };
</script> </script>
@ -38,38 +42,46 @@
<div class="space-y-4"> <div class="space-y-4">
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} /> <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 })} formatLabel={titleCase} />
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Link (optional)</span> <div class="label"><span class="label-text">Link (optional)</span></div>
<input class="input w-full" placeholder="https://… or /page" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} /> <input class="input input-bordered w-full" placeholder="https://… or /page" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
</label> </label>
<p class="text-sm text-base-content/60">Images load from the public media server, so they only appear in real inboxes once the site runs on a public domain.</p> <p class="text-sm text-base-content/60">Images load from the public media server, so they only appear in real inboxes once the site runs on a public domain.</p>
</div> </div>
{:else if block.type === 'button'} {:else if block.type === 'button'}
<div class="space-y-4"> <div class="space-y-4">
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Button label</span> <div class="label"><span class="label-text">Button label</span></div>
<input class="input w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} /> <input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
</label> </label>
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">URL</span> <div class="label"><span class="label-text">URL</span></div>
<input class="input w-full" placeholder={'https://…, /page or {{site_url}}'} value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} /> <input class="input input-bordered w-full" placeholder={'https://…, /page or {{site_url}}'} value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
</label> </label>
<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 })} formatLabel={titleCase} />
<ColorField label="Color" value={block.data.color || ''} fallback={primaryColor} placeholder="Site primary color" onChange={(color) => updateData({ color })} /> <div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Color</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered h-10 w-10 cursor-pointer p-1" type="color" value={block.data.color || primaryColor} oninput={(e) => updateData({ color: e.currentTarget.value })} />
<input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
</div>
</div>
</div>
</div> </div>
{:else if block.type === 'spacer'} {:else if block.type === 'spacer'}
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Height (px)</span> <div class="label"><span class="label-text">Height (px)</span></div>
<input type="number" min="0" class="input w-full" value={block.data.height ?? 24} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 0 })} /> <input type="number" min="0" class="input input-bordered w-full" value={block.data.height ?? 24} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 0 })} />
</label> </label>
{:else if block.type === 'divider'} {:else if block.type === 'divider'}
<p class="text-base-content/60">A thin horizontal line. No settings.</p> <p class="text-base-content/60">A thin horizontal line. No settings.</p>
{:else} {:else}
<div class="space-y-3"> <div class="space-y-3">
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Section title</span> <div class="label"><span class="label-text">Section title</span></div>
<input class="input w-full" placeholder="Leave empty for no title" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} /> <input class="input input-bordered w-full" placeholder="Leave empty for no title" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label> </label>
<p class="text-sm text-base-content/60">{autoFilled[block.type]}</p> <p class="text-sm text-base-content/60">{autoFilled[block.type]}</p>
</div> </div>

View file

@ -1,107 +1,105 @@
<script lang="ts"> <script lang="ts">
import { uploadMedia } from '$lib/pb'; import { uploadMedia } from '$lib/pb';
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{ let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
url?: string; url?: string;
alt?: string; alt?: string;
onChange?: (value: { url: string; alt: string }) => void; onChange?: (value: { url: string; alt: string }) => void;
}>(); }>();
let uploading = $state(false); let uploading = $state(false);
let error = $state(''); let error = $state('');
let fileInput = $state<HTMLInputElement>(); let fileInput = $state<HTMLInputElement>();
// Local state synced from props so reactivity works reliably in Svelte 5 // Local state synced from props so reactivity works reliably in Svelte 5
let localUrl = $state(urlProp); let localUrl = $state(urlProp);
let localAlt = $state(altProp); let localAlt = $state(altProp);
$effect(() => { localUrl = urlProp; }); $effect(() => { localUrl = urlProp; });
$effect(() => { localAlt = altProp; }); $effect(() => { localAlt = altProp; });
function emitChange() { function emitChange() {
onChange({ url: localUrl, alt: localAlt }); onChange({ url: localUrl, alt: localAlt });
} }
async function handleFile(event: Event) { async function handleFile(event: Event) {
const file = (event.currentTarget as HTMLInputElement).files?.[0]; const file = (event.currentTarget as HTMLInputElement).files?.[0];
if (!file) return; if (!file) return;
uploading = true; uploading = true;
error = ''; error = '';
try { try {
const result = await uploadMedia(file); const result = await uploadMedia(file);
localUrl = result.url; localUrl = result.url;
// Keep a hand-written alt text; otherwise use the one derived from the filename. emitChange();
if (!localAlt) localAlt = result.record?.alt || ''; } catch (e) {
emitChange(); error = e instanceof Error ? e.message : 'Upload failed';
} catch (e) { console.error('Image upload error:', e);
error = e instanceof Error ? e.message : 'Upload failed'; } finally {
console.error('Image upload error:', e); uploading = false;
} finally { }
uploading = false; }
}
} function removeImage() {
localUrl = '';
function removeImage() { localAlt = '';
localUrl = ''; emitChange();
localAlt = ''; if (fileInput) fileInput.value = '';
emitChange(); }
if (fileInput) fileInput.value = ''; </script>
}
</script> <div class="grid grid-cols-[1fr_1.5fr] gap-4">
<!-- Drop zone / upload area -->
<div class="grid grid-cols-[1fr_1.5fr] gap-4"> <div
<!-- Drop zone / upload area --> 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'}"
<div role="button"
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'}" tabindex="0"
role="button" onclick={() => fileInput?.click()}
tabindex="0" onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
onclick={() => fileInput?.click()} >
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()} {#if uploading}
> <span class="loading loading-spinner loading-lg text-primary"></span>
{#if uploading} <p class="mt-3 text-sm text-base-content/60">Uploading…</p>
<span class="loading loading-spinner loading-lg text-primary"></span> {:else if localUrl}
<p class="mt-3 text-sm text-base-content/60">Uploading…</p> <div class="relative w-full">
{:else if localUrl} <img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
<div class="relative w-full"> <button
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} /> class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
<button type="button"
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1" onclick={(e) => { e.stopPropagation(); removeImage(); }}
type="button" title="Remove image"
onclick={(e) => { e.stopPropagation(); removeImage(); }} >✕</button>
title="Remove image" </div>
>✕</button> {:else}
</div> <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">
{:else} <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 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"> </svg>
<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" /> <p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
</svg> <p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p> {/if}
<p class="text-xs text-base-content/40">PNG, JPG, WebP</p> </div>
{/if}
</div> {#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div>
{#if error} {/if}
<div class="alert alert-error col-span-full text-sm">{error}</div>
{/if} <input
class="hidden"
<input type="file"
class="hidden" accept="image/*"
type="file" onchange={handleFile}
accept="image/*" disabled={uploading}
onchange={handleFile} bind:this={fileInput}
disabled={uploading} />
bind:this={fileInput}
/> <!-- URL & Alt fields -->
<div class="space-y-3">
<!-- URL & Alt fields --> <label class="form-control w-full">
<div> <div class="label"><span class="label-text">Image URL</span></div>
<label class="fieldset pt-0"> <input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} />
<span class="fieldset-legend">Image URL</span> </label>
<input class="input w-full" bind:value={localUrl} oninput={() => emitChange()} /> <label class="form-control w-full">
</label> <div class="label"><span class="label-text">Alt text</span></div>
<label class="fieldset"> <input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} />
<span class="fieldset-legend">Alt text</span> </label>
<input class="input w-full" bind:value={localAlt} oninput={() => emitChange()} /> </div>
</label> </div>
</div>
</div>

View file

@ -1,46 +1,38 @@
<script lang="ts"> <script lang="ts">
// One row of mutually exclusive options with an optional label column on let {
// the left — the standard "setting row" in the block editors (see label,
// ColorField for the colour variant; both share the label column width). options,
let { value,
label, onChange,
options, formatLabel = (v: string | number) => String(v),
value, labelStyle = '',
onChange, class: className = ''
formatLabel = (v: string | number) => { }: {
const text = String(v); label?: string;
return text.charAt(0).toUpperCase() + text.slice(1); options: (string | number)[];
}, value: string | number;
strong = false, onChange: (value: string | number) => void;
class: className = '' formatLabel?: (value: string | number) => string;
}: { labelStyle?: string;
label?: string; class?: string;
options: (string | number)[]; } = $props();
value: string | number; </script>
onChange: (value: string | number) => void;
formatLabel?: (value: string | number) => string; <div class="form-control {className}">
/** Bold label, for section-level settings like Background/Foreground. */ <div class="flex items-center justify-between">
strong?: boolean; {#if label}
class?: string; <span class="label-text w-24" style={labelStyle}>{label}</span>
} = $props(); {/if}
</script> <div class="grid flex-1" style="grid-template-columns: repeat({options.length}, 1fr)">
{#each options as option, i}
<div class="flex items-center gap-3 {className}" role="group" aria-label={label}> <button
{#if label} type="button"
<span class="w-28 shrink-0 text-sm" class:font-bold={strong} class:font-medium={!strong}>{label}</span> class="btn btn-sm {i === 0 ? 'rounded-r-none' : ''} {i === options.length - 1 ? 'rounded-l-none' : ''} {value === option ? 'btn-active' : ''}"
{/if} onclick={() => onChange(option)}
<div class="join grid flex-1" style="grid-template-columns: repeat({options.length}, minmax(0, 1fr))"> >
{#each options as option} {formatLabel(option)}
<button </button>
type="button" {/each}
class="btn btn-sm join-item px-1" </div>
class:btn-active={value === option} </div>
class:btn-primary={value === option} </div>
aria-pressed={value === option}
onclick={() => onChange(option)}
>
{formatLabel(option)}
</button>
{/each}
</div>
</div>

View file

@ -33,9 +33,9 @@
</script> </script>
<div class="space-y-4"> <div class="space-y-4">
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Title</span> <div class="label"><span class="label-text">Title</span></div>
<input class="input w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} /> <input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label> </label>
<SegmentedControl <SegmentedControl
@ -74,6 +74,6 @@
</div> </div>
</div> </div>
{:else} {:else}
<p class="text-sm text-base-content/60">Nothing to sell yet — add some under Services & products.</p> <p class="text-sm text-base-content/60">No items yet — create some under Items in the admin.</p>
{/if} {/if}
</div> </div>

View file

@ -1,15 +0,0 @@
import { beforeNavigate } from '$app/navigation';
/**
* Warn before leaving a page with unsaved edits. Call during component init.
* Form submissions are allowed through (they are the save).
*/
export function warnOnUnsavedChanges(isDirty: () => boolean) {
beforeNavigate(({ cancel, type }) => {
if (!isDirty() || type === 'form') return;
// Closing the tab/reloading: browsers only allow their own prompt,
// which `cancel()` triggers. confirm() is ignored there.
if (type === 'leave') return cancel();
if (!confirm('You have unsaved changes. Leave anyway?')) cancel();
});
}

View file

@ -1,150 +1,139 @@
import type { CalendarEventRecord, ContentBlock } from '$lib/types'; import type { CalendarEventRecord, ContentBlock } from '$lib/types';
/** /**
* The portable export format. * The portable export format.
* Images are stored as base64 data-URIs so the file is fully self-contained. * Images are stored as base64 data-URIs so the file is fully self-contained.
*/ */
export type SiteExport = { export type SiteExport = {
version: 1; version: 1;
exportedAt: string; exportedAt: string;
pages: { pages: {
slug: string; slug: string;
title: string; title: string;
blocks: ContentBlock[]; blocks: ContentBlock[];
published: boolean; published: boolean;
}[]; }[];
globals: { globals: {
key: string; key: string;
data: Record<string, unknown>; data: Record<string, unknown>;
}[]; }[];
events?: Omit<CalendarEventRecord, 'id'>[]; events?: Omit<CalendarEventRecord, 'id'>[];
/** Maps original PocketBase file URLs → base64 data-URI */ /** Maps original PocketBase file URLs → base64 data-URI */
images: Record<string, string>; images: Record<string, string>;
}; };
/** Regex to match PocketBase file URLs */ /** Regex to match PocketBase file URLs */
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g; const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
/** /**
* Extract all PocketBase image URLs from a value (recursive). * Extract all PocketBase image URLs from a value (recursive).
*/ */
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> { export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
if (typeof value === 'string') { if (typeof value === 'string') {
let match: RegExpExecArray | null; let match: RegExpExecArray | null;
const re = new RegExp(PB_FILE_RE.source, 'g'); const re = new RegExp(PB_FILE_RE.source, 'g');
while ((match = re.exec(value)) !== null) { while ((match = re.exec(value)) !== null) {
urls.add(match[0]); urls.add(match[0]);
} }
} else if (Array.isArray(value)) { } else if (Array.isArray(value)) {
for (const item of value) extractImageUrls(item, urls); for (const item of value) extractImageUrls(item, urls);
} else if (value && typeof value === 'object') { } else if (value && typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls); for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
} }
return urls; return urls;
} }
/** /**
* Replace all PocketBase URLs in a value with a placeholder key. * Replace all PocketBase URLs in a value with a placeholder key.
*/ */
export function replaceUrlsWithKeys( export function replaceUrlsWithKeys(
value: unknown, value: unknown,
urlToKey: Map<string, string> urlToKey: Map<string, string>
): unknown { ): unknown {
if (typeof value === 'string') { if (typeof value === 'string') {
let result = value; let result = value;
for (const [url, key] of urlToKey) { for (const [url, key] of urlToKey) {
result = result.replaceAll(url, `__IMG__${key}__`); result = result.replace(url, `__IMG__${key}__`);
} }
return result; return result;
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map((item) => replaceUrlsWithKeys(item, urlToKey)); return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
} }
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {}; const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) { for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = replaceUrlsWithKeys(v, urlToKey); obj[k] = replaceUrlsWithKeys(v, urlToKey);
} }
return obj; return obj;
} }
return value; return value;
} }
/** /**
* Restore image placeholders back to real URLs after import. * Restore image placeholders back to real URLs after import.
*/ */
export function restorePlaceholders( export function restorePlaceholders(
value: unknown, value: unknown,
keyToUrl: Map<string, string> keyToUrl: Map<string, string>
): unknown { ): unknown {
if (typeof value === 'string') { if (typeof value === 'string') {
let result = value; let result = value;
for (const [key, url] of keyToUrl) { for (const [key, url] of keyToUrl) {
result = result.replaceAll(`__IMG__${key}__`, url); result = result.replace(`__IMG__${key}__`, url);
} }
return result; return result;
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {
return value.map((item) => restorePlaceholders(item, keyToUrl)); return value.map((item) => restorePlaceholders(item, keyToUrl));
} }
if (value && typeof value === 'object') { if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {}; const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) { for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = restorePlaceholders(v, keyToUrl); obj[k] = restorePlaceholders(v, keyToUrl);
} }
return obj; return obj;
} }
return value; return value;
} }
/** /**
* Generate a short unique key for an image URL. * Generate a short unique key for an image URL.
*/ */
export function urlToKey(url: string): string { export function urlToKey(url: string): string {
const parts = url.split('/'); const parts = url.split('/');
const filename = parts[parts.length - 1] || 'img'; const filename = parts[parts.length - 1] || 'img';
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown'; const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
return `${id}_${filename}`; return `${id}_${filename}`;
} }
/** /**
* Fetch an image and return it as a base64 data-URI string. * Fetch an image and return it as a base64 data-URI string.
*/ */
export async function fetchImageAsBase64(url: string): Promise<string> { export async function fetchImageAsBase64(url: string): Promise<string> {
const response = await fetch(url); const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`); if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
const blob = await response.blob(); const blob = await response.blob();
const buffer = await blob.arrayBuffer(); const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer); const bytes = new Uint8Array(buffer);
let binary = ''; let binary = '';
for (let i = 0; i < bytes.length; i++) { for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]); binary += String.fromCharCode(bytes[i]);
} }
const base64 = btoa(binary); const base64 = btoa(binary);
return `data:${blob.type};base64,${base64}`; return `data:${blob.type};base64,${base64}`;
} }
/** Shape check for an uploaded export file; returns an error message or null. */ /**
export function validateSiteExport(body: unknown): string | null { * Convert a base64 data-URI back to a File object for upload.
if (!body || typeof body !== 'object') return 'The file is not a CMS export.'; */
const b = body as Partial<SiteExport>; export function dataUriToFile(dataUri: string, filename: string): File {
if (b.version !== 1) return 'Unsupported export version.'; const [header, base64] = dataUri.split(',');
if (!Array.isArray(b.pages) || !Array.isArray(b.globals)) return 'The export is missing pages or globals.'; const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
if (b.events !== undefined && !Array.isArray(b.events)) return 'The export has an invalid events list.'; const binary = atob(base64);
if (!b.images || typeof b.images !== 'object' || Array.isArray(b.images)) return 'The export is missing its images.'; const bytes = new Uint8Array(binary.length);
return null; for (let i = 0; i < binary.length; i++) {
} bytes[i] = binary.charCodeAt(i);
}
/** return new File([bytes], filename, { type: mime });
* Convert a base64 data-URI back to a File object for upload.
*/
export function dataUriToFile(dataUri: string, filename: string): File {
const [header, base64] = dataUri.split(',');
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new File([bytes], filename, { type: mime });
} }

View file

@ -1,32 +0,0 @@
import { fail } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
/**
* Human-readable message for a failed PocketBase call, including per-field
* validation errors (e.g. "slug: Must be unique.").
*/
export function pbErrorMessage(e: unknown, fallback: string): string {
if (e instanceof ClientResponseError) {
const fields = Object.entries((e.response?.data ?? {}) as Record<string, { message?: string }>)
.map(([field, detail]) => `${field}: ${detail?.message ?? 'invalid'}`)
.join('; ');
if (e.status === 404) return `${fallback} (not found — it may have been deleted).`;
if (fields) return `${fallback} ${fields}`;
if (e.status === 0) return `${fallback} The database is unreachable.`;
}
return fallback;
}
/**
* Run a PocketBase mutation inside a form action. On failure, log it and
* return `fail(400, { message })` so the page shows an error banner instead
* of SvelteKit's generic 500 page.
*/
export async function attempt<T>(fallback: string, fn: () => Promise<T>) {
try {
return { ok: true as const, value: await fn() };
} catch (e) {
console.error(`[action] ${fallback}`, e);
return { ok: false as const, failure: fail(400, { message: pbErrorMessage(e, fallback) }) };
}
}

View file

@ -1,23 +0,0 @@
import type PocketBase from 'pocketbase';
/** Lowercase, URL-safe slug: anything outside a-z, 0-9 and "-" becomes "-". */
export function normalizeSlug(value: FormDataEntryValue | null): string {
return String(value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/**
* Whether another page already uses `slug`. The `pages` collection has no
* unique index on slug, so this is checked here; a duplicate would make one
* of the two pages unreachable.
*/
export async function slugTaken(pb: PocketBase, slug: string, exceptId = ''): Promise<boolean> {
const filter = exceptId
? pb.filter('slug = {:slug} && id != {:id}', { slug, id: exceptId })
: pb.filter('slug = {:slug}', { slug });
const existing = await pb.collection('pages').getList(1, 1, { filter, fields: 'id' });
return existing.totalItems > 0;
}

View file

@ -0,0 +1 @@
export * from '$shared/server/pb-admin';

View file

@ -1,10 +1,9 @@
import { env } from '$env/dynamic/private';
import { defaultColors } from '$lib/types'; import { defaultColors } from '$lib/types';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try { try {
const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key })); const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback; return record.data || fallback;
} catch { } catch {
return fallback; return fallback;
@ -13,12 +12,5 @@ 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 = await getGlobal(locals.pb, 'colors', defaultColors); const colors = await getGlobal(locals.pb, 'colors', defaultColors);
return { return { user: locals.user, colors };
user: locals.user,
colors,
// Admin dates/times are entered and shown in the site's timezone, and
// prices in the shop currency — same settings the booking emails use.
timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
currency: (env.STRIPE_CURRENCY || 'eur').toUpperCase()
};
}; };

View file

@ -1,112 +1,127 @@
<script lang="ts"> <script lang="ts">
import '../app.css'; import '../app.css';
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import { afterNavigate } from '$app/navigation';
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 { onMount } from 'svelte';
let { children, data } = $props(); let { children, data } = $props();
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
// Routes rendered without the admin shell: the login screen, and the let importing = $state(false);
// preview iframe (which must look like the public site, not the admin).
const BARE_ROUTES = ['/login', '/preview'];
let bare = $derived(BARE_ROUTES.includes(page.url.pathname));
// The active item is marked with a tint + bar in the brand colour, never
// brand-coloured text: the site's primary may be too light to read as text.
// Sidebar navigation, grouped by what the studio is doing. Labels are
// user-facing names; hrefs keep the original route names.
const navGroups = [
{
title: 'Website',
links: [
{ href: '/pages', label: 'Pages' },
{ href: '/globals', label: 'Site design' }
]
},
{
title: 'Bookings',
links: [
{ href: '/orders', label: 'Orders' },
{ href: '/slots', label: 'Slots' },
{ href: '/items', label: 'Services & products' },
{ href: '/calendar', label: 'Events' }
]
},
{
title: 'Settings',
links: [
{ href: '/emails', label: 'Emails' },
{ href: '/backup', label: 'Backup' }
]
}
];
const isActive = (href: string) => page.url.pathname === href || page.url.pathname.startsWith(`${href}/`);
// Mobile: the drawer is open while this is true; close it after navigating.
let navOpen = $state(false);
afterNavigate(() => (navOpen = false));
// One basket store per layout instance — provided to all children // One basket store per layout instance — provided to all children
// (preview iframe block renderers). Never module-level state. // (preview iframe block renderers). Never module-level state.
// Admin doesn't have a real basket; pass null so the store starts empty. // Admin doesn't have a real basket; pass null so the store starts empty.
const basketStore = createBasketStore(null); const basketStore = createBasketStore(null);
setBasketContext(basketStore); setBasketContext(basketStore);
async function handleExport() {
try {
const res = await fetch('/api/export');
if (!res.ok) throw new Error(`Export failed (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (e) {
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
}
}
async function handleImport(event: Event) {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
importing = true;
importStatus = null;
try {
const text = await file.text();
const json = JSON.parse(text);
const res = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(json)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Import failed (${res.status})`);
}
const result = await res.json();
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
setTimeout(() => location.reload(), 1500);
} catch (e) {
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
importing = false;
input.value = '';
}
}
onMount(() => {
// Apply saved colors so the preview iframe matches the public site.
if (data.colors) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script> </script>
<svelte:head> <svelte:head>
<link rel="icon" href={favicon} /> <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). -->
{@html rootStyleTag(brandThemeVars(data.colors))}
</svelte:head> </svelte:head>
{#if bare} <div class="min-h-screen bg-base-200">
{@render children()} <div class="navbar bg-base-100 shadow-sm">
{:else} <div class="flex-1">
<div class="drawer lg:drawer-open"> <a class="btn btn-ghost text-xl" href="/pages">Massage CMS</a>
<input id="admin-nav" type="checkbox" class="drawer-toggle" bind:checked={navOpen} />
<div class="drawer-content flex min-h-screen flex-col bg-base-200">
<!-- Top bar only on small screens; the sidebar is always visible from lg up. -->
<header class="navbar sticky top-0 z-30 bg-base-100 px-2 shadow-sm lg:hidden">
<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>
</label>
<a class="ml-1 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a>
</header>
<main class="mx-auto w-full max-w-7xl flex-1 p-4 md:p-8">
{@render children()}
</main>
</div> </div>
<div class="flex-none gap-2">
<div class="drawer-side z-40"> <a class="btn btn-ghost" href="/pages">Pages</a>
<label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label> <a class="btn btn-ghost" href="/calendar">Calendar</a>
<aside class="flex min-h-full w-64 flex-col border-r border-base-300 bg-base-100"> <a class="btn btn-ghost" href="/items">Items</a>
<a class="block px-6 pt-6 pb-4 text-lg font-bold tracking-tight" href="/pages">Massage CMS</a> <a class="btn btn-ghost" href="/slots">Slots</a>
<nav class="flex-1" aria-label="Main"> <a class="btn btn-ghost" href="/orders">Orders</a>
<ul class="menu w-full gap-0.5 px-3"> <a class="btn btn-ghost" href="/emails">Emails</a>
{#each navGroups as group (group.title)} <a class="btn btn-ghost" href="/globals">Globals</a>
<li class="menu-title mt-3 first:mt-0">{group.title}</li> <div class="dropdown dropdown-end">
{#each group.links as link (link.href)} <button class="btn btn-ghost btn-sm" type="button" tabindex="0">
<li> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
<a href={link.href} class={isActive(link.href) ? 'bg-primary/20 font-semibold shadow-[inset_3px_0_0_var(--color-primary)]' : ''} aria-current={isActive(link.href) ? 'page' : undefined}>{link.label}</a> Export/Import
</li> </button>
{/each} <ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
{/each} <li><button type="button" onclick={handleExport}>Export all</button></li>
</ul> <li>
</nav> <button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
<div class="border-t border-base-300 p-4"> {importing ? 'Importing…' : 'Import'}
{#if data.user?.email} </button>
<p class="mb-2 truncate text-sm text-base-content/60" title={data.user.email}>{data.user.email}</p> </li>
{/if} </ul>
<form method="POST" action="/login?/logout"> </div>
<button class="btn btn-outline btn-sm w-full" type="submit">Log out</button> <input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
</form> <form class="inline" method="POST" action="/login?/logout">
</div> <button class="btn btn-outline btn-sm" type="submit">Logout</button>
</aside> </form>
</div> </div>
</div> </div>
{/if} {#if importStatus}
<div class="mx-auto max-w-7xl px-4 pt-2">
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
{importStatus.message}
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
</div>
</div>
{/if}
<main class="mx-auto max-w-7xl p-4 md:p-8">
{@render children()}
</main>
</div>

View file

@ -1,101 +1,98 @@
import { env } from '$env/dynamic/private'; import { env } from '$env/dynamic/private';
import { json } from '@sveltejs/kit'; import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
extractImageUrls, extractImageUrls,
fetchImageAsBase64, fetchImageAsBase64,
replaceUrlsWithKeys, replaceUrlsWithKeys,
urlToKey, urlToKey,
type SiteExport type SiteExport
} from '$lib/exportImport'; } from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar'; import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => { export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages // Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals // Fetch all globals
const globals = await locals.pb.collection('globals').getFullList(); const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals // Collect all image URLs from pages and globals
const allUrls = new Set<string>(); const allUrls = new Set<string>();
for (const page of pages) { for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url); for (const url of extractImageUrls(page)) allUrls.add(url);
} }
for (const g of globals) { for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url); for (const url of extractImageUrls(g)) allUrls.add(url);
} }
// Fetch each image as base64. Stored image URLs may use any public host // Fetch each image as base64. Stored image URLs may use any public host
// (e.g. http://localhost:8080 from before a domain migration, or // (e.g. http://localhost:8080 from before a domain migration, or
// http://db.localhost:8080 after). The app container can only reach // http://db.localhost:8080 after). The app container can only reach
// PocketBase via the internal Docker network URL, so rewrite the host // PocketBase via the internal Docker network URL, so rewrite the host
// of every matched URL to the internal base. // of every matched URL to the internal base.
const internalBase = env.POCKETBASE_INTERNAL_URL!; const internalBase = env.POCKETBASE_INTERNAL_URL!;
const images: Record<string, string> = {}; const images: Record<string, string> = {};
for (const url of allUrls) { for (const url of allUrls) {
try { try {
// Replace the host (and optional port) with the internal base. // Replace the host (and optional port) with the internal base.
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase); const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
const key = urlToKey(url); const key = urlToKey(url);
images[key] = await fetchImageAsBase64(fetchUrl); images[key] = await fetchImageAsBase64(fetchUrl);
} catch (e) { } catch (e) {
console.warn(`Could not fetch image: ${url}`, e); console.warn(`Could not fetch image: ${url}`, e);
} }
} }
// Build URL → key mapping — only for images that were actually exported. // Build URL → key mapping
// A URL whose image couldn't be fetched is left as-is rather than turned const urlToKeyMap = new Map<string, string>();
// into a placeholder the import could never resolve. for (const url of allUrls) {
const urlToKeyMap = new Map<string, string>(); urlToKeyMap.set(url, urlToKey(url));
for (const url of allUrls) { }
const key = urlToKey(url);
if (key in images) urlToKeyMap.set(url, key); // Replace URLs with placeholders in pages
} const exportPages = pages.map((p) => ({
slug: p.slug,
// Replace URLs with placeholders in pages title: p.title,
const exportPages = pages.map((p) => ({ blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
slug: p.slug, published: p.published
title: p.title, }));
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published // Replace URLs with placeholders in globals
})); const exportGlobals = globals.map((g) => ({
key: g.key,
// Replace URLs with placeholders in globals data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
const exportGlobals = globals.map((g) => ({ }));
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown> const exportEvents = events.map((record) => {
})); const event = normalizeEvent(record);
return {
const exportEvents = events.map((record) => { name: event.name,
const event = normalizeEvent(record); start: event.start,
return { end: event.end,
name: event.name, description: event.description,
start: event.start, color: event.color,
end: event.end, link: event.link,
description: event.description, categories: event.categories,
color: event.color, published: event.published,
link: event.link, allDay: event.allDay
categories: event.categories, };
published: event.published, });
allDay: event.allDay
}; const exportData: SiteExport = {
}); version: 1,
exportedAt: new Date().toISOString(),
const exportData: SiteExport = { pages: exportPages,
version: 1, globals: exportGlobals,
exportedAt: new Date().toISOString(), events: exportEvents,
pages: exportPages, images
globals: exportGlobals, };
events: exportEvents,
images return json(exportData, {
}; headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
return json(exportData, { }
headers: { });
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
}; };

View file

@ -1,146 +1,140 @@
import { env } from '$env/dynamic/public'; import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit'; import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
dataUriToFile, dataUriToFile,
restorePlaceholders, restorePlaceholders,
validateSiteExport, type SiteExport
type SiteExport } from '$lib/exportImport';
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
export const POST: RequestHandler = async ({ request, locals }) => { const body = (await request.json()) as SiteExport;
let body: SiteExport;
try { if (!body || body.version !== 1) {
body = await request.json(); throw error(400, 'Invalid or unsupported export file.');
} catch { }
throw error(400, 'The file is not valid JSON.');
} const results = {
const invalid = validateSiteExport(body); imagesUploaded: 0,
if (invalid) throw error(400, invalid); pagesImported: 0,
globalsImported: 0,
const results = { eventsImported: 0,
imagesUploaded: 0, errors: [] as string[]
pagesImported: 0, };
globalsImported: 0,
eventsImported: 0, // 1. Upload images to PocketBase media collection
errors: [] as string[] // Build a map: placeholder key → new PocketBase URL
}; const keyToUrl = new Map<string, string>();
// 1. Upload images to PocketBase media collection for (const [key, dataUri] of Object.entries(body.images)) {
// Build a map: placeholder key → new PocketBase URL try {
const keyToUrl = new Map<string, string>(); // Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
for (const [key, dataUri] of Object.entries(body.images)) { const file = dataUriToFile(dataUri, filename);
try {
// Derive a filename from the key (e.g. "abc12345_logo.png") const formData = new FormData();
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png'; formData.append('file', file);
const file = dataUriToFile(dataUri, filename); formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const formData = new FormData(); const record = await locals.pb.collection('media').create(formData);
formData.append('file', file); const publicUrl = env.PUBLIC_POCKETBASE_URL;
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
const record = await locals.pb.collection('media').create(formData); keyToUrl.set(key, newUrl);
const publicUrl = env.PUBLIC_POCKETBASE_URL; results.imagesUploaded++;
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; } catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
keyToUrl.set(key, newUrl); }
results.imagesUploaded++; }
} catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`); // 2. Import pages
} for (const page of body.pages) {
} try {
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// 2. Import pages
for (const page of body.pages) { // Try to find existing page by slug
try { let existing;
const blocks = restorePlaceholders(page.blocks, keyToUrl); try {
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
// Try to find existing page by slug } catch {
let existing; existing = null;
try { }
existing = await locals.pb.collection('pages').getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: page.slug }));
} catch { if (existing) {
existing = null; await locals.pb.collection('pages').update(existing.id, {
} title: page.title,
blocks,
if (existing) { published: page.published
await locals.pb.collection('pages').update(existing.id, { });
title: page.title, } else {
blocks, await locals.pb.collection('pages').create({
published: page.published slug: page.slug,
}); title: page.title,
} else { blocks,
await locals.pb.collection('pages').create({ published: page.published
slug: page.slug, });
title: page.title, }
blocks, results.pagesImported++;
published: page.published } catch (e) {
}); results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
} }
results.pagesImported++; }
} catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`); // 3. Import globals
} for (const g of body.globals) {
} try {
const data = restorePlaceholders(g.data, keyToUrl);
// 3. Import globals
for (const g of body.globals) { let existing;
try { try {
const data = restorePlaceholders(g.data, keyToUrl); existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
} catch {
let existing; existing = null;
try { }
existing = await locals.pb.collection('globals').getFirstListItem(locals.pb.filter('key = {:key}', { key: g.key }));
} catch { if (existing) {
existing = null; await locals.pb.collection('globals').update(existing.id, { data });
} } else {
await locals.pb.collection('globals').create({ key: g.key, data });
if (existing) { }
await locals.pb.collection('globals').update(existing.id, { data }); results.globalsImported++;
} else { } catch (e) {
await locals.pb.collection('globals').create({ key: g.key, data }); results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
} }
results.globalsImported++; }
} catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`); // 4. Import events
} for (const event of body.events || []) {
} try {
let existing;
// 4. Import events try {
for (const event of body.events || []) { existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
try { } catch {
let existing; existing = null;
try { }
existing = await locals.pb
.collection('events') const payload = {
.getFirstListItem(locals.pb.filter('name = {:name} && start = {:start}', { name: event.name, start: event.start })); name: event.name,
} catch { start: event.start,
existing = null; end: event.end || null,
} description: event.description || '',
color: event.color || '#8a9a7b',
const payload = { link: event.link || '',
name: event.name, categories: event.categories || [],
start: event.start, published: Boolean(event.published),
end: event.end || null, allDay: event.allDay !== false
description: event.description || '', };
color: event.color || '#8a9a7b',
link: event.link || '', if (existing) {
categories: event.categories || [], await locals.pb.collection('events').update(existing.id, payload);
published: Boolean(event.published), } else {
allDay: event.allDay !== false await locals.pb.collection('events').create(payload);
}; }
results.eventsImported++;
if (existing) { } catch (e) {
await locals.pb.collection('events').update(existing.id, payload); results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
} else { }
await locals.pb.collection('events').create(payload); }
}
results.eventsImported++; return json(results);
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
}; };

View file

@ -1,112 +0,0 @@
<script lang="ts">
let importStatus = $state<{ ok: boolean; message: string; errors?: string[] } | null>(null);
let importing = $state(false);
let exporting = $state(false);
let fileInput: HTMLInputElement | undefined = $state();
async function handleExport() {
exporting = true;
importStatus = null;
try {
const res = await fetch('/api/export');
if (!res.ok) throw new Error(`Export failed (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);
} catch (e) {
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
exporting = false;
}
}
async function handleImport(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
if (!confirm(`Import "${file.name}"? Pages, site design and events with the same slug/key/name will be overwritten.`)) {
input.value = '';
return;
}
importing = true;
importStatus = null;
try {
let json: unknown;
try {
json = JSON.parse(await file.text());
} catch {
throw new Error('The file is not valid JSON.');
}
const res = await fetch('/api/import', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(json)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Import failed (${res.status})`);
}
const result = await res.json();
const message = `Imported ${result.pagesImported} page(s), ${result.globalsImported} site design section(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
importStatus = result.errors?.length
? { ok: false, message: `${message} ${result.errors.length} item(s) failed:`, errors: result.errors }
: { ok: true, message };
} catch (e) {
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
} finally {
importing = false;
input.value = '';
}
}
</script>
<svelte:head><title>Backup | CMS</title></svelte:head>
<div class="mb-6">
<h1 class="text-3xl font-bold">Backup</h1>
<p class="text-base-content/60">Download the website content as a single file, or restore it from one.</p>
</div>
{#if importStatus}
<div class="alert mb-6 items-start" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok} role="status">
<div>
<p>{importStatus.message}</p>
{#if importStatus.errors?.length}
<ul class="mt-2 list-disc pl-5 text-sm">
{#each importStatus.errors as err}<li>{err}</li>{/each}
</ul>
{/if}
</div>
</div>
{/if}
<div class="grid gap-6 md:grid-cols-2">
<div class="flex flex-col rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-2 text-2xl font-bold">Export</h2>
<p class="text-sm text-base-content/60">
Pages, site design, colors and events, with their images embedded. Services, slots, orders and email templates are not included.
</p>
<div class="flex-grow"></div>
<button class="btn btn-primary mt-6 w-full" type="button" disabled={exporting} onclick={handleExport}>
{#if exporting}<span class="loading loading-spinner loading-sm"></span>{/if}
Download export
</button>
</div>
<div class="flex flex-col rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-2 text-2xl font-bold">Import</h2>
<p class="text-sm text-base-content/60">
Restores an export file. Pages with the same slug, site design sections and matching events are overwritten; everything else is kept.
</p>
<div class="flex-grow"></div>
<input class="hidden" type="file" accept=".json,application/json" bind:this={fileInput} onchange={handleImport} />
<button class="btn btn-outline mt-6 w-full" type="button" disabled={importing} onclick={() => fileInput?.click()}>
{#if importing}<span class="loading loading-spinner loading-sm"></span> Importing…{:else}Choose export file…{/if}
</button>
</div>
</div>

View file

@ -1,62 +1,54 @@
import { env } from '$env/dynamic/private'; import { fail } from '@sveltejs/kit';
import { fail } from '@sveltejs/kit'; import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar'; import type { Actions, PageServerLoad } from './$types';
import { attempt } from '$lib/server/actions';
import type { Actions, PageServerLoad } from './$types'; function eventPayload(data: FormData) {
const allDay = String(data.get('allDay')) === 'true';
function eventPayload(data: FormData) { const start = String(data.get('start') || '').trim();
const allDay = String(data.get('allDay')) === 'true'; const end = String(data.get('end') || '').trim();
const start = String(data.get('start') || '').trim(); const name = String(data.get('name') || '').trim();
const end = String(data.get('end') || '').trim();
const name = String(data.get('name') || '').trim(); return {
const timeZone = env.SITE_TIMEZONE || 'Europe/Oslo'; name,
start: dateInputToPocketBase(start, allDay),
return { end: end ? dateInputToPocketBase(end, allDay) : null,
name, description: String(data.get('description') || '').trim(),
start: dateInputToPocketBase(start, allDay, timeZone), color: String(data.get('color') || '#8a9a7b').trim(),
end: end ? dateInputToPocketBase(end, allDay, timeZone) : null, link: String(data.get('link') || '').trim(),
description: String(data.get('description') || '').trim(), categories: normalizeCategories(String(data.get('categories') || '')),
color: String(data.get('color') || '#8a9a7b').trim(), published: String(data.get('published')) === 'true',
link: String(data.get('link') || '').trim(), allDay
categories: normalizeCategories(String(data.get('categories') || '')), };
published: String(data.get('published')) === 'true', }
allDay
}; export const load: PageServerLoad = async ({ locals }) => {
} const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const events = records.map((record) => normalizeEvent(record));
export const load: PageServerLoad = async ({ locals }) => { return { events };
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); };
const events = records.map((record) => normalizeEvent(record));
return { events }; export const actions: Actions = {
}; create: async ({ request, locals }) => {
const data = await request.formData();
export const actions: Actions = { const payload = eventPayload(data);
create: async ({ request, locals }) => { if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
const data = await request.formData(); await locals.pb.collection('events').create(payload);
const payload = eventPayload(data); return { ok: true };
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); },
if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' }); update: async ({ request, locals }) => {
const result = await attempt('Could not create the event.', () => locals.pb.collection('events').create(payload)); const data = await request.formData();
if (!result.ok) return result.failure; const id = String(data.get('id') || '');
return { ok: true }; const payload = eventPayload(data);
}, if (!id) return fail(400, { message: 'Event id is required.' });
update: async ({ request, locals }) => { if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
const data = await request.formData(); await locals.pb.collection('events').update(id, payload);
const id = String(data.get('id') || ''); return { ok: true };
const payload = eventPayload(data); },
if (!id) return fail(400, { message: 'Event id is required.' }); delete: async ({ request, locals }) => {
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); const data = await request.formData();
if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' }); const id = String(data.get('id') || '');
const result = await attempt('Could not save the event.', () => locals.pb.collection('events').update(id, payload)); if (!id) return fail(400, { message: 'Event id is required.' });
if (!result.ok) return result.failure; await locals.pb.collection('events').delete(id);
return { ok: true }; return { ok: true };
}, }
delete: async ({ request, locals }) => { };
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Event id is required.' });
const result = await attempt('Could not delete the event.', () => locals.pb.collection('events').delete(id));
if (!result.ok) return result.failure;
return { ok: true };
}
};

View file

@ -1,229 +1,236 @@
<script lang="ts"> <script lang="ts">
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toZonedDatetimeInput } from '$lib/calendar'; import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm'; import type { CalendarEventRecord } from '$lib/types';
import Modal from '$lib/admin/Modal.svelte';
import type { CalendarEventRecord } from '$lib/types'; let { data, form } = $props();
let events = $derived(sortEvents(data.events || []));
let { data, form } = $props(); let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
let events = $derived(sortEvents(data.events || [])); let showEditor = $state(false);
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1)); let draft = $state<CalendarEventRecord>({
let showEditor = $state(false); id: '',
let draft = $state<CalendarEventRecord>({ name: '',
id: '', start: toDateInput(new Date().toISOString()),
name: '', end: '',
start: toDateInput(new Date().toISOString()), description: '',
end: '', color: '#8a9a7b',
description: '', link: '',
color: '#8a9a7b', categories: [],
link: '', published: false,
categories: [], allDay: true
published: false, });
allDay: true let categoryText = $state('');
});
let categoryText = $state(''); const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let month = $derived(createCalendarMonth(viewDate));
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; let action = $derived(draft.id ? '?/update' : '?/create');
let month = $derived(createCalendarMonth(viewDate, new Date(), 1)); let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let action = $derived(draft.id ? '?/update' : '?/create'); let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local'); let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toZonedDatetimeInput(draft.start, data.timezone)); let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toZonedDatetimeInput(draft.end, data.timezone));
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b))); function eventsForDay(date: Date) {
return events.filter((event) => eventOverlapsDay(event, date));
function eventsForDay(date: Date) { }
return events.filter((event) => eventOverlapsDay(event, date));
} function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
return {
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord { id: '',
return { name: '',
id: '', start,
name: '', end: '',
start, description: '',
end: '', color: '#8a9a7b',
description: '', link: '',
color: '#8a9a7b', categories: [],
link: '', published: false,
categories: [], allDay: true
published: false, };
allDay: true }
};
} function createEvent(start?: string) {
draft = emptyDraft(start);
function createEvent(start?: string) { categoryText = '';
draft = emptyDraft(start); showEditor = true;
categoryText = ''; }
showEditor = true;
} function editEvent(event: CalendarEventRecord) {
draft = structuredClone(event);
function editEvent(event: CalendarEventRecord) { categoryText = event.categories.join(', ');
draft = structuredClone(event); showEditor = true;
categoryText = event.categories.join(', '); }
showEditor = true;
} function previousMonth() {
viewDate = addMonths(viewDate, -1);
function previousMonth() { }
viewDate = addMonths(viewDate, -1);
} function nextMonth() {
viewDate = addMonths(viewDate, 1);
function nextMonth() { }
viewDate = addMonths(viewDate, 1);
} function addCategory(category: string) {
if (!category || draft.categories.includes(category)) return;
function addCategory(category: string) { draft = { ...draft, categories: [...draft.categories, category] };
if (!category || draft.categories.includes(category)) return; categoryText = draft.categories.join(', ');
draft = { ...draft, categories: [...draft.categories, category] }; }
categoryText = draft.categories.join(', ');
} function removeCategory(category: string) {
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
function removeCategory(category: string) { categoryText = draft.categories.join(', ');
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) }; }
categoryText = draft.categories.join(', ');
} function syncCategoryText(value: string) {
categoryText = value;
function syncCategoryText(value: string) { draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
categoryText = value; }
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) }; </script>
}
</script> <svelte:head><title>Calendar | CMS</title></svelte:head>
<svelte:head><title>Events | 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 class="space-y-6"> <div>
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <h1 class="text-3xl font-bold">Calendar</h1>
<div> <p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
<h1 class="text-3xl font-bold">Events</h1> </div>
<p class="text-base-content/60">Workshops and events shown in Upcoming Calendar blocks.</p> <button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
</div> {#if form?.message}<div class="alert alert-error">{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="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="rounded-box bg-base-100 p-5 shadow"> <button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3"> <h2 class="text-2xl font-bold">{month.label}</h2>
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button> <button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
<h2 class="text-2xl font-bold">{month.label}</h2> </div>
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
</div> <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}
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50"> </div>
{#each weekdays as weekday}<div>{weekday}</div>{/each} <div class="mt-2 grid grid-cols-7 gap-2">
</div> {#each month.days as day}
<div class="mt-2 grid grid-cols-7 gap-2"> <div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
{#each month.days as day} <button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}> <div class="space-y-1">
<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> {#each eventsForDay(day.date) as event}
<div class="space-y-1"> <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)}>
{#each eventsForDay(day.date) as event} <span class="block truncate">{event.name}</span>
<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="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
<span class="block truncate">{event.name}</span> </button>
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span> {/each}
</button> </div>
{/each} </div>
</div> {/each}
</div> </div>
{/each} </div>
</div>
</div> <div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-xl font-bold">All events</h2>
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="overflow-x-auto">
<h2 class="mb-4 text-xl font-bold">All events</h2> <table class="table">
<div class="overflow-x-auto"> <thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
<table class="table"> <tbody>
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead> {#each events as event}
<tbody> <tr>
{#each events as event (event.id)} <td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
<tr> <td>{formatEventDateRange(event)}</td>
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td> <td>{event.categories.join(', ')}</td>
<td>{formatEventDateRange(event)}</td> <td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
<td>{event.categories.join(', ')}</td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td> </tr>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td> {/each}
</tr> </tbody>
{:else} </table>
<tr><td colspan="5" class="py-10 text-center text-base-content/60">No events yet — click a day or “Create event”.</td></tr> </div>
{/each} </div>
</tbody> </div>
</table>
</div> {#if showEditor}
</div> <div class="fixed inset-0 z-50 bg-black/50 p-4">
</div> <div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
<Modal bind:open={showEditor} title={draft.id ? 'Edit event' : 'Create event'} wide> <h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
<form method="POST" action={action} class="space-y-1"> <button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
<input type="hidden" name="id" value={draft.id} /> </div>
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} /> <form method="POST" action={action} class="space-y-4">
<input type="hidden" name="categories" value={categoryText} /> <input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<label class="fieldset"> <input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
<span class="fieldset-legend">Name</span> <input type="hidden" name="categories" value={categoryText} />
<input class="input w-full" name="name" required bind:value={draft.name} />
</label> <label class="form-control w-full">
<div class="label"><span class="label-text">Name</span></div>
<div class="grid gap-x-4 md:grid-cols-2"> <input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
<label class="fieldset"> </label>
<span class="fieldset-legend">Start{draft.allDay ? '' : ` (${data.timezone})`}</span>
<input class="input w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} /> <div class="grid gap-4 md:grid-cols-2">
</label> <label class="form-control w-full">
<label class="fieldset"> <div class="label"><span class="label-text">Start</span></div>
<span class="fieldset-legend">End <span class="font-normal text-base-content/50">(optional)</span></span> <input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
<input class="input w-full" type={dateInputType} name="end" min={startValue} value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} /> </label>
</label> <label class="form-control w-full">
</div> <div class="label"><span class="label-text">End optional</span></div>
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
<div class="flex flex-wrap gap-6 py-2"> </label>
<label class="label cursor-pointer gap-3 text-base-content"> </div>
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
All-day event <div class="flex flex-wrap gap-4">
</label> <label class="label cursor-pointer justify-start gap-3">
<label class="label cursor-pointer gap-3 text-base-content"> <input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} /> <span class="label-text">All-day event</span>
Published </label>
</label> <label class="label cursor-pointer justify-start gap-3">
</div> <input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
<span class="label-text">Published</span>
<label class="fieldset"> </label>
<span class="fieldset-legend">Description</span> </div>
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label> <label class="form-control w-full">
<div class="label"><span class="label-text">Description</span></div>
<div class="grid gap-x-4 md:grid-cols-2"> <textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
<div class="fieldset"> </label>
<span class="fieldset-legend">Color</span>
<div class="flex gap-2"> <div class="grid gap-4 md:grid-cols-2">
<input class="input w-14 cursor-pointer p-1" type="color" aria-label="Pick color" bind:value={draft.color} /> <label class="form-control w-full">
<input class="input flex-1 font-mono" name="color" aria-label="Color value" bind:value={draft.color} /> <div class="label"><span class="label-text">Color</span></div>
</div> <div class="flex gap-2">
</div> <input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
<label class="fieldset"> <input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
<span class="fieldset-legend">Link <span class="font-normal text-base-content/50">(optional)</span></span> </div>
<input class="input w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} /> </label>
</label> <label class="form-control w-full">
</div> <div class="label"><span class="label-text">Link optional</span></div>
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
<div class="fieldset"> </label>
<label class="fieldset-legend" for="event-categories">Categories <span class="font-normal text-base-content/50">(comma-separated)</span></label> </div>
<input id="event-categories" class="input w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
{#if allCategories.length} <div class="rounded-box border border-base-300 p-4">
<div class="mt-1 flex flex-wrap gap-2"> <label class="form-control w-full">
{#each allCategories as category} <div class="label"><span class="label-text">Categories comma-separated</span></div>
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button> <input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
{/each} </label>
</div> {#if allCategories.length}
{/if} <div class="mt-3 flex flex-wrap gap-2">
</div> {#each allCategories as category}
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
<div class="modal-action justify-between"> {/each}
{#if draft.id} </div>
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit(`Delete the event "${draft.name}"?`)}>Delete</button> {/if}
{:else} </div>
<span></span>
{/if} <div class="flex justify-between gap-2 pt-2">
<div class="flex gap-2"> {#if draft.id}
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> <button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
<button class="btn btn-primary" type="submit">Save event</button> {:else}
</div> <span></span>
</div> {/if}
</form> <div class="flex gap-2">
</Modal> <button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save event</button>
</div>
</div>
</form>
</div>
</div>
{/if}

View file

@ -1,9 +1,9 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { beforeNavigate } from '$app/navigation';
import BlockList from '$lib/admin/BlockList.svelte'; import BlockList from '$lib/admin/BlockList.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 { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email'; import { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email';
import type { EmailBlock, EmailBlockType } from '$lib/types'; import type { EmailBlock, EmailBlockType } from '$lib/types';
@ -31,7 +31,9 @@
let rendered = $derived(renderEmail({ subject, blocks }, context)); let rendered = $derived(renderEmail({ subject, blocks }, context));
let isAlert = $derived(data.key === 'client_alert'); let isAlert = $derived(data.key === 'client_alert');
warnOnUnsavedChanges(() => dirty); beforeNavigate(({ cancel, type }) => {
if (dirty && type !== 'form' && !confirm('You have unsaved changes. Leave anyway?')) cancel();
});
function addBlock(type: EmailBlockType) { function addBlock(type: EmailBlockType) {
const block = createEmailBlock(type); const block = createEmailBlock(type);
@ -44,9 +46,8 @@
} }
function deleteBlock(id: string) { function deleteBlock(id: string) {
const index = blocks.findIndex((block) => block.id === id);
blocks = blocks.filter((block) => block.id !== id); blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || ''; if (selectedId === id) selectedId = blocks[0]?.id || '';
} }
function moveBlock(from: number, to: number) { function moveBlock(from: number, to: number) {
@ -99,22 +100,24 @@
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div> <div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if} {/if}
<div class="space-y-2 rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box space-y-4 bg-base-100 p-5 shadow">
<label class="label cursor-pointer gap-3 text-base-content"> <label class="label cursor-pointer justify-start gap-3">
<input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} /> <input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} />
{enabled ? 'This email is sent automatically' : 'This email is turned off'} <span class="label-text">{enabled ? 'This email is sent automatically' : 'This email is turned off'}</span>
</label> </label>
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Subject</span> <div class="label"><span class="label-text">Subject</span></div>
<input class="input w-full" name="subject" bind:value={subject} /> <input class="input input-bordered w-full" name="subject" bind:value={subject} />
</label> </label>
{#if isAlert} {#if isAlert}
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Send to (comma-separated)</span> <div class="label"><span class="label-text">Send to (comma-separated)</span></div>
<input class="input w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} /> <input class="input input-bordered w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} />
<span class="label"> <div class="label">
{#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if} <span class="label-text-alt text-base-content/60">
</span> {#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if}
</span>
</div>
</label> </label>
{:else} {:else}
<input type="hidden" name="recipients" value="" /> <input type="hidden" name="recipients" value="" />
@ -128,7 +131,7 @@
<div class="grid gap-2 sm:grid-cols-2"> <div class="grid gap-2 sm:grid-cols-2">
{#each emailPlaceholders as placeholder} {#each emailPlaceholders as placeholder}
<button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}> <button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}>
<code class="font-semibold">{`{{${placeholder.key}}}`}</code> <code class="text-primary">{`{{${placeholder.key}}}`}</code>
<span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span> <span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span>
</button> </button>
{/each} {/each}
@ -142,7 +145,7 @@
<div class="rounded-box bg-base-100 p-4 shadow"> <div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full"> <div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button> <button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-20 mt-2 w-full rounded-box bg-base-100 p-2 shadow-lg"> <ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each emailBlockTypes as type} {#each emailBlockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li> <li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li>
{/each} {/each}
@ -206,7 +209,7 @@
<input type="hidden" name="subject" value={subject} /> <input type="hidden" name="subject" value={subject} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} /> <input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<div class="flex flex-col gap-2 sm:flex-row"> <div class="flex flex-col gap-2 sm:flex-row">
<input class="input flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required /> <input class="input input-bordered flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required />
<button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button> <button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button>
</div> </div>
{#if form?.action === 'test' && form.message} {#if form?.action === 'test' && form.message}

View file

@ -1,55 +1,31 @@
import { fail } from '@sveltejs/kit'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import { ClientResponseError } from 'pocketbase'; import type { Actions, PageServerLoad } from './$types';
import { attempt } from '$lib/server/actions';
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
import type { Actions, PageServerLoad } from './$types'; try {
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
const SECTIONS = ['header', 'footer', 'colors'] as const; } catch {
return await pb.collection('globals').create({ key, data: fallback });
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { }
try { }
return await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
} catch (e) { export const load: PageServerLoad = async ({ locals }) => {
// Only create the record when it genuinely doesn't exist — any other const [header, footer, colors] = await Promise.all([
// error (PocketBase down, auth) must not create duplicates. getGlobal(locals.pb, 'header', defaultHeader),
if (e instanceof ClientResponseError && e.status === 404) { getGlobal(locals.pb, 'footer', defaultFooter),
return await pb.collection('globals').create({ key, data: fallback }); getGlobal(locals.pb, 'colors', defaultColors)
} ]);
throw e;
} // Fetch all pages for the home page selector
} const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
export const load: PageServerLoad = async ({ locals }) => { return { header, footer, colors, pages };
const [header, footer, colors] = await Promise.all([ };
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter), export const actions: Actions = {
getGlobal(locals.pb, 'colors', defaultColors) save: async ({ request, locals }) => {
]); const data = await request.formData();
const id = String(data.get('id'));
// Fetch all pages for the home page selector await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug', fields: 'id,slug,title' }); }
};
return { header, footer, colors, pages };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
const section = String(data.get('section') || '');
if (!id || !SECTIONS.includes(section as (typeof SECTIONS)[number])) {
return fail(400, { section, ok: false, message: 'Invalid request.' });
}
let value: unknown;
try {
value = JSON.parse(String(data.get('data') || ''));
} catch {
return fail(400, { section, ok: false, message: 'The settings could not be read. Nothing was saved.' });
}
const result = await attempt('Could not save.', () => locals.pb.collection('globals').update(id, { data: value }));
if (!result.ok) return fail(400, { section, ok: false, message: result.failure.data.message });
return { section, ok: true, message: 'Saved.' };
}
};

View file

@ -1,149 +1,96 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
import type { SubmitFunction } from '@sveltejs/kit'; let { data } = $props();
let header = $state(structuredClone(data.header.data));
let { data, form } = $props(); let footer = $state(structuredClone(data.footer.data));
let header = $state(structuredClone(data.header.data)); let colors = $state(structuredClone(data.colors.data));
let footer = $state(structuredClone(data.footer.data)); function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
let colors = $state(structuredClone(data.colors.data)); function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
let saving = $state(''); </script>
// Older records may predate the CTA button; the inputs below need an object.
header.ctaButton ??= { label: '', href: '' }; <svelte:head><title>Globals | CMS</title></svelte:head>
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; } <div class="mb-6">
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; } <h1 class="text-3xl font-bold">Global sections</h1>
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
const footerFields = [ </div>
{ key: 'businessName', label: 'Business name' },
{ key: 'tagline', label: 'Tagline' }, <div class="grid gap-6 xl:grid-cols-3">
{ key: 'address', label: 'Address' }, <form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
{ key: 'phone', label: 'Phone' }, <input type="hidden" name="id" value={data.header.id} />
{ key: 'email', label: 'Email', hint: 'Also used as the reply-to and alert address for booking emails.' }, <input type="hidden" name="data" value={JSON.stringify(header)} />
{ key: 'copyrightText', label: 'Copyright text' } <h2 class="mb-4 text-2xl font-bold">Header</h2>
]; <ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
<h3 class="mt-6 font-bold">Navigation</h3>
const colorFields = [ {#each header.navLinks || [] as link, i}
{ key: 'background', label: 'Background' }, <div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
{ key: 'heading', label: 'Headings' }, <input class="input input-bordered" bind:value={link.label} placeholder="Label" />
{ key: 'subheading', label: 'Subheadings' }, <input class="input input-bordered" bind:value={link.href} placeholder="Href" />
{ key: 'text', label: 'Body text' }, <button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
{ key: 'primary', label: 'Primary', hint: 'Buttons and links' }, </div>
{ key: 'accent', label: 'Accent', hint: 'Highlights' } {/each}
]; <button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
<h3 class="mt-6 font-bold">CTA button</h3>
const isHex = (value: unknown) => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value); <input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
const submit: SubmitFunction = ({ formData }) => { <h3 class="mt-6 font-bold">Home page</h3>
saving = String(formData.get('section')); <select class="select select-bordered w-full" bind:value={header.homePage}>
return async ({ update }) => { <option value="">— Select a page —</option>
// Re-run loads so the admin theme picks up saved colours immediately. {#each data.pages as page}
await update({ reset: false }); <option value={page.slug}>{page.title} [{page.slug}]</option>
saving = ''; {/each}
}; </select>
}; <p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
</script> <div class="flex-grow"></div>
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
<svelte:head><title>Site design | CMS</title></svelte:head> </form>
{#snippet status(section: string)} <form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
{#if form?.section === section && form.message} <input type="hidden" name="id" value={data.footer.id} />
<div class="alert mt-4 py-2 text-sm" class:alert-success={form.ok} class:alert-error={!form.ok} role="status">{form.message}</div> <input type="hidden" name="data" value={JSON.stringify(footer)} />
{/if} <h2 class="mb-4 text-2xl font-bold">Footer</h2>
{/snippet} {#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
<label class="form-control w-full">
{#snippet saveButton(section: string, label: string)} <div class="label"><span class="label-text">{field}</span></div>
<div class="flex-grow"></div> <input class="input input-bordered w-full" bind:value={footer[field]} />
{@render status(section)} </label>
<button class="btn btn-primary mt-4 w-full" type="submit" disabled={saving !== ''}> {/each}
{#if saving === section}<span class="loading loading-spinner loading-sm"></span>{/if} <h3 class="mt-6 font-bold">Social links</h3>
{label} {#each footer.socialLinks || [] as link, i}
</button> <div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
{/snippet} <input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
<div class="mb-6"> <button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
<h1 class="text-3xl font-bold">Site design</h1> </div>
<p class="text-base-content/60">The header, footer and colors shared by every page of the site.</p> {/each}
</div> <button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
<div class="flex-grow"></div>
<div class="grid gap-6 xl:grid-cols-3"> <button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
<form class="flex flex-col rounded-box bg-base-100 p-5 shadow" method="POST" action="?/save" use:enhance={submit}> </form>
<input type="hidden" name="id" value={data.header.id} />
<input type="hidden" name="section" value="header" /> <form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
<input type="hidden" name="data" value={JSON.stringify(header)} /> <input type="hidden" name="id" value={data.colors.id} />
<h2 class="mb-4 text-2xl font-bold">Header</h2> <input type="hidden" name="data" value={JSON.stringify(colors)} />
<h3 class="mb-2 font-bold">Logo</h3> <h2 class="mb-4 text-2xl font-bold">Colors</h2>
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} /> <p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
<h3 class="mt-6 font-bold">Navigation</h3> {#each [
{#each header.navLinks || [] as link, i} { key: 'background', label: 'Background color' },
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2"> { key: 'heading', label: 'Heading color' },
<input class="input" aria-label="Link label" bind:value={link.label} placeholder="Label" /> { key: 'subheading', label: 'Subheading color' },
<input class="input" aria-label="Link address" bind:value={link.href} placeholder="/page" /> { key: 'text', label: 'Text color' },
<button class="btn btn-error btn-outline btn-square" type="button" aria-label="Remove link" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>✕</button> { key: 'primary', label: 'Primary color (buttons, links)' },
</div> { key: 'accent', label: 'Accent color (highlights)' }
{/each} ] as { key, label }}
<button class="btn btn-sm mt-1" type="button" onclick={addHeaderLink}>Add link</button> <label class="form-control w-full mb-3">
<h3 class="mt-6 mb-2 font-bold">CTA button</h3> <div class="label"><span class="label-text">{label}</span></div>
<div class="grid grid-cols-2 gap-2"> <div class="flex gap-2">
<input class="input w-full" aria-label="Button label" bind:value={header.ctaButton.label} placeholder="Label" /> <input type="color" class="cursor-pointer" bind:value={colors[key]} />
<input class="input w-full" aria-label="Button address" bind:value={header.ctaButton.href} placeholder="/book" /> <input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
</div> </div>
<h3 class="mt-6 mb-2 font-bold">Home page</h3> </label>
<select class="select w-full" aria-label="Home page" bind:value={header.homePage}> {/each}
<option value="">— Select a page —</option> <div class="flex-grow"></div>
{#each data.pages as page (page.id)} <button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
<option value={page.slug}>{page.title} [{page.slug}]</option> </form>
{/each} </div>
</select>
<p class="mt-1 text-sm text-base-content/60">The page that "/" will redirect to.</p>
{@render saveButton('header', 'Save header')}
</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.footer.id} />
<input type="hidden" name="section" value="footer" />
<input type="hidden" name="data" value={JSON.stringify(footer)} />
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
{#each footerFields as field (field.key)}
<label class="fieldset py-1">
<span class="fieldset-legend pb-0">{field.label}</span>
{#if field.key === 'address'}
<textarea class="textarea w-full" rows="2" bind:value={footer[field.key]}></textarea>
{:else}
<input class="input w-full" type={field.key === 'email' ? 'email' : 'text'} bind:value={footer[field.key]} />
{/if}
{#if field.hint}<span class="label">{field.hint}</span>{/if}
</label>
{/each}
<h3 class="mt-6 font-bold">Social links</h3>
{#each footer.socialLinks || [] as link, i}
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
<input class="input" aria-label="Platform" bind:value={link.platform} placeholder="Platform" />
<input class="input" aria-label="Profile URL" bind:value={link.url} placeholder="https://…" />
<button class="btn btn-error btn-outline btn-square" type="button" aria-label="Remove social link" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>✕</button>
</div>
{/each}
<button class="btn btn-sm mt-1" type="button" onclick={addSocial}>Add social link</button>
{@render saveButton('footer', 'Save footer')}
</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.colors.id} />
<input type="hidden" name="section" value="colors" />
<input type="hidden" name="data" value={JSON.stringify(colors)} />
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
<p class="mb-2 text-sm text-base-content/60">Default colors for the public site. Individual blocks can override them.</p>
{#each colorFields as field (field.key)}
<div class="fieldset py-1">
<label class="fieldset-legend pb-0" for="color-{field.key}">
{field.label}{#if field.hint}<span class="font-normal text-base-content/50">— {field.hint}</span>{/if}
</label>
<div class="flex gap-2">
<input type="color" class="input w-14 cursor-pointer p-1" aria-label="{field.label} picker" value={isHex(colors[field.key]) ? colors[field.key] : '#000000'} oninput={(e) => (colors[field.key] = e.currentTarget.value)} />
<input id="color-{field.key}" type="text" class="input flex-1 font-mono text-sm" bind:value={colors[field.key]} />
</div>
</div>
{/each}
{@render saveButton('colors', 'Save colors')}
</form>
</div>

View file

@ -1,6 +1,5 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb'; import { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
@ -52,9 +51,8 @@ export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const payload = itemPayload(data); const payload = itemPayload(data);
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload)); await locals.pb.collection('items').create(payload);
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
@ -62,17 +60,15 @@ export const actions: Actions = {
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
const payload = itemPayload(data); const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload)); await locals.pb.collection('items').update(id, payload);
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
const result = await attempt('Could not delete the item — if it has slots or past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id)); await locals.pb.collection('items').delete(id);
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -1,15 +1,10 @@
<script lang="ts"> <script lang="ts">
import { uploadMedia } from '$lib/pb';
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
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('');
let fileInput: HTMLInputElement | undefined = $state();
type ItemDraft = { type ItemDraft = {
id: string; id: string;
@ -27,7 +22,7 @@
let draft = $state<ItemDraft>(emptyDraft()); let draft = $state<ItemDraft>(emptyDraft());
let action = $derived(draft.id ? '?/update' : '?/create'); let action = $derived(draft.id ? '?/update' : '?/create');
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
function emptyDraft(): ItemDraft { function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true }; return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true };
@ -35,7 +30,6 @@
function createItem() { function createItem() {
draft = emptyDraft(); draft = emptyDraft();
uploadError = '';
showEditor = true; showEditor = true;
} }
@ -52,7 +46,6 @@
duration: item.duration == null ? '' : String(item.duration), duration: item.duration == null ? '' : String(item.duration),
active: item.active active: item.active
}; };
uploadError = '';
showEditor = true; showEditor = true;
} }
@ -61,12 +54,16 @@
const file = input.files?.[0]; const file = input.files?.[0];
if (!file) return; if (!file) return;
uploading = true; uploading = true;
uploadError = '';
try { try {
const result = await uploadMedia(file); const formData = new FormData();
formData.append('file', file);
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
const result = await res.json();
draft = { ...draft, image: result.record.id, imageUrl: result.url }; draft = { ...draft, image: result.record.id, imageUrl: result.url };
} catch (err) { } catch (err) {
uploadError = err instanceof Error ? err.message : 'Upload failed.'; console.error(err);
} finally { } finally {
uploading = false; uploading = false;
input.value = ''; input.value = '';
@ -74,45 +71,41 @@
} }
</script> </script>
<svelte:head><title>Services & products | CMS</title></svelte:head> <svelte:head><title>Items | CMS</title></svelte:head>
<div class="space-y-6"> <div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col 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">Items</h1>
<p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p> <p class="text-base-content/60">Manage 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()}>Create item</button>
</div> </div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error">{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="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><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 items as item (item.id)} {#each items as item}
<tr> <tr>
<td> <td>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
{#if item.imageUrl} {#if item.imageUrl}
<img class="size-10 rounded-box object-cover" src={item.imageUrl} alt="" /> <img class="h-10 w-10 rounded-box object-cover" src={item.imageUrl} alt="" />
{:else}
<div class="size-10 rounded-box bg-base-200"></div>
{/if} {/if}
<span class="font-semibold">{item.name}</span> <span class="font-semibold">{item.name}</span>
</div> </div>
</td> </td>
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td> <td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{money.format(item.price)}</td> <td>{eur.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td> <td>{item.type === 'item' ? (item.stock ?? '—') : '—'}</td>
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td> <td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td>
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td> <td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr> </tr>
{:else}
<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>
@ -120,84 +113,87 @@
</div> </div>
</div> </div>
<Modal bind:open={showEditor} title={draft.id ? `Edit “${draft.name}”` : 'New service or product'} wide> {#if showEditor}
<form method="POST" action={action} class="space-y-1"> <div class="fixed inset-0 z-50 bg-black/50 p-4">
<input type="hidden" name="id" value={draft.id} /> <div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} /> <div class="mb-4 flex items-center justify-between gap-3">
<input type="hidden" name="image" value={draft.image} /> <h2 class="text-2xl font-bold">{draft.id ? 'Edit item' : 'Create item'}</h2>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<label class="fieldset"> <form method="POST" action={action} class="space-y-4">
<span class="fieldset-legend">Name</span> <input type="hidden" name="id" value={draft.id} />
<input class="input w-full" name="name" required bind:value={draft.name} /> <input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
</label>
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Description</span> <div class="label"><span class="label-text">Name</span></div>
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea> <input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
</label> </label>
<div class="grid gap-x-4 md:grid-cols-2"> <label class="form-control w-full">
<label class="fieldset"> <div class="label"><span class="label-text">Description</span></div>
<span class="fieldset-legend">Price ({data.currency})</span> <textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} /> </label>
</label>
<label class="fieldset">
<span class="fieldset-legend">Type</span>
<select class="select w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service (bookable)</option>
</select>
</label>
</div>
{#if draft.type === 'item'} <div class="grid gap-4 md:grid-cols-2">
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Stock</span> <div class="label"><span class="label-text">Price</span></div>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} /> <input class="input input-bordered w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label> </label>
{:else} <label class="form-control w-full">
<label class="fieldset"> <div class="label"><span class="label-text">Type</span></div>
<span class="fieldset-legend">Duration (minutes)</span> <select class="select select-bordered w-full" name="type" bind:value={draft.type}>
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} /> <option value="item">Product</option>
</label> <option value="item_with_time">Service</option>
{/if} </select>
</label>
<div class="fieldset">
<span class="fieldset-legend">Image</span>
<div class="flex items-center gap-4">
{#if draft.imageUrl}
<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> </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>
<label class="label mt-2 cursor-pointer gap-3 text-base-content"> {#if draft.type === 'item'}
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} /> <label class="form-control w-full">
Active <span class="text-base-content/60">— inactive items are hidden from the shop</span> <div class="label"><span class="label-text">Stock</span></div>
</label> <input class="input input-bordered w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
{:else}
<label class="form-control w-full">
<div class="label"><span class="label-text">Duration minutes</span></div>
<input class="input input-bordered w-full" type="number" min="0" step="1" name="duration" placeholder="60" bind:value={draft.duration} />
</label>
{/if}
<div class="modal-action justify-between"> <div class="form-control w-full">
{#if draft.id} <div class="label"><span class="label-text">Image</span></div>
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit(`Delete "${draft.name}"?`)}>Delete</button> <div class="flex items-start gap-3">
{:else} {#if draft.imageUrl}
<span></span> <img class="h-16 w-16 rounded-box object-cover" src={draft.imageUrl} alt="" />
{/if} {/if}
<div class="flex gap-2"> <div class="flex-1 space-y-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> <input class="input input-bordered w-full" name="image" placeholder="Media record id" bind:value={draft.image} />
<button class="btn btn-primary" type="submit" disabled={uploading}>Save</button> <input class="file-input file-input-bordered file-input-sm w-full" type="file" accept="image/*" disabled={uploading} onchange={onImageSelected} />
</div> <p class="text-xs text-base-content/60">
{uploading ? 'Uploading…' : 'Upload a file or paste a media record id. A media picker will replace this in a later iteration.'}
</p>
</div>
</div>
</div>
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} />
<span class="label-text">Active</span>
</label>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save item</button>
</div>
</div>
</form>
</div> </div>
</form> </div>
</Modal> {/if}

View file

@ -9,14 +9,13 @@ export const actions: Actions = {
try { try {
try { try {
await locals.pb.collection('_superusers').authWithPassword(email, password); await locals.pb.admins.authWithPassword(email, password);
} catch { } catch {
await locals.pb.collection('users').authWithPassword(email, password); await locals.pb.collection('users').authWithPassword(email, password);
} }
} catch { } catch (err) {
// One line per failed attempt; the full SDK error object is noise here. console.error('Login failed for', email, err);
console.warn('Admin login failed for', email); return fail(400, { message: 'Invalid email or password.' });
return fail(400, { email, message: 'Invalid email or password.' });
} }
throw redirect(303, '/pages'); throw redirect(303, '/pages');

View file

@ -1,38 +1,26 @@
<script lang="ts"> <script lang="ts">
let { form } = $props(); let { form } = $props();
let submitting = $state(false); </script>
</script>
<svelte:head><title>Admin login</title></svelte:head>
<svelte:head><title>Sign in | CMS</title></svelte:head>
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
<div class="grid min-h-screen place-items-center bg-base-200 p-4"> <form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
<div class="w-full max-w-sm"> <div class="card-body">
<p class="mb-6 text-center text-lg font-bold tracking-tight">Massage CMS</p> <h1 class="card-title text-3xl">Sign in</h1>
<form class="card bg-base-100 shadow-xl" method="POST" action="?/login" onsubmit={() => (submitting = true)}> <p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
<div class="card-body gap-4"> {#if form?.message}
<div> <div class="alert alert-error mt-4">{form.message}</div>
<h1 class="text-2xl font-bold">Sign in</h1> {/if}
<p class="text-sm text-base-content/60">Use your CMS account to manage the website.</p> <label class="form-control mt-4">
</div> <span class="label-text">Email</span>
{#if form?.message} <input class="input input-bordered" name="email" type="email" required />
<div class="alert alert-error text-sm" role="alert">{form.message}</div> </label>
{/if} <label class="form-control">
<fieldset class="fieldset gap-3 p-0"> <span class="label-text">Password</span>
<label class="flex flex-col gap-1"> <input class="input input-bordered" name="password" type="password" required />
<span class="fieldset-legend p-0">Email</span> </label>
<!-- svelte-ignore a11y_autofocus --> <button class="btn btn-primary mt-4" type="submit">Login</button>
<input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus /> </div>
</label> </form>
<label class="flex flex-col gap-1"> </div>
<span class="fieldset-legend p-0">Password</span>
<input class="input w-full" name="password" type="password" autocomplete="current-password" required />
</label>
</fieldset>
<button class="btn btn-primary w-full" type="submit" disabled={submitting}>
{#if submitting}<span class="loading loading-spinner loading-sm"></span>{/if}
Sign in
</button>
</div>
</form>
</div>
</div>

View file

@ -3,45 +3,38 @@ import { sendOrderEmails, type EmailKind } from '$lib/server/email';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
// Newest first. `created` comes from the 1791244800 migration; orders made // Sort by id, not 'created' — commerce collections were imported without
// before it have no date and sort last (PocketBase ids are random, so they // autodate fields. PocketBase ids are time-sortable ULIDs.
// can't be ordered chronologically). const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []);
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
// All lines in one request (previously one request per order). const orders = [];
const lineRecords = records.length for (const record of records) {
? await locals.pb const lineRecords = await locals.pb
.collection('order_lines') .collection('order_lines')
.getFullList({ sort: 'start' }) .getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) })
.catch(() => []) .catch(() => []);
: [];
const linesByOrder = new Map<string, typeof lineRecords>(); orders.push({
for (const line of lineRecords) { id: record.id,
const list = linesByOrder.get(line.order) ?? []; email: String(record.email || ''),
list.push(line); customerDetails: record.customerDetails || {},
linesByOrder.set(line.order, list); total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
lines: lineRecords.map((line) => ({
id: line.id,
name: String(line.name || ''),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : ''
}))
});
} }
const orders = records.map((record) => ({
id: record.id,
email: String(record.email || ''),
customerDetails: record.customerDetails || {},
total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
lines: (linesByOrder.get(record.id) ?? []).map((line) => ({
id: line.id,
name: String(line.name || ''),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : ''
}))
}));
return { orders }; return { orders };
}; };

View file

@ -1,12 +1,11 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { formatDateTime } from '$lib/calendar';
let { data, form } = $props(); let { data, form } = $props();
let orders = $derived(data.orders || []); let orders = $derived(data.orders || []);
let resending = $state(''); let resending = $state('');
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
</script> </script>
{#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)} {#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)}
@ -24,7 +23,7 @@
> >
<input type="hidden" name="orderId" value={order.id} /> <input type="hidden" name="orderId" value={order.id} />
<input type="hidden" name="kind" value={kind} /> <input type="hidden" name="kind" value={kind} />
<span class="badge badge-sm" class:badge-success={sentAt} class:badge-ghost={!sentAt} title={sentAt ? `Sent ${formatDateTime(sentAt, data.timezone)}` : 'Not sent'}> <span class="badge badge-sm" class:badge-success={sentAt} class:badge-ghost={!sentAt} title={sentAt ? new Date(sentAt).toLocaleString() : 'Not sent'}>
{label}: {sentAt ? 'sent' : 'not sent'} {label}: {sentAt ? 'sent' : 'not sent'}
</span> </span>
<button class="btn btn-ghost btn-xs" type="submit" disabled={resending !== ''}> <button class="btn btn-ghost btn-xs" type="submit" disabled={resending !== ''}>
@ -38,14 +37,14 @@
<div class="space-y-6"> <div class="space-y-6">
<div> <div>
<h1 class="text-3xl font-bold">Orders</h1> <h1 class="text-3xl font-bold">Orders</h1>
<p class="text-base-content/60">Bookings and purchases from the shop.</p> <p class="text-base-content/60">Confirmed bookings and purchases.</p>
</div> </div>
{#if orders.length === 0} {#if orders.length === 0}
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">No orders yet.</div> <div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">No orders yet.</div>
{/if} {/if}
{#each orders as order (order.id)} {#each orders as order}
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box bg-base-100 p-5 shadow">
<div class="flex flex-col justify-between gap-3 md:flex-row md:items-center"> <div class="flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div> <div>
@ -53,7 +52,7 @@
<p class="text-sm text-base-content/60"> <p class="text-sm text-base-content/60">
{order.email} {order.email}
{#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if} {#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if}
{#if order.created} · {formatDateTime(order.created, data.timezone)}{/if} {#if order.created} · {new Date(order.created).toLocaleString()}{/if}
</p> </p>
</div> </div>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
@ -63,16 +62,16 @@
class:badge-warning={order.status === 'pending'} class:badge-warning={order.status === 'pending'}
class:badge-error={order.status === 'refunded'} class:badge-error={order.status === 'refunded'}
>{order.status}</span> >{order.status}</span>
<span class="text-lg font-bold">{money.format(order.total)}</span> <span class="text-lg font-bold">{eur.format(order.total)}</span>
</div> </div>
</div> </div>
<ul class="mt-4 space-y-1 border-t border-base-300 pt-4"> <ul class="mt-4 space-y-1 border-t border-base-300 pt-4">
{#each order.lines as line} {#each order.lines as line}
<li> <li>
{line.quantity}× {line.name} — {money.format(line.price)} {line.quantity}× {line.name} — {eur.format(line.price)}
{#if line.lineType === 'slot' && line.start} {#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}</span> <span class="block text-sm text-base-content/60">{new Date(line.start).toLocaleString()}</span>
{/if} {/if}
</li> </li>
{/each} {/each}

View file

@ -1,39 +1,29 @@
import { fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import { attempt } from '$lib/server/actions'; import type { Actions, PageServerLoad } from './$types';
import { normalizeSlug, slugTaken } from '$lib/server/pages';
import type { Actions, PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ locals }) => {
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
export const load: PageServerLoad = async ({ locals }) => { return { pages };
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); };
return { pages };
}; export const actions: Actions = {
create: async ({ request, locals }) => {
export const actions: Actions = { const data = await request.formData();
create: async ({ request, locals }) => { const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
const data = await request.formData(); const title = String(data.get('title') || '').trim();
const slug = normalizeSlug(data.get('slug')); if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
const title = String(data.get('title') || '').trim();
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
if (await slugTaken(locals.pb, slug)) return fail(400, { message: `A page with the slug "${slug}" already exists.` }); throw redirect(303, `/pages/${slug}`);
},
const result = await attempt('Could not create the page.', () => toggle: async ({ request, locals }) => {
locals.pb.collection('pages').create({ slug, title, blocks: [], published: false }) const data = await request.formData();
); await locals.pb.collection('pages').update(String(data.get('id')), {
if (!result.ok) return result.failure; published: String(data.get('published')) !== 'true'
throw redirect(303, `/pages/${slug}`); });
}, },
toggle: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const result = await attempt('Could not change the publish status.', () => await locals.pb.collection('pages').delete(String(data.get('id')));
locals.pb.collection('pages').update(String(data.get('id')), { }
published: String(data.get('published')) !== 'true' };
})
);
if (!result.ok) return result.failure;
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const result = await attempt('Could not delete the page.', () => locals.pb.collection('pages').delete(String(data.get('id'))));
if (!result.ok) return result.failure;
}
};

View file

@ -1,79 +1,65 @@
<script lang="ts"> <script lang="ts">
import { env } from '$env/dynamic/public'; let { data, form } = $props();
import { confirmSubmit } from '$lib/admin/confirm'; </script>
import Modal from '$lib/admin/Modal.svelte';
<svelte:head><title>Pages | CMS</title></svelte:head>
let { data, form } = $props();
let showCreate = $state(false); <div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div>
const siteUrl = (env.PUBLIC_SITE_URL || '').replace(/\/$/, ''); <h1 class="text-3xl font-bold">Pages</h1>
const publicUrl = (slug: string) => `${siteUrl}/${slug === 'home' ? '' : slug}`; <p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
</script> </div>
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
<svelte:head><title>Pages | CMS</title></svelte:head> </div>
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center"> {#if form?.message}
<div> <div class="alert alert-error mb-4">{form.message}</div>
<h1 class="text-3xl font-bold">Pages</h1> {/if}
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
</div> <div class="overflow-x-auto rounded-box bg-base-100 shadow">
<button class="btn btn-primary" type="button" onclick={() => (showCreate = true)}>New page</button> <table class="table">
</div> <thead>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
{#if form?.message} </thead>
<div class="alert alert-error mb-4" role="alert">{form.message}</div> <tbody>
{/if} {#each data.pages as page}
<tr>
<div class="overflow-x-auto rounded-box bg-base-100 shadow"> <td class="font-mono">{page.slug}</td>
<table class="table"> <td>{page.title}</td>
<thead> <td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr> <td class="flex justify-end gap-2">
</thead> <a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
<tbody> <a class="btn btn-sm" href={`${import.meta.env.VITE_PUBLIC_SITE_URL}/${page.slug === 'home' ? '' : page.slug}`} target="_blank">Preview</a>
{#each data.pages as page (page.id)} <form method="POST" action="?/toggle">
<tr> <input type="hidden" name="id" value={page.id} />
<td class="font-mono">{page.slug}</td> <input type="hidden" name="published" value={page.published} />
<td>{page.title}</td> <button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td> </form>
<td> <form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
<div class="flex flex-wrap justify-end gap-2"> <input type="hidden" name="id" value={page.id} />
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a> <button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
{#if siteUrl && page.published} </form>
<a class="btn btn-sm" href={publicUrl(page.slug)} target="_blank" rel="noopener" title="Open on the live site">View</a> </td>
{/if} </tr>
<form method="POST" action="?/toggle"> {/each}
<input type="hidden" name="id" value={page.id} /> </tbody>
<input type="hidden" name="published" value={page.published} /> </table>
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button> </div>
</form>
<form method="POST" action="?/delete" onsubmit={confirmSubmit(`Delete the page "${page.title}"? This cannot be undone.`)}> <dialog id="new-page" class="modal">
<input type="hidden" name="id" value={page.id} /> <form class="modal-box" method="POST" action="?/create">
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button> <h2 class="text-2xl font-bold">Create page</h2>
</form> <label class="form-control w-full mt-4">
</div> <div class="label"><span class="label-text">Slug</span></div>
</td> <input class="input input-bordered w-full" name="slug" placeholder="about" required />
</tr> </label>
{:else} <label class="form-control w-full">
<tr><td colspan="4" class="py-10 text-center text-base-content/60">No pages yet — create your first one.</td></tr> <div class="label"><span class="label-text">Title</span></div>
{/each} <input class="input input-bordered w-full" name="title" placeholder="About" required />
</tbody> </label>
</table> <div class="modal-action">
</div> <button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
<button class="btn btn-primary" type="submit">Create</button>
<Modal bind:open={showCreate} title="Create page"> </div>
<form method="POST" action="?/create" class="space-y-1"> </form>
<label class="fieldset"> </dialog>
<span class="fieldset-legend">Title</span>
<input class="input w-full" name="title" placeholder="About" required />
</label>
<label class="fieldset">
<span class="fieldset-legend">Slug</span>
<input class="input w-full font-mono" name="slug" placeholder="about" required pattern="[A-Za-z0-9 _\-]+" />
<span class="label">The page address: {siteUrl || 'your site'}/<em>slug</em></span>
</label>
<div class="modal-action">
<button class="btn" type="button" onclick={() => (showCreate = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Create</button>
</div>
</form>
</Modal>

View file

@ -1,56 +1,30 @@
import { error, fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase'; import { extractCategories, normalizeEvent } from '$lib/calendar';
import { extractCategories, normalizeEvent } from '$lib/calendar'; import type { Actions, PageServerLoad } from './$types';
import { attempt } from '$lib/server/actions';
import { normalizeSlug, slugTaken } from '$lib/server/pages'; export const load: PageServerLoad = async ({ params, locals }) => {
import type { Actions, PageServerLoad } from './$types'; const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
export const load: PageServerLoad = async ({ params, locals }) => { const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
const page = await locals.pb const items = await locals.pb
.collection('pages') .collection('items')
.getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: params.slug })) .getFullList({ sort: 'name' })
.catch((e) => { .then((records) => records.map(({ id, name, type }) => ({ id, name, type })))
if (e instanceof ClientResponseError && e.status === 404) throw error(404, `No page with the slug "${params.slug}".`); .catch(() => []);
throw e; return { page, eventCategories, items };
}); };
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event))); export const actions: Actions = {
const items = await locals.pb save: async ({ request, locals }) => {
.collection('items') const data = await request.formData();
.getFullList({ sort: 'name' }) const id = String(data.get('id'));
.then((records) => records.map(({ id, name, type }) => ({ id, name, type }))) const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
.catch(() => []); const title = String(data.get('title') || '').trim();
return { page, eventCategories, items }; const blocks = JSON.parse(String(data.get('blocks') || '[]'));
}; const publish = String(data.get('publish')) === 'true';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
export const actions: Actions = {
save: async ({ params, request, locals }) => { await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
const data = await request.formData(); throw redirect(303, `/pages/${slug}`);
const id = String(data.get('id')); }
const slug = normalizeSlug(data.get('slug')); };
const title = String(data.get('title') || '').trim();
const publish = data.get('intent') === 'publish';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
let blocks: unknown;
try {
blocks = JSON.parse(String(data.get('blocks') || '[]'));
} catch {
return fail(400, { message: 'The block data could not be read. Nothing was saved.' });
}
if (!Array.isArray(blocks)) return fail(400, { message: 'The block data could not be read. Nothing was saved.' });
if (slug !== params.slug && (await slugTaken(locals.pb, slug, id))) {
return fail(400, { message: `A page with the slug "${slug}" already exists.` });
}
const result = await attempt('Could not save the page.', () =>
locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) })
);
if (!result.ok) return result.failure;
// The URL contains the slug, so a rename has to navigate.
if (slug !== params.slug) throw redirect(303, `/pages/${slug}`);
return { ok: true, message: publish ? 'Saved and published.' : 'Draft saved.' };
}
};

View file

@ -1,156 +1,104 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import BlockList from '$lib/admin/BlockList.svelte';
import BlockList from '$lib/admin/BlockList.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 type { ContentBlock } from '$lib/types';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
import type { ContentBlock } from '$lib/types'; let { data, form } = $props();
let page = $state(data.page);
let { data, form } = $props(); let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
// Local editable copies; the server data is only the starting point. let selectedId = $state(blocks[0]?.id || '');
let slug = $state(data.page.slug); let previewMode = $state<'desktop' | 'mobile'>('desktop');
let title = $state(data.page.title); let showPreview = $state(false);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
let selectedId = $state(data.page.blocks?.[0]?.id || ''); let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
let published = $derived(data.page.published);
let previewMode = $state<'desktop' | 'mobile'>('desktop'); function addBlock(type: keyof typeof blockLabels) {
let showPreview = $state(false); const block = createBlock(type);
let saving = $state<'' | 'save' | 'publish'>(''); blocks = [...blocks, block];
selectedId = block.id;
const serialize = () => JSON.stringify({ slug, title, blocks }); }
let savedSnapshot = $state(serialize());
let dirty = $derived(serialize() !== savedSnapshot); function updateBlock(updated: ContentBlock) {
warnOnUnsavedChanges(() => dirty); blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
}
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
function deleteBlock(id: string) {
function addBlock(type: keyof typeof blockLabels) { blocks = blocks.filter((block) => block.id !== id);
const block = createBlock(type); if (selectedId === id) selectedId = blocks[0]?.id || '';
blocks = [...blocks, block]; }
selectedId = block.id;
(document.activeElement as HTMLElement | null)?.blur(); // close the dropdown function moveBlock(from: number, to: number) {
} const copy = [...blocks];
const [item] = copy.splice(from, 1);
function updateBlock(updated: ContentBlock) { copy.splice(to, 0, item);
blocks = blocks.map((block) => (block.id === updated.id ? updated : block)); blocks = copy;
} }
function deleteBlock(id: string) { function openPreview() {
const index = blocks.findIndex((block) => block.id === id); sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
blocks = blocks.filter((block) => block.id !== id); showPreview = true;
if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || ''; }
}
function markPublish(event: MouseEvent) {
function moveBlock(from: number, to: number) { const form = (event.currentTarget as HTMLButtonElement).form;
const copy = [...blocks]; const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
const [item] = copy.splice(from, 1); if (input) input.value = 'true';
copy.splice(to, 0, item); }
blocks = copy; </script>
}
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
function openPreview() {
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks)); <form method="POST" action="?/save" class="space-y-6">
showPreview = true; <input type="hidden" name="id" value={page.id} />
} <input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
</script> <input type="hidden" name="publish" value="false" />
<svelte:head><title>Edit {title || 'page'} | CMS</title></svelte:head> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<svelte:window onkeydown={(e) => showPreview && e.key === 'Escape' && (showPreview = false)} /> <h1 class="text-3xl font-bold">Edit page</h1>
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
<form </div>
method="POST" <div class="flex flex-wrap gap-2">
action="?/save" <button class="btn" type="button" onclick={openPreview}>Preview</button>
class="space-y-6" <button class="btn btn-outline" type="submit">Save draft</button>
use:enhance={({ submitter }) => { <button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
saving = submitter?.getAttribute('value') === 'publish' ? 'publish' : 'save'; </div>
return async ({ result, update }) => { </div>
await update({ reset: false });
saving = ''; {#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
if (result.type === 'success' || result.type === 'redirect') {
// Adopt what the server stored (it normalises the slug). <div class="grid gap-4 md:grid-cols-2">
slug = data.page.slug; <label class="form-control w-full"><div class="label"><span class="label-text">Slug</span></div><input class="input input-bordered w-full" name="slug" bind:value={page.slug} /></label>
title = data.page.title; <label class="form-control w-full"><div class="label"><span class="label-text">Title</span></div><input class="input input-bordered w-full" name="title" bind:value={page.title} /></label>
savedSnapshot = serialize(); </div>
}
}; <div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
}} <aside class="space-y-4">
> <div class="rounded-box bg-base-100 p-4 shadow">
<input type="hidden" name="id" value={data.page.id} /> <div class="dropdown w-full">
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} /> <button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> {#each blockTypes as type}
<div> <li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
<a class="link link-hover text-sm text-base-content/60" href="/pages">← Pages</a> {/each}
<div class="flex flex-wrap items-center gap-3"> </ul>
<h1 class="text-3xl font-bold">Edit page</h1> </div>
<span class="badge" class:badge-success={published}>{published ? 'Published' : 'Draft'}</span> </div>
</div> <BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
<p class="text-base-content/60"> </aside>
{published ? 'This page is live — saved changes appear on the site immediately.' : 'Not visible on the site until you publish it.'} <BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} />
</p> </div>
</div> </form>
<div class="flex flex-wrap items-center gap-2">
{#if dirty}<span class="badge badge-warning">Unsaved changes</span>{/if} {#if showPreview}
<button class="btn" type="button" onclick={openPreview}>Preview</button> <div class="fixed inset-0 z-50 bg-black/60 p-4">
<button class="btn btn-outline" type="submit" name="intent" value="save" disabled={saving !== ''}> <div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
{#if saving === 'save'}<span class="loading loading-spinner loading-sm"></span>{/if} <div class="mb-3 flex items-center justify-between gap-3">
{published ? 'Save' : 'Save draft'} <div class="join"><button class="btn join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button><button class="btn join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button></div>
</button> <button class="btn" onclick={() => (showPreview = false)}>Close</button>
{#if !published} </div>
<button class="btn btn-primary" type="submit" name="intent" value="publish" disabled={saving !== ''}> <iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
{#if saving === 'publish'}<span class="loading loading-spinner loading-sm"></span>{/if} </div>
Save & publish </div>
</button> {/if}
{/if}
</div>
</div>
{#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">
<label class="fieldset py-0">
<span class="fieldset-legend">Title</span>
<input class="input w-full" name="title" required bind:value={title} />
</label>
<label class="fieldset py-0">
<span class="fieldset-legend">Slug</span>
<input class="input w-full font-mono" name="slug" required bind:value={slug} />
</label>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-20 mt-2 w-full rounded-box bg-base-100 p-2 shadow-lg">
{#each blockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} />
</div>
</form>
{#if showPreview}
<div class="fixed inset-0 z-50 bg-black/60 p-4" role="dialog" aria-modal="true" aria-label="Page preview">
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
<div class="mb-3 flex items-center justify-between gap-3">
<div class="join">
<button class="btn btn-sm join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button>
<button class="btn btn-sm join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button>
</div>
<p class="hidden text-sm text-base-content/60 sm:block">Unsaved draft preview</p>
<button class="btn btn-sm" onclick={() => (showPreview = false)}>Close</button>
</div>
<iframe class="mx-auto h-full rounded-box border border-base-300" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
</div>
</div>
{/if}

View file

@ -1,22 +0,0 @@
import { eventOverlapsRange, getUpcomingCalendarRange, normalizeEvent } from '$lib/calendar';
import { loadShopData } from '$shared/server/shop';
import type { PageServerLoad } from './$types';
// The draft blocks come from sessionStorage (client-side), so load the data
// any block might need: shop items/slots and upcoming events. Failures leave
// the blocks empty rather than breaking the preview.
export const load: PageServerLoad = async ({ locals }) => {
const range = getUpcomingCalendarRange();
const [shop, events] = await Promise.all([
loadShopData(locals.pb).catch((e) => {
console.warn('Preview: shop data unavailable:', e instanceof Error ? e.message : e);
return { items: [], slots: [] };
}),
locals.pb
.collection('events')
.getFullList({ filter: locals.pb.filter('published = true && start <= {:end}', { end: range.end }), sort: 'start' })
.catch(() => [])
]);
const calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
return { ...shop, calendarEvents };
};

View file

@ -1,36 +1,25 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import BlockRenderer from '$shared/blocks/BlockRenderer.svelte'; import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
import type { ContentBlock } from '$lib/types'; import type { ContentBlock } from '$lib/types';
import { rootStyleTag, siteThemeVars } from '$shared/theme';
let blocks = $state<ContentBlock[]>([]);
let { data } = $props();
let blocks = $state<ContentBlock[]>([]); onMount(() => {
let error = $state(''); const raw = sessionStorage.getItem('cms-preview-blocks');
if (raw) blocks = JSON.parse(raw);
onMount(() => { });
const raw = sessionStorage.getItem('cms-preview-blocks'); </script>
if (!raw) return;
try { <svelte:head>
const parsed = JSON.parse(raw); <title>Preview</title>
if (Array.isArray(parsed)) blocks = parsed; </svelte:head>
} catch {
error = 'The preview data could not be read. Close the preview and open it again.'; {#if blocks.length}
} <BlockRenderer {blocks} />
}); {:else}
</script> <section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1>
<svelte:head> <p class="mt-4 text-charcoal/65">Open preview from the page editor to view the current draft.</p>
<title>Preview</title> </section>
<!-- Full site colours so the draft looks like the public site. --> {/if}
{@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head>
{#if blocks.length}
<BlockRenderer {blocks} items={data.items} slots={data.slots} calendarEvents={data.calendarEvents} />
{:else}
<section class="mx-auto max-w-3xl px-6 py-20 text-center">
<h1 class="text-4xl">No preview content</h1>
<p class="mt-4 text-charcoal/65">{error || 'Open preview from the page editor to view the current draft.'}</p>
</section>
{/if}

View file

@ -1,37 +1,24 @@
import { env } from '$env/dynamic/private';
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb'; import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import type { SlotStatus } from '$lib/types'; import type { SlotStatus } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
type SlotPayload = type SlotPayload =
| { payload: { item: string; start: string; end: string; notes: string } } | { payload: { item: string; start: string; end: string; status: string; notes: string } }
| { error: string }; | { error: string };
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */
function isHoldActive(slot: Record<string, any> | null) {
if (slot?.status !== 'held') return false;
const until = Date.parse(String(slot.heldUntil || '').replace(' ', 'T'));
return Number.isNaN(until) || until > Date.now();
}
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> { async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const itemId = String(data.get('item') || '').trim(); const itemId = String(data.get('item') || '').trim();
const startValue = String(data.get('start') || '').trim(); const startValue = String(data.get('start') || '').trim();
const status = String(data.get('status') || 'available').trim();
const notes = String(data.get('notes') || '').trim(); const notes = String(data.get('notes') || '').trim();
if (!itemId || !startValue) return { error: 'Service and start are required.' }; if (!itemId || !startValue) return { error: 'Service and start are required.' };
// The form sends a wall-clock time in the site's timezone. const start = new Date(startValue);
const startIso = zonedInputToIso(startValue, siteTimezone()); if (Number.isNaN(start.getTime())) return { error: 'Invalid start time.' };
if (!startIso) return { error: 'Invalid start time.' };
const start = new Date(startIso);
let item: Record<string, any>; let item: Record<string, any>;
try { try {
@ -44,9 +31,9 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const duration = Number(item.duration) || 0; const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000); const end = new Date(start.getTime() + duration * 60_000);
// Status is never taken from the form: it is owned by the booking flow return {
// (held by a basket, booked by a paid order). New slots start available. payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), status, notes }
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } }; };
} }
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
@ -62,7 +49,7 @@ export const load: PageServerLoad = async ({ locals }) => {
const slotRecords = await locals.pb const slotRecords = await locals.pb
.collection('slots') .collection('slots')
.getFullList({ sort: 'start', expand: 'item' }) .getFullList({ sort: '-start', expand: 'item' })
.catch(() => []); .catch(() => []);
const slots = slotRecords.map((record) => ({ const slots = slotRecords.map((record) => ({
id: record.id, id: record.id,
@ -85,33 +72,16 @@ export const actions: Actions = {
const data = await request.formData(); const data = await request.formData();
const result = await slotPayload(data, locals.pb); const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error }); if ('error' in result) return fail(400, { message: result.error });
const created = await attempt('Could not create the slot.', () => await locals.pb.collection('slots').create(result.payload);
locals.pb.collection('slots').create({ ...result.payload, status: 'available' })
);
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') || '');
if (!id) return fail(400, { message: 'Slot id is required.' }); if (!id) return fail(400, { message: 'Slot id is required.' });
const result = await slotPayload(data, locals.pb);
// Re-read the slot: the page may be stale, and a customer may have if ('error' in result) return fail(400, { message: result.error });
// held or booked it since. Only notes can change while it's held. await locals.pb.collection('slots').update(id, result.payload);
const current = await locals.pb.collection('slots').getOne(id).catch(() => null);
if (!current) return fail(404, { message: 'This slot no longer exists.' });
if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' });
let patch: Record<string, string>;
if (isHoldActive(current)) {
patch = { notes: String(data.get('notes') || '').trim() };
} else {
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
patch = result.payload;
}
const updated = await attempt('Could not save the slot.', () => locals.pb.collection('slots').update(id, patch));
if (!updated.ok) return updated.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
@ -119,10 +89,8 @@ export const actions: Actions = {
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' }); if (!id) return fail(400, { message: 'Slot id is required.' });
const record = await locals.pb.collection('slots').getOne(id).catch(() => null); const record = await locals.pb.collection('slots').getOne(id).catch(() => null);
if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' }); if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted' });
if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' }); await 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;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -1,11 +1,11 @@
<script lang="ts"> <script lang="ts">
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import { toDatetimeInput } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
let slots = $derived(data.slots || []); let slots = $derived(
[...(data.slots || [])].sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
);
let showEditor = $state(false); let showEditor = $state(false);
type SlotDraft = { type SlotDraft = {
@ -23,14 +23,14 @@
let selectedItem = $derived(items.find((item) => item.id === draft.item)); let selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => { let endLabel = $derived.by(() => {
if (!selectedItem || !draft.start) return ''; if (!selectedItem || !draft.start) return '';
const startIso = zonedInputToIso(draft.start, data.timezone); const start = new Date(draft.start);
if (!startIso) return ''; if (Number.isNaN(start.getTime())) return '';
const end = new Date(new Date(startIso).getTime() + (Number(selectedItem.duration) || 0) * 60_000); const end = new Date(start.getTime() + (Number(selectedItem.duration) || 0) * 60_000);
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`; return `Ends at ${end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
}); });
function emptyDraft(): SlotDraft { function emptyDraft(): SlotDraft {
return { id: '', item: '', start: toZonedDatetimeInput(new Date().toISOString(), data.timezone), status: 'available', heldUntil: '', notes: '' }; return { id: '', item: '', start: toDatetimeInput(new Date().toISOString()), status: 'available', heldUntil: '', notes: '' };
} }
function createSlot() { function createSlot() {
@ -42,7 +42,7 @@
draft = { draft = {
id: slot.id, id: slot.id,
item: slot.item, item: slot.item,
start: toZonedDatetimeInput(slot.start, data.timezone), start: toDatetimeInput(slot.start),
status: slot.status, status: slot.status,
heldUntil: slot.heldUntil, heldUntil: slot.heldUntil,
notes: slot.notes notes: slot.notes
@ -57,22 +57,22 @@
<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">Slots</h1> <h1 class="text-3xl font-bold">Slots</h1>
<p class="text-base-content/60">Create bookable time slots for your services. Times are in {data.timezone}.</p> <p class="text-base-content/60">Create bookable time slots for your services.</p>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button> <button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
</div> </div>
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error">{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="overflow-x-auto"> <div class="overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead> <thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each slots as slot (slot.id)} {#each slots as slot}
<tr> <tr>
<td><span class="font-semibold">{slot.itemName}</span></td> <td><span class="font-semibold">{slot.itemName}</span></td>
<td>{formatDateTime(slot.start, data.timezone)}</td> <td>{new Date(slot.start).toLocaleString()}</td>
<td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td> <td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td>
<td> <td>
<span <span
@ -83,11 +83,9 @@
>{slot.status}</span> >{slot.status}</span>
</td> </td>
<td class="text-right"> <td class="text-right">
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} title={slot.status === 'booked' ? 'Booked slots can’t be edited' : undefined} onclick={() => editSlot(slot)}>Edit</button> <button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} onclick={() => editSlot(slot)}>Edit</button>
</td> </td>
</tr> </tr>
{:else}
<tr><td colspan="5" class="py-10 text-center text-base-content/60">{items.length ? 'No slots yet — create one so customers can book.' : 'Add a bookable service under Services & products first.'}</td></tr>
{/each} {/each}
</tbody> </tbody>
</table> </table>
@ -95,47 +93,69 @@
</div> </div>
</div> </div>
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}> {#if showEditor}
<form method="POST" action={action} class="space-y-1"> <div class="fixed inset-0 z-50 bg-black/50 p-4">
<input type="hidden" name="id" value={draft.id} /> <div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
{#if isHeld} <h2 class="text-2xl font-bold">{draft.id ? 'Edit slot' : 'Create slot'}</h2>
<div class="alert alert-warning mb-2 text-sm"> <button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed.
</div> </div>
{/if}
<label class="fieldset"> <form method="POST" action={action} class="space-y-4">
<span class="fieldset-legend">Service</span> <input type="hidden" name="id" value={draft.id} />
<select class="select w-full" name="item" required disabled={isHeld} bind:value={draft.item}> <input type="hidden" name="status" value={draft.status} />
<option value="" disabled>Select a service…</option> {#if isHeld}
{#each items as item (item.id)} <input type="hidden" name="item" value={draft.item} />
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option> <input type="hidden" name="start" value={draft.start} />
{/each} {/if}
</select>
</label>
<label class="fieldset"> {#if isHeld}
<span class="fieldset-legend">Start ({data.timezone})</span> <div class="alert alert-warning">
<input class="input w-full" type="datetime-local" name="start" required disabled={isHeld} bind:value={draft.start} /> This slot is currently held by a basket{draft.heldUntil ? ` (until ${new Date(draft.heldUntil).toLocaleString()})` : ''} — editing start/end is disabled.
{#if endLabel}<span class="label">{endLabel}</span>{/if} </div>
</label> {/if}
<label class="fieldset"> <label class="form-control w-full">
<span class="fieldset-legend">Notes</span> <div class="label"><span class="label-text">Service</span></div>
<textarea class="textarea w-full" name="notes" bind:value={draft.notes}></textarea> <select class="select select-bordered w-full" name="item" required disabled={isHeld} bind:value={draft.item}>
</label> <option value="" disabled>Select a service…</option>
{#each items as item}
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
{/each}
</select>
</label>
<div class="modal-action justify-between"> <label class="form-control w-full">
{#if draft.id && !isHeld} <div class="label"><span class="label-text">Start</span></div>
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit('Delete this slot?')}>Delete</button> <input
{:else} class="input input-bordered w-full"
<span></span> type="datetime-local"
{/if} name="start"
<div class="flex gap-2"> required
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> disabled={isHeld}
<button class="btn btn-primary" type="submit">Save slot</button> value={draft.start}
</div> oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })}
/>
</label>
{#if endLabel}<p class="text-sm text-base-content/60">{endLabel}</p>{/if}
<label class="form-control w-full">
<div class="label"><span class="label-text">Notes</span></div>
<textarea class="textarea textarea-bordered" name="notes" bind:value={draft.notes}></textarea>
</label>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save slot</button>
</div>
</div>
</form>
</div> </div>
</form> </div>
</Modal> {/if}

View file

@ -14,6 +14,7 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.26.9", "pocketbase": "^0.26.9",
"stripe": "^22.3.2",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
@ -1986,6 +1987,23 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/stripe": {
"version": "22.5.0",
"resolved": "https://registry.npmjs.org/stripe/-/stripe-22.5.0.tgz",
"integrity": "sha512-QVwMwriC0bbySx6R4dpsvJ0W//GojC1kwWVS6rPSoVqDUIZX4Hy3TaUrd2AZeXEAaKbfWIjQjvo3vKAReHZ0vQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/node": ">=18"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/supports-preserve-symlinks-flag": { "node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",

View file

@ -26,6 +26,7 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.26.9", "pocketbase": "^0.26.9",
"stripe": "^22.3.2",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
} }
} }

View file

@ -1,202 +1,51 @@
<script lang="ts"> <script lang="ts">
import { afterNavigate } from '$app/navigation'; import type { HeaderGlobal } from '$lib/types';
import { page } from '$app/state'; import { getBasketContext } from '$lib/basket.svelte';
import type { HeaderGlobal } from '$lib/types';
import { getBasketContext } from '$lib/basket.svelte'; let { header } = $props<{ header: HeaderGlobal }>();
let { header } = $props<{ header: HeaderGlobal }>(); const basket = getBasketContext();
let hasItems = $derived(basket.count > 0);
const basket = getBasketContext();
let hasItems = $derived(basket.count > 0); function formatTotal(amount: number) {
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
// Phone menu: a native modal <dialog> sliding in from the right, so focus }
// trapping, Escape and the inert page behind come from the browser. </script>
let drawer = $state<HTMLDialogElement>();
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur">
function openMenu() { <div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-6 py-4">
drawer?.showModal(); <a class="flex items-center gap-3" href="/" aria-label="Home">
} {#if header.logo?.url}
<img class="h-12 w-12 rounded-full object-cover" src={header.logo.url} alt={header.logo.alt || ''} />
function closeMenu() { {:else}
drawer?.close(); <span class="grid h-12 w-12 place-items-center rounded-full bg-sage text-lg font-bold text-white">ES</span>
} {/if}
<span class="font-serif text-xl font-bold">Eva Shafik</span>
// Following a link (or the browser's back button) closes the menu. </a>
afterNavigate(closeMenu);
<nav class="hidden items-center gap-7 md:flex" aria-label="Main navigation">
function isCurrent(href: string) { {#each header.navLinks || [] as link}
const path = page.url.pathname; <a class="text-sm font-semibold text-charcoal/75 transition hover:text-sage-dark" href={link.href}>{link.label}</a>
return href === '/' ? path === '/' : path === href || path.startsWith(href + '/'); {/each}
} </nav>
function formatTotal(amount: number) { <div class="flex items-center gap-3">
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount); {#if hasItems}
} <a
</script> class="relative flex items-center gap-2 rounded-full border border-charcoal/10 px-4 py-2 text-sm font-semibold text-charcoal/80 transition hover:border-sage hover:text-sage-dark"
href="/book"
{#snippet basketIcon()} aria-label="View your basket"
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5" aria-hidden="true"> >
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007Z" /> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
</svg> <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007Z" />
{/snippet} </svg>
<span class="badge badge-sm rounded-full border-0 bg-sage text-white">{basket.count}</span>
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur"> <span class="hidden sm:inline">{formatTotal(basket.total)}</span>
<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>
<a class="flex min-w-0 items-center gap-3" href="/" aria-label="Home"> {/if}
{#if header.logo?.url} {#if header.ctaButton?.label}
<img class="h-10 w-10 shrink-0 rounded-full object-cover md:h-12 md:w-12" src={header.logo.url} alt={header.logo.alt || ''} /> <a class="btn rounded-full border-0 px-6 text-white hover:opacity-90" style="background-color: var(--color-primary, #8a9a7b);" href={header.ctaButton.href}>{header.ctaButton.label}</a>
{:else} {/if}
<span class="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-sage text-lg font-bold text-primary-content md:h-12 md:w-12">ES</span> </div>
{/if} </div>
<span class="truncate font-serif text-lg font-bold md:text-xl">Eva Shafik</span> </header>
</a>
<nav class="hidden items-center gap-7 md:flex" aria-label="Main navigation">
{#each header.navLinks || [] as link}
<a
class="text-sm font-semibold transition hover:text-sage-dark {isCurrent(link.href) ? 'text-charcoal underline decoration-sage decoration-2 underline-offset-8' : 'text-charcoal/75'}"
href={link.href}
aria-current={isCurrent(link.href) ? 'page' : undefined}>{link.label}</a
>
{/each}
</nav>
<div class="flex shrink-0 items-center gap-2 md:gap-3">
{#if hasItems}
<a
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="/book"
aria-label="View your basket ({basket.count})"
>
{@render basketIcon()}
<span class="badge badge-sm rounded-full border-0 bg-sage text-primary-content">{basket.count}</span>
<span class="hidden sm:inline">{formatTotal(basket.total)}</span>
</a>
{/if}
{#if header.ctaButton?.label}
<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}
<button
class="grid h-10 w-10 place-items-center rounded-full text-charcoal/80 transition hover:bg-charcoal/5 md:hidden"
type="button"
aria-label="Open menu"
aria-haspopup="dialog"
onclick={openMenu}
>
<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="M4 7h16M4 12h16M4 17h16" />
</svg>
</button>
</div>
</div>
</header>
<!-- Clicking the backdrop lands on the <dialog> itself, so close then.
Escape is handled natively. -->
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
<dialog bind:this={drawer} class="nav-drawer" aria-label="Menu" onclick={(e) => e.target === drawer && closeMenu()}>
<div class="flex h-full flex-col">
<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>
<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">
<path stroke-linecap="round" d="M6 6l12 12M18 6L6 18" />
</svg>
</button>
</div>
<nav class="flex-1 overflow-y-auto px-3 py-4" aria-label="Main navigation">
<ul class="space-y-1">
{#each header.navLinks || [] as link}
<li>
<a
class="block rounded-xl px-4 py-3 text-lg font-semibold transition {isCurrent(link.href) ? 'bg-sage/15 text-charcoal shadow-[inset_3px_0_0_var(--color-sage)]' : 'text-charcoal/80 hover:bg-charcoal/5'}"
href={link.href}
aria-current={isCurrent(link.href) ? 'page' : undefined}>{link.label}</a
>
</li>
{/each}
</ul>
{#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="/book">
{@render basketIcon()}
<span class="flex-1">Basket ({basket.count})</span>
<span class="text-charcoal/60">{formatTotal(basket.total)}</span>
</a>
{/if}
</nav>
{#if header.ctaButton?.label}
<div class="border-t border-charcoal/10 p-6">
<a class="cta btn btn-block rounded-full border-0 hover:opacity-90" href={header.ctaButton.href}>{header.ctaButton.label}</a>
</div>
{/if}
</div>
</dialog>
<style>
/* Brand button: site Primary with its contrast text colour (see $shared/theme). */
.cta {
background-color: var(--color-primary, #8a9a7b);
color: var(--color-primary-content, #fff);
}
.nav-drawer {
position: fixed;
inset: 0 0 0 auto;
margin: 0;
width: min(20rem, 85vw);
height: 100dvh;
max-height: none;
padding: 0;
border: 0;
background: var(--color-warm);
box-shadow: -8px 0 32px rgb(0 0 0 / 0.15);
translate: 100% 0;
transition:
translate 0.25s ease,
display 0.25s allow-discrete,
overlay 0.25s allow-discrete;
}
.nav-drawer[open] {
translate: 0 0;
}
@starting-style {
.nav-drawer[open] {
translate: 100% 0;
}
}
.nav-drawer::backdrop {
background: rgb(0 0 0 / 0);
transition:
background 0.25s ease,
display 0.25s allow-discrete,
overlay 0.25s allow-discrete;
}
.nav-drawer[open]::backdrop {
background: rgb(0 0 0 / 0.45);
}
@starting-style {
.nav-drawer[open]::backdrop {
background: rgb(0 0 0 / 0);
}
}
/* Don't scroll the page behind the open menu. */
:global(html:has(.nav-drawer[open])) {
overflow: hidden;
}
@media (prefers-reduced-motion: reduce) {
.nav-drawer,
.nav-drawer::backdrop {
transition: none;
}
}
</style>

View file

@ -0,0 +1 @@
export * from '$shared/server/basket';

View file

@ -0,0 +1 @@
export * from '$shared/server/pb-admin';

View file

@ -1,138 +0,0 @@
import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { getFileUrl } from '$lib/pb';
import type { Basket, BasketLine, OrderRecord } from '$lib/types';
import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email';
// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All
// basket, payment and order writes happen there; this app holds no
// PocketBase or Stripe secrets — it keeps the basket cookie and forwards.
export const BASKET_COOKIE = 'basket_id';
/** Cookie lifetime; PocketBase keeps the basket alive for 24h after its last change. */
export const BASKET_COOKIE_MAX_AGE = 24 * 60 * 60;
function shopUrl(path: string) {
return `${env.POCKETBASE_INTERNAL_URL}/api/shop${path}`;
}
/** Call the shop API; PocketBase errors become SvelteKit errors with the same status and message. */
export async function shopFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
let res: Response;
try {
res = await fetch(shopUrl(path), init);
} catch (e) {
console.error('[shop] PocketBase unreachable:', e);
throw error(503, 'The shop is temporarily unavailable — please try again');
}
if (res.status === 204) return undefined as T;
const body = await res.json().catch(() => ({}));
if (!res.ok) throw error(res.status, body?.message || `Shop request failed (${res.status})`);
return body as T;
}
/** Wrap an API route so shop errors always reach the browser as JSON `{ message }` (never an HTML error page). */
export function jsonErrors<E extends Parameters<RequestHandler>[0]>(handler: (event: E) => Promise<Response>) {
return async (event: E) => {
try {
return await handler(event);
} catch (e) {
if (isHttpError(e)) return json({ message: e.body.message }, { status: e.status });
throw e;
}
};
}
export function postJson<T>(path: string, data: unknown): Promise<T> {
return shopFetch<T>(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
}
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null;
/** Map the API's raw basket records to the `Basket` type used by the UI. */
export function mapBasket(payload: BasketPayload): Basket | null {
if (!payload) return null;
const { record, lines } = payload;
const mappedLines: BasketLine[] = lines.map((line) => {
const item = line.expand?.item;
const slot = line.expand?.slot;
const media = item?.expand?.image;
return {
id: line.id,
basket: line.basket,
item: line.item,
slot: line.slot || null,
quantity: line.quantity,
lineType: line.lineType,
itemName: item?.name,
itemPrice: item?.price,
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
slotStart: slot?.start,
slotEnd: slot?.end
};
});
return {
id: record.id,
status: record.status,
expiresAt: record.expiresAt,
email: record.email || null,
customerDetails: record.customerDetails || null,
stripePaymentIntentId: record.stripePaymentIntentId || null,
lines: mappedLines
};
}
/** The basket for a cookie value, or null (expired, completed, unknown). */
export async function getBasket(basketId: string | undefined): Promise<Basket | null> {
// Ids are PocketBase record ids; anything else can't be a basket.
if (!basketId || !/^[a-z0-9]{1,32}$/i.test(basketId)) return null;
const { basket } = await shopFetch<{ basket: BasketPayload }>(`/basket/${basketId}`);
return mapBasket(basket);
}
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[]): OrderRecord {
return {
id: order.id,
basket: order.basket,
email: order.email,
customerDetails: order.customerDetails,
total: order.total,
status: order.status,
stripePaymentIntentId: order.stripePaymentIntentId,
createdAt: order.created,
lines: lines.map((l) => ({
id: l.id,
order: l.order,
item: l.item,
slot: l.slot || null,
quantity: l.quantity,
lineType: l.lineType,
name: l.name,
price: l.price,
start: l.start || null
}))
};
}
/**
* Send the booking emails for a new order (data supplied by PocketBase's
* webhook handler), then report the outcome back so /orders shows it.
* Never throws; runs after Stripe has had its response.
*/
export async function sendAndRecordOrderEmails(data: OrderEmailData) {
const { patch } = await sendOrderEmailsFromData(data);
const secret = env.INTERNAL_API_SECRET;
if (!secret) {
console.warn(`[email] INTERNAL_API_SECRET is not set — email status for order ${data.order.id} was not recorded`);
return;
}
await shopFetch('/order-email-status', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Internal-Secret': secret },
body: JSON.stringify({ orderId: data.order.id, patch })
}).catch((e) => console.error(`[email] could not record email status on order ${data.order.id}:`, e));
}

View file

@ -0,0 +1,17 @@
import Stripe from 'stripe';
import { env } from '$env/dynamic/private';
let stripe: Stripe | null = null;
export function getStripe(): Stripe {
if (!stripe) {
const key = env.STRIPE_SECRET_KEY;
if (!key) throw new Error('STRIPE_SECRET_KEY is not set');
stripe = new Stripe(key);
}
return stripe;
}
export function getCurrency(): string {
return env.STRIPE_CURRENCY || 'eur';
}

View file

@ -1,12 +1,13 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord, SlotRecord } from '$lib/types'; import type { ItemRecord, SlotRecord } from '$lib/types';
import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; import { getFileUrl } from '$lib/pb';
import { loadShopData } from '$shared/server/shop'; import { getAdminPb } from '$lib/server/pb-admin';
import { BASKET_COOKIE, loadBasket, sweepExpiredHolds } from '$lib/server/basket';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try { try {
const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key })); const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback; return record.data || fallback;
} catch { } catch {
return fallback; return fallback;
@ -22,18 +23,57 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => {
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.
// rules allow active items / available slots); the basket comes from the let basket = null;
// shop API in PocketBase. Failures leave the shop empty, never break a page. let items: ItemRecord[] = [];
const [shop, basket] = await Promise.all([ let slots: SlotRecord[] = [];
loadShopData(locals.pb).catch((e) => {
console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e); try {
return null; const pb = await getAdminPb();
}), await sweepExpiredHolds(pb);
getBasket(cookies.get(BASKET_COOKIE)).catch(() => null)
]); const basketId = cookies.get(BASKET_COOKIE);
const items: ItemRecord[] = shop?.items ?? []; if (basketId) basket = await loadBasket(pb, basketId);
const slots: SlotRecord[] = shop?.slots ?? [];
const itemRecords = await pb
.collection('items')
.getFullList({ filter: 'active = true', sort: 'name', expand: 'image' })
.catch(() => []);
items = itemRecords.map((record) => {
const media = record.expand?.image;
return {
id: record.id,
name: record.name,
description: record.description || '',
price: record.price,
image: record.image || '',
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type,
stock: record.stock ?? null,
duration: record.duration ?? null,
active: record.active
};
});
const nowIso = new Date().toISOString();
const slotRecords = await pb
.collection('slots')
.getFullList({ filter: `status = 'available' && start >= "${nowIso}"`, sort: 'start' })
.catch(() => []);
slots = slotRecords.map((record) => ({
id: record.id,
item: record.item,
start: record.start,
end: record.end || '',
status: record.status,
heldUntil: record.heldUntil || null,
order: record.order || null,
notes: record.notes || ''
}));
} catch (e) {
// Admin PB not configured (e.g. fresh dev env) — commerce features off.
console.warn('Commerce data unavailable:', e instanceof Error ? e.message : e);
}
return { header, footer, colors, user: locals.user, basket, items, slots }; return { header, footer, colors, user: locals.user, basket, items, slots };
}; };

View file

@ -4,7 +4,7 @@
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 { onMount } from 'svelte';
let { children, data } = $props(); let { children, data } = $props();
@ -16,14 +16,23 @@
// Keep the store in sync when layout data refreshes (e.g. after checkout // Keep the store in sync when layout data refreshes (e.g. after checkout
// clears the cookie and data.basket becomes null). // clears the cookie and data.basket becomes null).
$effect(() => basketStore.syncFrom(data.basket ?? null)); $effect(() => basketStore.syncFrom(data.basket ?? null));
onMount(() => {
if (data.colors) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script> </script>
<svelte:head> <svelte:head>
<link rel="icon" href={favicon} /> <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" />
<!-- Site colours, rendered server-side (previously applied in onMount, which
flashed the defaults on every page load). Values are sanitised. -->
{@html rootStyleTag(siteThemeVars(data.colors))}
</svelte:head> </svelte:head>
<Header header={data.header} /> <Header header={data.header} />

View file

@ -16,7 +16,7 @@ export const load: PageServerLoad = async ({ locals }) => {
try { try {
const page = await locals.pb const page = await locals.pb
.collection('pages') .collection('pages')
.getFirstListItem(locals.pb.filter('slug = {:slug} && published = true', { slug: homeSlug })); .getFirstListItem(`slug = "${homeSlug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = []; let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) { if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange(); const range = getUpcomingCalendarRange();

View file

@ -7,7 +7,7 @@ export const load: PageServerLoad = async ({ params, locals }) => {
try { try {
const page = await locals.pb const page = await locals.pb
.collection('pages') .collection('pages')
.getFirstListItem(locals.pb.filter('slug = {:slug} && published = true', { slug: params.slug })); .getFirstListItem(`slug = "${params.slug}" && published = true`);
let calendarEvents: CalendarEventRecord[] = []; let calendarEvents: CalendarEventRecord[] = [];
if (hasUpcomingCalendarBlock(page.blocks || [])) { if (hasUpcomingCalendarBlock(page.blocks || [])) {
const range = getUpcomingCalendarRange(); const range = getUpcomingCalendarRange();

View file

@ -1,15 +1,54 @@
import { json, error } from '@sveltejs/kit'; import { json, error, type Cookies } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { BASKET_COOKIE, BASKET_COOKIE_MAX_AGE, getBasket, jsonErrors, mapBasket, postJson } from '$lib/server/shop'; import { getAdminPb } from '$lib/server/pb-admin';
import {
BASKET_COOKIE,
BASKET_TTL_MS,
SLOT_HOLD_MS,
sweepExpiredHolds,
loadBasket,
createBasket,
touchBasket,
releaseLineHold
} from '$lib/server/basket';
import type PocketBase from 'pocketbase';
// Basket API for the browser. The logic (stock, slot holds, expiry) is in function setBasketCookie(cookies: Cookies, basketId: string) {
// PocketBase — pocketbase/pb_hooks/shop; this route only adds the cookie. cookies.set(BASKET_COOKIE, basketId, {
path: '/',
httpOnly: true,
sameSite: 'lax',
maxAge: BASKET_TTL_MS / 1000
});
}
export const GET: RequestHandler = jsonErrors(async ({ cookies }) => { /**
return json({ basket: await getBasket(cookies.get(BASKET_COOKIE)) }); * Resolve the current basket from the cookie. When `create` is true and no
}); * valid basket exists, a new one is created (and the cookie is set).
*/
async function resolveBasket(pb: PocketBase, cookies: Cookies, create: boolean) {
const id = cookies.get(BASKET_COOKIE);
if (id) {
const basket = await loadBasket(pb, id);
if (basket) return { basket, isNew: false };
}
if (!create) return { basket: null, isNew: false };
const basket = await createBasket(pb);
setBasketCookie(cookies, basket.id);
return { basket, isNew: true };
}
export const GET: RequestHandler = async ({ cookies }) => {
const pb = await getAdminPb();
await sweepExpiredHolds(pb);
const { basket } = await resolveBasket(pb, cookies, false);
return json({ basket });
};
export const POST: RequestHandler = async ({ request, cookies }) => {
const pb = await getAdminPb();
await sweepExpiredHolds(pb);
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
let body: Record<string, unknown>; let body: Record<string, unknown>;
try { try {
body = await request.json(); body = await request.json();
@ -17,17 +56,112 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body'); throw error(400, 'Invalid JSON body');
} }
const { basket } = await postJson<{ basket: Parameters<typeof mapBasket>[0] }>('/basket', { const action = String(body.action || '');
action: body.action,
itemId: body.itemId,
slotId: body.slotId,
lineId: body.lineId,
quantity: body.quantity,
basketId: cookies.get(BASKET_COOKIE) || ''
});
const mapped = mapBasket(basket); // All mutations need a basket — lazily created on first add.
// A basket is created on the first add; (re)set the cookie to keep it alive. const { basket } = await resolveBasket(pb, cookies, action === 'add_item' || action === 'add_slot');
if (mapped) cookies.set(BASKET_COOKIE, mapped.id, { path: '/', httpOnly: true, sameSite: 'lax', maxAge: BASKET_COOKIE_MAX_AGE }); if (!basket) throw error(400, 'No active basket — add an item first');
return json({ basket: mapped });
}); switch (action) {
case 'add_item': {
const itemId = String(body.itemId || '');
const quantity = Math.max(1, Number(body.quantity) || 1);
if (!itemId) throw error(400, 'itemId is required');
const item = await pb.collection('items').getOne(itemId).catch(() => null);
if (!item || !item.active) throw error(404, 'Item not found');
if (item.type !== 'item') throw error(400, 'Use add_slot for bookable services');
const existing = basket.lines.find((l) => l.lineType === 'item' && l.item === itemId);
const newQty = (existing?.quantity ?? 0) + quantity;
if (item.stock != null && newQty > item.stock) {
throw error(409, `Only ${item.stock} in stock`);
}
if (existing) {
await pb.collection('basket_lines').update(existing.id, { quantity: newQty });
} else {
await pb.collection('basket_lines').create({
basket: basket.id,
item: itemId,
quantity,
lineType: 'item'
});
}
break;
}
case 'add_slot': {
const slotId = String(body.slotId || '');
if (!slotId) throw error(400, 'slotId is required');
if (basket.lines.some((l) => l.slot === slotId)) {
throw error(409, 'Slot already in your basket');
}
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
if (!slot) throw error(404, 'Slot not found');
if (slot.status !== 'available') throw error(409, 'Slot is no longer available');
// Atomic guard: basket_lines.slot has a partial UNIQUE index, so two
// concurrent requests cannot both create a line for the same slot.
// The line is created first; whoever loses the race gets a 409.
let line;
try {
line = await pb.collection('basket_lines').create({
basket: basket.id,
item: slot.item,
slot: slotId,
quantity: 1,
lineType: 'slot'
});
} catch {
throw error(409, 'Slot was just reserved by someone else');
}
try {
await pb.collection('slots').update(slotId, {
status: 'held',
heldUntil: new Date(Date.now() + SLOT_HOLD_MS).toISOString()
});
} catch (e) {
// Roll back the line if the hold update failed
await pb.collection('basket_lines').delete(line.id).catch(() => {});
throw error(500, 'Could not reserve the slot — please try again');
}
break;
}
case 'update_quantity': {
const lineId = String(body.lineId || '');
const quantity = Number(body.quantity);
const line = basket.lines.find((l) => l.id === lineId);
if (!line) throw error(404, 'Line not found in your basket');
if (line.lineType === 'slot') throw error(400, 'Slot lines have fixed quantity 1');
if (!Number.isInteger(quantity) || quantity < 1) throw error(400, 'Quantity must be a positive integer');
const item = await pb.collection('items').getOne(line.item).catch(() => null);
if (item?.stock != null && quantity > item.stock) {
throw error(409, `Only ${item.stock} in stock`);
}
await pb.collection('basket_lines').update(lineId, { quantity });
break;
}
case 'remove_line': {
const lineId = String(body.lineId || '');
const line = basket.lines.find((l) => l.id === lineId);
if (!line) throw error(404, 'Line not found in your basket');
await pb.collection('basket_lines').delete(lineId);
await releaseLineHold(pb, line);
break;
}
default:
throw error(400, `Unknown action: ${action}`);
}
await touchBasket(pb, basket.id);
const updated = await loadBasket(pb, basket.id);
return json({ basket: updated });
};

View file

@ -1,10 +1,26 @@
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 } from '$lib/server/shop'; import { getAdminPb } from '$lib/server/pb-admin';
import { BASKET_COOKIE, SLOT_CHECKOUT_HOLD_MS, sweepExpiredHolds, loadBasket, extendBasketHolds } from '$lib/server/basket';
import { getStripe, getCurrency } from '$lib/stripe.server';
import type { CustomerDetails } from '$lib/types';
export const POST: RequestHandler = async ({ request, cookies }) => {
const pb = await getAdminPb();
const basketId = cookies.get(BASKET_COOKIE);
// Payment is starting — extend any held slots to the checkout hold (30 min)
// so a booked service survives the customer entering card details or
// retrying a declined card. Extend BEFORE sweeping so a slot whose hold
// just lapsed is rescued rather than released at the moment they try to pay.
if (basketId) await extendBasketHolds(pb, basketId, SLOT_CHECKOUT_HOLD_MS);
await sweepExpiredHolds(pb);
if (!basketId) throw error(400, 'No active basket');
const basket = await loadBasket(pb, basketId);
if (!basket) throw error(400, 'Your session has expired — please re-select your items');
if (!basket.lines.length) throw error(400, 'Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
// Starts payment: PocketBase re-validates the basket, extends slot holds and
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop).
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
let body: Record<string, unknown>; let body: Record<string, unknown>;
try { try {
body = await request.json(); body = await request.json();
@ -12,12 +28,75 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body'); throw error(400, 'Invalid JSON body');
} }
const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', { const customer: CustomerDetails = {
basketId: cookies.get(BASKET_COOKIE) || '', name: String(body.name || '').trim(),
name: body.name, email: String(body.email || '').trim(),
email: body.email, phone: String(body.phone || '').trim(),
phone: body.phone, notes: String(body.notes || '').trim()
notes: body.notes };
if (!customer.name) throw error(400, 'Name is required');
if (!customer.email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) {
throw error(400, 'A valid email is required');
}
// Re-validate every line server-side (source of truth for the total).
let totalCents = 0;
for (const line of basket.lines) {
const item = await pb.collection('items').getOne(line.item).catch(() => null);
if (!item || !item.active) throw error(409, `"${line.itemName ?? 'An item'}" is no longer available`);
if (line.lineType === 'slot') {
const slot = await pb.collection('slots').getOne(line.slot!).catch(() => null);
if (!slot || slot.status !== 'held') {
throw error(409, `Your time slot for "${item.name}" has expired — please pick it again`);
}
} else {
if (item.stock != null && item.stock < line.quantity) {
throw error(409, `Only ${item.stock} of "${item.name}" left in stock`);
}
}
totalCents += Math.round(item.price * 100) * line.quantity;
}
if (totalCents <= 0) throw error(400, 'Basket total must be positive');
let paymentIntent;
if (basket.stripePaymentIntentId) {
// Reuse an existing intent when possible (page reload / retry).
try {
const existing = await getStripe().paymentIntents.retrieve(basket.stripePaymentIntentId);
if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') {
paymentIntent = await getStripe().paymentIntents.update(existing.id, {
amount: totalCents,
metadata: { basket_id: basket.id }
});
}
} catch {
// Intent missing/invalid — fall through and create a new one
}
}
if (!paymentIntent) {
paymentIntent = await getStripe().paymentIntents.create({
amount: totalCents,
currency: getCurrency(),
automatic_payment_methods: { enabled: true },
receipt_email: customer.email,
metadata: {
basket_id: basket.id,
line_summary: basket.lines
.map((l) => `${l.quantity}× ${l.itemName ?? l.item}`)
.join('; ')
.slice(0, 450)
}
});
}
await pb.collection('baskets').update(basket.id, {
stripePaymentIntentId: paymentIntent.id,
email: customer.email,
customerDetails: customer
}); });
return json({ clientSecret });
}); return json({ clientSecret: paymentIntent.client_secret });
};

View file

@ -1,25 +1,128 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { jsonErrors, sendAndRecordOrderEmails, shopFetch } from '$lib/server/shop'; import { env } from '$env/dynamic/private';
import type { OrderEmailData } from '$lib/server/email'; import { getStripe } from '$lib/stripe.server';
import { getAdminPb } from '$lib/server/pb-admin';
import { getFileUrl } from '$lib/pb';
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
import { sendOrderEmails } from '$lib/server/email';
import type PocketBase from 'pocketbase';
// Stripe webhook endpoint (keeps the URL configured in the Stripe dashboard). async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
// PocketBase verifies the signature and creates the order; this app only const basketId = paymentIntent.metadata?.basket_id;
// sends the booking emails, which it can render (pocketbase/pb_hooks/shop). if (!basketId) return; // Not one of ours
export const POST: RequestHandler = jsonErrors(async ({ request }) => {
// Idempotency: if an order already exists for this intent, we're done.
const existing = await pb
.collection('orders')
.getFirstListItem(pb.filter('stripePaymentIntentId = {:id}', { id: paymentIntent.id }))
.catch(() => null);
if (existing) return;
const basket = await pb.collection('baskets').getOne(basketId).catch(() => null);
if (!basket) return;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: pb.filter('basket = {:basketId}', { basketId }), expand: 'item,slot' });
// Create the order
const order = await pb.collection('orders').create({
basket: basketId,
email: basket.email || paymentIntent.receipt_email || '',
customerDetails: basket.customerDetails || {},
total: paymentIntent.amount / 100,
status: 'paid',
stripePaymentIntentId: paymentIntent.id
});
// Snapshot order lines, flip slots to booked, decrement item stock
for (const line of lines) {
const item = line.expand?.item;
const slot = line.expand?.slot;
await pb.collection('order_lines').create({
order: order.id,
item: line.item,
slot: line.slot || null,
quantity: line.quantity,
lineType: line.lineType,
name: item?.name ?? 'Unknown item',
price: item?.price ?? 0,
start: slot?.start || null
});
if (line.lineType === 'slot' && line.slot) {
await pb
.collection('slots')
.update(line.slot, { status: 'booked', heldUntil: null, order: order.id })
.catch(() => {});
} else if (line.lineType === 'item' && item?.stock != null) {
await pb
.collection('items')
.update(item.id, { stock: Math.max(0, item.stock - line.quantity) })
.catch(() => {});
}
}
// Basket completed — lines can go (order_lines hold the snapshot).
for (const line of lines) {
await pb.collection('basket_lines').delete(line.id).catch(() => {});
}
await pb.collection('baskets').update(basketId, { status: 'completed' }).catch(() => {});
// Confirmation to the customer + alert to the studio. Not awaited: SMTP can
// be slow and Stripe only needs the 2xx. sendOrderEmails never throws and
// records the outcome on the order, so failures can be resent from /orders.
void sendOrderEmails(pb, order.id);
}
async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) {
const basketId = paymentIntent.metadata?.basket_id;
if (!basketId) return;
// The card was refused (or the payment otherwise failed). Keep the slots
// held for the customer so they can retry without re-picking them — just
// reset the hold to the standard 10-minute window. Starting payment again
// (create-intent) will extend it back to 30 min.
await extendBasketHolds(pb, basketId, SLOT_HOLD_MS).catch(() => {});
if (paymentIntent.id) {
await pb
.collection('baskets')
.update(basketId, { stripePaymentIntentId: null })
.catch(() => {});
}
}
export const POST: RequestHandler = async ({ request }) => {
const secret = env.STRIPE_WEBHOOK_SECRET;
if (!secret) throw error(500, 'STRIPE_WEBHOOK_SECRET is not configured');
// Signature verification MUST use the raw request body.
const body = await request.text();
const signature = request.headers.get('stripe-signature'); const signature = request.headers.get('stripe-signature');
if (!signature) throw error(400, 'Missing Stripe-Signature header'); if (!signature) throw error(400, 'Missing Stripe-Signature header');
// Forward the exact body: the signature covers the raw bytes. let event;
const result = await shopFetch<{ received: boolean; orderEmail: OrderEmailData | null }>('/stripe-webhook', { try {
method: 'POST', event = getStripe().webhooks.constructEvent(body, signature, secret);
headers: { 'Content-Type': request.headers.get('content-type') || 'application/json', 'Stripe-Signature': signature }, } catch (e) {
body: await request.text() throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`);
}); }
// Not awaited: SMTP can be slow and Stripe only needs the 2xx. Failures are const pb = await getAdminPb();
// recorded on the order and can be resent from the admin's /orders.
if (result.orderEmail) void sendAndRecordOrderEmails(result.orderEmail); switch (event.type) {
case 'payment_intent.succeeded':
await handlePaymentSucceeded(pb, event.data.object);
break;
case 'payment_intent.payment_failed':
await handlePaymentFailed(pb, event.data.object);
break;
default:
// Unhandled event types are fine — acknowledge receipt.
break;
}
return json({ received: true }); return json({ received: true });
}); };

View file

@ -1,19 +1,64 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop'; import { getStripe } from '$lib/stripe.server';
import { getAdminPb } from '$lib/server/pb-admin';
type OrderStatus = import { BASKET_COOKIE } from '$lib/server/basket';
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' } import type { OrderRecord } from '$lib/types';
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
export const load: PageServerLoad = async ({ url, cookies }) => { export const load: PageServerLoad = async ({ url, cookies }) => {
const intentId = url.searchParams.get('payment_intent'); const intentId = url.searchParams.get('payment_intent');
if (!intentId) return { state: 'missing' as const }; if (!intentId) return { state: 'missing' as const };
// PocketBase checks the intent with Stripe and looks up the order (the let intent;
// webhook is the source of truth and may not have landed yet). try {
const status = await shopFetch<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`); intent = await getStripe().paymentIntents.retrieve(intentId);
if (status.state !== 'paid') return { state: status.state }; } catch {
return { state: 'invalid' as const };
}
const pb = await getAdminPb();
// Webhook may not have landed yet — the webhook is the source of truth.
const order = await pb
.collection('orders')
.getFirstListItem(`stripePaymentIntentId = "${intentId}"`)
.catch(() => null);
if (!order) {
// Payment succeeded but webhook is still in flight.
if (intent.status === 'succeeded') return { state: 'processing' as const };
return { state: intent.status === 'canceled' ? ('canceled' as const) : ('failed' as const) };
}
// Sort by id, not 'created' — the order_lines collection was imported without
// autodate fields. PocketBase ids are time-sortable ULIDs, so this preserves
// chronological order without requiring a schema migration.
const orderLines = await pb
.collection('order_lines')
.getFullList({ filter: `order = "${order.id}"`, sort: 'id' });
cookies.delete(BASKET_COOKIE, { path: '/' }); cookies.delete(BASKET_COOKIE, { path: '/' });
return { state: 'paid' as const, order: mapOrder(status.order, status.lines) };
const result: OrderRecord = {
id: order.id,
basket: order.basket,
email: order.email,
customerDetails: order.customerDetails,
total: order.total,
status: order.status,
stripePaymentIntentId: order.stripePaymentIntentId,
createdAt: order.created,
lines: orderLines.map((l) => ({
id: l.id,
order: l.order,
item: l.item,
slot: l.slot || null,
quantity: l.quantity,
lineType: l.lineType,
name: l.name,
price: l.price,
start: l.start || null
}))
};
return { state: 'paid' as const, order: result };
}; };

View file

@ -25,7 +25,7 @@
<section class="mx-auto max-w-2xl px-6 py-16 text-center"> <section class="mx-auto max-w-2xl px-6 py-16 text-center">
{#if data.state === 'paid' && data.order} {#if data.state === 'paid' && data.order}
<div class="mb-6 inline-grid h-16 w-16 place-items-center rounded-full bg-sage text-3xl text-primary-content">✓</div> <div class="mb-6 inline-grid h-16 w-16 place-items-center rounded-full bg-sage text-3xl text-white">✓</div>
<h1 class="font-serif text-4xl">Thank you, {data.order.customerDetails?.name || 'friend'}!</h1> <h1 class="font-serif text-4xl">Thank you, {data.order.customerDetails?.name || 'friend'}!</h1>
<p class="mt-3 text-charcoal/70"> <p class="mt-3 text-charcoal/70">
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>.
@ -51,7 +51,7 @@
</div> </div>
</div> </div>
<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> <a class="btn mt-8 rounded-full border-0 px-8 text-white" style="background-color: var(--color-primary, #8a9a7b);" href="/">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">
@ -63,10 +63,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-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a> <a class="btn mt-8 rounded-full border-0 px-8 text-white" 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-full border-0 px-8 text-primary-content" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a> <a class="btn mt-8 rounded-full border-0 px-8 text-white" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a>
{/if} {/if}
</section> </section>

View file

@ -1,104 +1,95 @@
services: services:
pocketbase: pocketbase:
# Pinned: schema (pb_schema.json) and migrations target this version's image: spectado/pocketbase:latest
# format/JS API. Upgrade deliberately — read the PocketBase changelog, container_name: massage-pocketbase
# back up pb_data, then bump the tag and test migrations locally. restart: unless-stopped
image: docker.io/spectado/pocketbase:0.23.12 # Internal only — accessed via the caddy reverse proxy
container_name: massage-pocketbase expose:
restart: unless-stopped - "80"
# Internal only — accessed via the caddy reverse proxy volumes:
expose: - pocketbase:/pb_data
- "80"
volumes: app-admin:
- pocketbase:/pb_data build:
# Versioned schema changes; PocketBase applies pending ones on start. context: .
- ./pocketbase/pb_migrations:/pb_migrations:ro,Z dockerfile: app-admin/Dockerfile
# Shop API (baskets, slot holds, Stripe payments, orders) — the only container_name: massage-app-admin
# place commerce data is written. See pocketbase/pb_hooks/shop/lib.js. restart: unless-stopped
- ./pocketbase/pb_hooks:/pb_hooks:ro,Z depends_on:
environment: - pocketbase
STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} environment:
STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} PORT: 3001
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} POCKETBASE_INTERNAL_URL: http://pocketbase:80
# Shared with app-public: lets it record booking-email status on orders. PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080
INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-} ORIGIN: http://admin.${DOMAIN:-localhost}:8080
PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080
app-admin: BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64
build: # Commerce (reservation & payment system) — set these in a root-level .env
context: . POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
dockerfile: app-admin/Dockerfile POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
container_name: massage-app-admin STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
restart: unless-stopped # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends
depends_on: SMTP_HOST: ${SMTP_HOST:-}
- pocketbase SMTP_PORT: ${SMTP_PORT:-587}
environment: SMTP_USER: ${SMTP_USER:-}
PORT: 3001 SMTP_PASS: ${SMTP_PASS:-}
POCKETBASE_INTERNAL_URL: http://pocketbase:80 EMAIL_FROM: ${EMAIL_FROM:-}
PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
ORIGIN: http://admin.${DOMAIN:-localhost}:8080 SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 # Internal only — served via the caddy reverse proxy
BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 expose:
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - "3001"
# Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends
SMTP_HOST: ${SMTP_HOST:-} app-public:
SMTP_PORT: ${SMTP_PORT:-587} build:
SMTP_USER: ${SMTP_USER:-} context: .
SMTP_PASS: ${SMTP_PASS:-} dockerfile: app-public/Dockerfile
EMAIL_FROM: ${EMAIL_FROM:-} container_name: massage-app-public
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} restart: unless-stopped
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} depends_on:
# Internal only — served via the caddy reverse proxy - pocketbase
expose: environment:
- "3001" PORT: 3000
POCKETBASE_INTERNAL_URL: http://pocketbase:80
app-public: PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080
build: ORIGIN: http://www.${DOMAIN:-localhost}:8080
context: . # Commerce (reservation & payment system) — set these in a root-level .env
dockerfile: app-public/Dockerfile POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
container_name: massage-app-public POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
restart: unless-stopped STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-}
depends_on: STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
- pocketbase PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-}
environment: STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
PORT: 3000 # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook
POCKETBASE_INTERNAL_URL: http://pocketbase:80 SMTP_HOST: ${SMTP_HOST:-}
PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 SMTP_PORT: ${SMTP_PORT:-587}
ORIGIN: http://www.${DOMAIN:-localhost}:8080 SMTP_USER: ${SMTP_USER:-}
# No PocketBase or Stripe secrets here: shop writes happen in PocketBase SMTP_PASS: ${SMTP_PASS:-}
# (pb_hooks/shop). The publishable key is public by design. EMAIL_FROM: ${EMAIL_FROM:-}
PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-} # Internal only — served via the caddy reverse proxy
# Booking emails (Brevo SMTP relay) — sent from the Stripe webhook expose:
SMTP_HOST: ${SMTP_HOST:-} - "3000"
SMTP_PORT: ${SMTP_PORT:-587}
SMTP_USER: ${SMTP_USER:-} caddy:
SMTP_PASS: ${SMTP_PASS:-} image: caddy:2-alpine
EMAIL_FROM: ${EMAIL_FROM:-} container_name: massage-caddy
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} restart: unless-stopped
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} ports:
# Internal only — served via the caddy reverse proxy - "8080:8080"
expose: environment:
- "3000" DOMAIN: ${DOMAIN:-localhost}
# Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080
caddy: # (matches the ORIGIN vars below). Switch to "https" only if you also
image: docker.io/library/caddy:2-alpine # update ORIGIN/PUBLIC_* URLs and provide a cert issuer.
container_name: massage-caddy CADDY_SCHEME: ${CADDY_SCHEME:-http}
restart: unless-stopped volumes:
ports: - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
- "8080:8080" depends_on:
environment: - app-admin
DOMAIN: ${DOMAIN:-localhost} - app-public
# Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 - pocketbase
# (matches the ORIGIN vars below). Switch to "https" only if you also
# update ORIGIN/PUBLIC_* URLs and provide a cert issuer. volumes:
CADDY_SCHEME: ${CADDY_SCHEME:-http} pocketbase:
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
depends_on:
- app-admin
- app-public
- pocketbase
volumes:
pocketbase:

View file

@ -347,7 +347,7 @@
{#if payState === 'idle' || payState === 'creating'} {#if payState === 'idle' || payState === 'creating'}
<button <button
type="submit" type="submit"
class="btn w-full rounded-full border-0 text-primary-content" class="btn w-full rounded-full border-0 text-white"
style="background-color: var(--color-primary, #8a9a7b);" style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'creating'} disabled={payState === 'creating'}
> >
@ -382,7 +382,7 @@
{#if payState === 'ready' || payState === 'confirming'} {#if payState === 'ready' || payState === 'confirming'}
<button <button
type="button" type="button"
class="btn mt-4 w-full rounded-full border-0 text-primary-content" class="btn mt-4 w-full rounded-full border-0 text-white"
style="background-color: var(--color-primary, #8a9a7b);" style="background-color: var(--color-primary, #8a9a7b);"
disabled={payState === 'confirming'} disabled={payState === 'confirming'}
onclick={confirmPayment} onclick={confirmPayment}

View file

@ -21,7 +21,7 @@
{/if} {/if}
{#if data.buttonLabel} {#if data.buttonLabel}
<div class="animate-fade-in mt-10" style="animation-delay: 0.3s;"> <div class="animate-fade-in mt-10" style="animation-delay: 0.3s;">
<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'}> <a class="btn rounded-full border-0 bg-sage px-10 py-3 text-lg text-white shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || '/book'}>
{data.buttonLabel} {data.buttonLabel}
</a> </a>
</div> </div>

View file

@ -130,14 +130,6 @@
<h2 class="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}
{#if !visibleItems.length}
<!-- Never an empty section: no active items, a filter that matches none,
or commerce data unavailable (see the public layout's server log). -->
<p class="rounded-2xl border border-dashed border-charcoal/15 px-6 py-10 text-center text-charcoal/60">
Nothing is available to book right now — please check back soon.
</p>
{/if}
<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]}
@ -212,7 +204,7 @@
class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5' ? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
: itemSlotsByDay?.size : itemSlotsByDay?.size
? 'bg-sage text-primary-content hover:bg-sage-dark' ? 'bg-sage text-white hover:bg-sage-dark'
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}" : 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen} disabled={!itemSlotsByDay?.size && !ui?.pickerOpen}
onclick={() => togglePicker(item.id)} onclick={() => togglePicker(item.id)}
@ -222,7 +214,7 @@
{:else} {:else}
<button <button
type="button" type="button"
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" class="inline-flex items-center justify-center gap-2 rounded-full bg-sage px-6 py-2.5 text-sm font-medium text-white 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)}
> >
@ -260,7 +252,7 @@
aria-pressed={selected} aria-pressed={selected}
onclick={() => (ui.selectedDayKey = day.dateKey)} onclick={() => (ui.selectedDayKey = day.dateKey)}
class="aspect-square rounded-full 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-white'
: 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'
: 'cursor-default text-charcoal/25'} {!day.inMonth ? 'opacity-40' : ''} {day.isToday && : 'cursor-default text-charcoal/25'} {!day.inMonth ? 'opacity-40' : ''} {day.isToday &&

View file

@ -1,282 +1,199 @@
import type { CalendarEventRecord, ContentBlock } from './types'; import type { CalendarEventRecord, ContentBlock } from './types';
type UnknownRecord = Record<string, unknown>; type UnknownRecord = Record<string, unknown>;
export type CalendarDay = { export type CalendarDay = {
date: Date; date: Date;
dateKey: string; dateKey: string;
dayNumber: number; dayNumber: number;
inMonth: boolean; inMonth: boolean;
isToday: boolean; isToday: boolean;
}; };
export type CalendarMonth = { export type CalendarMonth = {
date: Date; date: Date;
label: string; label: string;
days: CalendarDay[]; days: CalendarDay[];
}; };
export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) { export function hasUpcomingCalendarBlock(blocks: ContentBlock[] = []) {
return blocks.some((block) => block.type === 'upcoming_calendar'); return blocks.some((block) => block.type === 'upcoming_calendar');
} }
export function toDateInput(value?: string | null) { export function toDateInput(value?: string | null) {
if (!value) return ''; if (!value) return '';
return value.slice(0, 10); return value.slice(0, 10);
} }
export function toDatetimeInput(value?: string | null) { export function toDatetimeInput(value?: string | null) {
if (!value) return ''; if (!value) return '';
const date = new Date(value); const date = new Date(value);
if (Number.isNaN(date.getTime())) return value.slice(0, 16); if (Number.isNaN(date.getTime())) return value.slice(0, 16);
const offset = date.getTimezoneOffset(); const offset = date.getTimezoneOffset();
const local = new Date(date.getTime() - offset * 60_000); const local = new Date(date.getTime() - offset * 60_000);
return local.toISOString().slice(0, 16); return local.toISOString().slice(0, 16);
} }
/** export function dateInputToPocketBase(value: string, allDay = true) {
* Convert a form date value to PocketBase format. All-day dates are stored as if (!value) return '';
* UTC midnight of that calendar date. Timed values (`YYYY-MM-DDTHH:mm` from a if (!allDay && value.includes('T')) {
* datetime-local input) are wall-clock times in `timeZone` — NOT the server's return new Date(value).toISOString();
* zone, which is UTC in the container and silently shifted every save. }
*/ return `${value.slice(0, 10)} 00:00:00.000Z`;
export function dateInputToPocketBase(value: string, allDay = true, timeZone = 'UTC') { }
if (!value) return '';
if (!allDay && value.includes('T')) { export function parseEventDate(value?: string | null) {
return zonedInputToIso(value, timeZone); if (!value) return null;
} const datePart = value.slice(0, 10);
return `${value.slice(0, 10)} 00:00:00.000Z`; const [year, month, day] = datePart.split('-').map(Number);
} if (!year || !month || !day) return null;
return new Date(year, month - 1, day);
// ── Site-timezone helpers ────────────────────────────────────────────── }
// Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so
// what the admin types is what customers book, and the server render (UTC export function dateKey(date: Date) {
// container) matches the browser render. const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, '0');
const LOCAL_INPUT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/; const day = `${date.getDate()}`.padStart(2, '0');
return `${year}-${month}-${day}`;
function zonedParts(date: Date, timeZone: string) { }
const parts = new Intl.DateTimeFormat('en-US', {
timeZone, export function addDays(date: Date, days: number) {
hourCycle: 'h23', const copy = new Date(date);
year: 'numeric', copy.setDate(copy.getDate() + days);
month: '2-digit', return copy;
day: '2-digit', }
hour: '2-digit',
minute: '2-digit', export function addMonths(date: Date, months: number) {
second: '2-digit' return new Date(date.getFullYear(), date.getMonth() + months, 1);
}).formatToParts(date); }
const get = (type: string) => parts.find((part) => part.type === type)?.value ?? '00';
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour'), minute: get('minute'), second: get('second') }; export function startOfMonth(date = new Date()) {
} return new Date(date.getFullYear(), date.getMonth(), 1);
}
/** Milliseconds `timeZone` is ahead of UTC at instant `date`. */
function zoneOffsetMs(date: Date, timeZone: string) { export function endOfMonth(date = new Date()) {
const p = zonedParts(date, timeZone); return new Date(date.getFullYear(), date.getMonth() + 1, 0);
const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second); }
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
} export function getUpcomingCalendarRange(reference = new Date()) {
const start = startOfMonth(reference);
function parseInstant(value?: string | null) { const end = endOfMonth(addMonths(reference, 1));
if (!value) return null; return { start, end };
const date = new Date(value.replace(' ', 'T')); }
return Number.isNaN(date.getTime()) ? null : date;
} export function createCalendarMonth(monthDate: Date, reference = new Date()): CalendarMonth {
const first = startOfMonth(monthDate);
/** `2026-10-08T10:00` as a wall-clock time in `timeZone` → ISO UTC string ('' if invalid). */ const monthEnd = endOfMonth(monthDate);
export function zonedInputToIso(value: string, timeZone: string) { const gridStart = addDays(first, -first.getDay());
const m = LOCAL_INPUT_RE.exec(value); const gridEnd = addDays(monthEnd, 6 - monthEnd.getDay());
if (!m) return ''; const todayKey = dateKey(reference);
const wallClockAsUtc = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]); const days: CalendarDay[] = [];
let instant = wallClockAsUtc - zoneOffsetMs(new Date(wallClockAsUtc), timeZone);
// Re-check at the candidate instant in case a DST change lies in between. for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) {
const corrected = wallClockAsUtc - zoneOffsetMs(new Date(instant), timeZone); days.push({
if (corrected !== instant) instant = corrected; date: new Date(day),
return new Date(instant).toISOString(); dateKey: dateKey(day),
} dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(),
/** isToday: dateKey(day) === todayKey
* A stored instant → `YYYY-MM-DDTHH:mm` in `timeZone`, for datetime-local });
* inputs. Values that are already wall-clock input strings pass through; a }
* bare date becomes midnight.
*/ return {
export function toZonedDatetimeInput(value: string | null | undefined, timeZone: string) { date: first,
if (!value) return ''; label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }),
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return value; days
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00`; };
const date = parseInstant(value); }
if (!date) return '';
const p = zonedParts(date, timeZone); export function getCurrentAndNextMonths(reference = new Date()) {
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`; const current = startOfMonth(reference);
} return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)];
}
/** "8 Oct 2026, 10:00" in `timeZone`. Fixed locale so SSR and browser agree. */
export function formatDateTime(value: string | null | undefined, timeZone: string) { export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) {
const date = parseInstant(value); return startA <= endB && endA >= startB;
if (!date) return ''; }
return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
} export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
/** "10:00" in `timeZone`. */ const end = parseEventDate(event.end) || start;
export function formatTime(value: string | null | undefined, timeZone: string) { return end < start ? { start: end, end: start } : { start, end };
const date = parseInstant(value); }
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date); export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
} const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
export function parseEventDate(value?: string | null) { }
if (!value) return null;
const datePart = value.slice(0, 10); export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const [year, month, day] = datePart.split('-').map(Number); const range = eventRange(event);
if (!year || !month || !day) return null; return rangesOverlap(range.start, range.end, start, end);
return new Date(year, month - 1, day); }
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
export function dateKey(date: Date) { return {
const year = date.getFullYear(); id: String(record.id || ''),
const month = `${date.getMonth() + 1}`.padStart(2, '0'); name: String(record.name || ''),
const day = `${date.getDate()}`.padStart(2, '0'); start: String(record.start || ''),
return `${year}-${month}-${day}`; end: record.end ? String(record.end) : '',
} description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
export function addDays(date: Date, days: number) { link: record.link ? String(record.link) : '',
const copy = new Date(date); categories: normalizeCategories(record.categories),
copy.setDate(copy.getDate() + days); published: Boolean(record.published),
return copy; allDay: record.allDay !== false
} };
}
export function addMonths(date: Date, months: number) {
return new Date(date.getFullYear(), date.getMonth() + months, 1); export function normalizeCategories(value: unknown): string[] {
} if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
export function startOfMonth(date = new Date()) { }
return new Date(date.getFullYear(), date.getMonth(), 1); if (typeof value === 'string') {
} return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
export function endOfMonth(date = new Date()) { return [];
return new Date(date.getFullYear(), date.getMonth() + 1, 0); }
}
export function categoriesToText(categories: string[] = []) {
export function getUpcomingCalendarRange(reference = new Date()) { return categories.join(', ');
const start = startOfMonth(reference); }
const end = endOfMonth(addMonths(reference, 1));
return { start, end }; export function extractCategories(events: CalendarEventRecord[]) {
} return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
/** `weekStartsOn`: 0 = Sunday (default), 1 = Monday. */
export function createCalendarMonth(monthDate: Date, reference = new Date(), weekStartsOn: 0 | 1 = 0): CalendarMonth { export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
const first = startOfMonth(monthDate); if (!categories.length) return true;
const monthEnd = endOfMonth(monthDate); return event.categories?.some((category) => categories.includes(category));
const gridStart = addDays(first, -((first.getDay() - weekStartsOn + 7) % 7)); }
const gridEnd = addDays(monthEnd, 6 - ((monthEnd.getDay() - weekStartsOn + 7) % 7));
const todayKey = dateKey(reference); export function sortEvents(events: CalendarEventRecord[]) {
const days: CalendarDay[] = []; return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
for (let day = new Date(gridStart); day <= gridEnd; day = addDays(day, 1)) { const startB = parseEventDate(b.start)?.getTime() ?? 0;
days.push({ return startA - startB || a.name.localeCompare(b.name);
date: new Date(day), });
dateKey: dateKey(day), }
dayNumber: day.getDate(),
inMonth: day.getMonth() === first.getMonth(), export function formatEventDateRange(event: CalendarEventRecord) {
isToday: dateKey(day) === todayKey const start = parseEventDate(event.start);
}); const end = parseEventDate(event.end);
} if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
return { if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
date: first, return `${formatter.format(start)} – ${formatter.format(end)}`;
label: first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' }), }
days
}; export function normalizeLink(link?: string) {
} const value = String(link || '').trim();
if (!value) return '';
export function getCurrentAndNextMonths(reference = new Date()) { if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
const current = startOfMonth(reference); if (/^https?:\/\//i.test(value)) return value;
return [createCalendarMonth(current, reference), createCalendarMonth(addMonths(current, 1), reference)]; return `/${value.replace(/^\/+/, '')}`;
} }
export function rangesOverlap(startA: Date, endA: Date, startB: Date, endB: Date) { export function isExternalLink(link?: string) {
return startA <= endB && endA >= startB; return /^https?:\/\//i.test(String(link || ''));
} }
export function eventRange(event: Pick<CalendarEventRecord, 'start' | 'end'>) {
const start = parseEventDate(event.start) || new Date();
const end = parseEventDate(event.end) || start;
return end < start ? { start: end, end: start } : { start, end };
}
export function eventOverlapsDay(event: CalendarEventRecord, day: Date) {
const { start, end } = eventRange(event);
return rangesOverlap(start, end, day, day);
}
export function eventOverlapsRange(event: CalendarEventRecord, start: Date, end: Date) {
const range = eventRange(event);
return rangesOverlap(range.start, range.end, start, end);
}
export function normalizeEvent(record: UnknownRecord): CalendarEventRecord {
return {
id: String(record.id || ''),
name: String(record.name || ''),
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
description: record.description ? String(record.description) : '',
color: String(record.color || '#8a9a7b'),
link: record.link ? String(record.link) : '',
categories: normalizeCategories(record.categories),
published: Boolean(record.published),
allDay: record.allDay !== false
};
}
export function normalizeCategories(value: unknown): string[] {
if (Array.isArray(value)) {
return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))];
}
if (typeof value === 'string') {
return [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
}
return [];
}
export function categoriesToText(categories: string[] = []) {
return categories.join(', ');
}
export function extractCategories(events: CalendarEventRecord[]) {
return [...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b));
}
export function eventMatchesCategories(event: CalendarEventRecord, categories: string[] = []) {
if (!categories.length) return true;
return event.categories?.some((category) => categories.includes(category));
}
export function sortEvents(events: CalendarEventRecord[]) {
return [...events].sort((a, b) => {
const startA = parseEventDate(a.start)?.getTime() ?? 0;
const startB = parseEventDate(b.start)?.getTime() ?? 0;
return startA - startB || a.name.localeCompare(b.name);
});
}
export function formatEventDateRange(event: CalendarEventRecord) {
const start = parseEventDate(event.start);
const end = parseEventDate(event.end);
if (!start) return '';
const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
if (!end || dateKey(start) === dateKey(end)) return formatter.format(start);
return `${formatter.format(start)} – ${formatter.format(end)}`;
}
export function normalizeLink(link?: string) {
const value = String(link || '').trim();
if (!value) return '';
if (value.startsWith('/') || value.startsWith('#') || value.startsWith('mailto:') || value.startsWith('tel:')) return value;
if (/^https?:\/\//i.test(value)) return value;
return `/${value.replace(/^\/+/, '')}`;
}
export function isExternalLink(link?: string) {
return /^https?:\/\//i.test(String(link || ''));
}

View file

@ -0,0 +1,187 @@
import type PocketBase from 'pocketbase';
import type { Basket, BasketLine } from '../types';
import { getFileUrl } from '../pb';
export const BASKET_COOKIE = 'basket_id';
/** Basket lifetime — refreshed on every basket API call. */
export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h
/** How long a slot stays held once added to a basket / after a failed payment. */
export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min
/** Hold extended to this once a payment is in progress, so the slot survives
* the customer entering card details / retrying a declined card. */
export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min
function now() {
return new Date();
}
function iso(date: Date) {
return date.toISOString();
}
/**
* Release any slots whose hold has expired, removing their basket lines
* and flipping them back to `available`. Also marks expired active
* baskets as `abandoned`. Runs lazily on basket reads / checkout.
*
* The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather
* than via a PocketBase date-string filter, so a slot is never released
* *before* its hold genuinely lapses — regardless of how PocketBase stores /
* compares the date field. A slot is held for the full SLOT_HOLD_MS (or
* SLOT_CHECKOUT_HOLD_MS during payment).
*/
export async function sweepExpiredHolds(pb: PocketBase) {
const nowMs = Date.now();
// 1. Release expired slot holds (and drop the lines holding them)
const heldSlots = await pb
.collection('slots')
.getFullList({ filter: `status = 'held'` })
.catch(() => []);
for (const slot of heldSlots) {
const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN;
// Still valid, or no parseable hold to judge by — leave it alone.
if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `slot = "${slot.id}"` })
.catch(() => []);
for (const line of lines) {
await pb.collection('basket_lines').delete(line.id).catch(() => {});
}
await pb
.collection('slots')
.update(slot.id, { status: 'available', heldUntil: null })
.catch(() => {});
}
// 2. Abandon expired active baskets (their slot holds were already
// covered by heldUntil above — same 10-min window < 24h basket TTL)
const nowIso = iso(now());
await pb
.collection('baskets')
.getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` })
.then(async (expired) => {
for (const basket of expired) {
await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {});
}
})
.catch(() => {});
}
/** Map raw PB records (with expand) to our Basket type. */
function mapBasket(record: Record<string, any>, lines: Record<string, any>[]): Basket {
const mappedLines: BasketLine[] = lines.map((line) => {
const item = line.expand?.item;
const slot = line.expand?.slot;
const media = item?.expand?.image;
return {
id: line.id,
basket: line.basket,
item: line.item,
slot: line.slot || null,
quantity: line.quantity,
lineType: line.lineType,
itemName: item?.name,
itemPrice: item?.price,
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
slotStart: slot?.start,
slotEnd: slot?.end
};
});
return {
id: record.id,
status: record.status,
expiresAt: record.expiresAt,
email: record.email || null,
customerDetails: record.customerDetails || null,
stripePaymentIntentId: record.stripePaymentIntentId || null,
lines: mappedLines
};
}
/** Load a basket + its lines (with item/slot expand) by basket id. */
export async function loadBasket(pb: PocketBase, basketId: string): Promise<Basket | null> {
try {
const record = await pb.collection('baskets').getOne(basketId);
if (record.status !== 'active') return null;
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' });
return mapBasket(record, lines);
} catch {
return null;
}
}
/** Create a fresh active basket. */
export async function createBasket(pb: PocketBase): Promise<Basket> {
const record = await pb.collection('baskets').create({
status: 'active',
expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS))
});
return {
id: record.id,
status: 'active',
expiresAt: record.expiresAt,
email: null,
customerDetails: null,
stripePaymentIntentId: null,
lines: []
};
}
/** Touch the basket expiry (rolling TTL). */
export async function touchBasket(pb: PocketBase, basketId: string) {
await pb
.collection('baskets')
.update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) })
.catch(() => {});
}
/** Release a slot hold for a basket line (slot back to available). */
export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) {
if (!line.slot) return;
await pb
.collection('slots')
.update(line.slot, { status: 'available', heldUntil: null })
.catch(() => {});
}
/**
* Re-reserve (extend) the hold on every slot line in a basket, as long as
* the slot is still in `held` status. Used:
* - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a
* service survives the customer entering card details / retrying a
* declined card;
* - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer
* can retry within a fresh 10-minute window.
* The slot is genuinely still the customer's (nobody else could grab it
* while `held`), so renewing is safe. Slots whose status is no longer
* `held` (e.g. released and re-booked by someone else) are returned so the
* caller can inform the user.
*/
export async function extendBasketHolds(
pb: PocketBase,
basketId: string,
durationMs = SLOT_HOLD_MS
): Promise<string[]> {
const unheld: string[] = [];
const lines = await pb
.collection('basket_lines')
.getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` })
.catch(() => []);
const until = iso(new Date(Date.now() + durationMs));
for (const line of lines) {
const slotId = line.slot;
if (!slotId) continue;
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
if (slot && slot.status === 'held') {
await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {});
} else {
unheld.push(line.id);
}
}
return unheld;
}

View file

@ -62,14 +62,13 @@ export function emailSiteUrl(): string {
} }
export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> { export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> {
const [footer, colors] = await Promise.all([getGlobalData(pb, 'footer', {}), getGlobalData(pb, 'colors', {})]); const [business, colors] = await Promise.all([
return emailSettingsFrom(footer, colors); getGlobalData(pb, 'footer', defaultFooter),
} getGlobalData(pb, 'colors', defaultColors)
]);
function emailSettingsFrom(footer: Partial<FooterGlobal> | null, colors: Partial<ColorsGlobal> | null): EmailSettings {
return { return {
business: { ...defaultFooter, ...(footer || {}) }, business,
colors: { ...defaultColors, ...(colors || {}) }, colors,
siteUrl: emailSiteUrl(), siteUrl: emailSiteUrl(),
timezone: env.SITE_TIMEZONE || 'Europe/Oslo', timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
currency: env.STRIPE_CURRENCY || 'eur' currency: env.STRIPE_CURRENCY || 'eur'
@ -105,47 +104,11 @@ function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSetting
return events.length ? buildIcs(events, settings.business.businessName || 'Booking') : null; return events.length ? buildIcs(events, settings.business.businessName || 'Booking') : null;
} }
/** async function loadOrderContext(pb: PocketBase, orderId: string, settings: EmailSettings) {
* Everything the booking emails for one order need, as raw PocketBase const order = await pb.collection('orders').getOne(orderId);
* records (REST JSON shape). Built by `loadOrderEmailData` (admin resend) or const lineRecords = await pb
* by the PocketBase shop hooks (`orderEmailData` in pb_hooks/shop/lib.js, .collection('order_lines')
* after a payment) — keep the two in sync. .getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' });
*/
export type OrderEmailData = {
order: Record<string, any>;
/** order_lines with `expand.slot` and `expand.item` */
lines: Record<string, any>[];
templates: Partial<Record<EmailTemplateKey, Record<string, any> | null>>;
footer: Partial<FooterGlobal> | null;
colors: Partial<ColorsGlobal> | null;
};
export async function loadOrderEmailData(pb: PocketBase, orderId: string): Promise<OrderEmailData> {
const globalData = (key: string) =>
pb
.collection('globals')
.getFirstListItem(pb.filter('key = {:key}', { key }))
.then((record) => record.data || null)
.catch(() => null);
const template = (key: string) =>
pb
.collection('email_templates')
.getFirstListItem(pb.filter('key = {:key}', { key }))
.catch(() => null);
const [order, lines, customer_confirmation, client_alert, footer, colors] = await Promise.all([
pb.collection('orders').getOne(orderId),
pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' }),
template('customer_confirmation'),
template('client_alert'),
globalData('footer'),
globalData('colors')
]);
return { order, lines, templates: { customer_confirmation, client_alert }, footer, colors };
}
function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
const order = data.order;
const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || '')));
const lines: EmailLine[] = lineRecords.map((line) => { const lines: EmailLine[] = lineRecords.map((line) => {
const start = line.start ? new Date(line.start).toISOString() : null; const start = line.start ? new Date(line.start).toISOString() : null;
@ -180,34 +143,32 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
lines, lines,
...settings ...settings
}; };
return { ctx, lineIds: lineRecords.map((line) => line.id) }; return { order, ctx, lineIds: lineRecords.map((line) => line.id) };
} }
/** Email status fields to write on the order (customerEmailSentAt / clientEmailSentAt / emailError). */
export type OrderEmailPatch = Record<string, string>;
/** /**
* Render and send the booking emails for a paid order. Never throws — a * Render and send the booking emails for a paid order, then record the
* failed email must not fail the payment flow; the admin can resend from * outcome on the order (customerEmailSentAt / clientEmailSentAt / emailError).
* /orders. Returns the outcomes and the status patch for the caller to save. * Never throws — a failed email must not fail the Stripe webhook; the admin
* can resend from /orders.
*/ */
export async function sendOrderEmailsFromData( export async function sendOrderEmails(
data: OrderEmailData, pb: PocketBase,
orderId: string,
kinds: EmailKind[] = ['customer', 'client'] kinds: EmailKind[] = ['customer', 'client']
): Promise<{ outcomes: Partial<Record<EmailKind, EmailOutcome>>; patch: OrderEmailPatch }> { ): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {}; const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {};
const patch: OrderEmailPatch = {};
const orderId = String(data.order?.id || '');
try { try {
const settings = emailSettingsFrom(data.footer, data.colors); const settings = await loadEmailSettings(pb);
const { ctx, lineIds } = orderEmailContext(data, settings); const { order, ctx, lineIds } = await loadOrderContext(pb, orderId, settings);
const errorLines = String(data.order.emailError || '') const patch: Record<string, string> = {};
const errorLines = String(order.emailError || '')
.split('\n') .split('\n')
.filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind]))); .filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind])));
for (const kind of kinds) { for (const kind of kinds) {
const template = normalizeEmailTemplate(TEMPLATE_KEY[kind], data.templates[TEMPLATE_KEY[kind]] ?? null); const template = await loadEmailTemplate(pb, TEMPLATE_KEY[kind]);
if (!template.enabled) { if (!template.enabled) {
outcomes[kind] = 'disabled'; outcomes[kind] = 'disabled';
continue; continue;
@ -244,31 +205,14 @@ export async function sendOrderEmailsFromData(
} }
patch.emailError = errorLines.join('\n').slice(0, 2000); patch.emailError = errorLines.join('\n').slice(0, 2000);
await pb
.collection('orders')
.update(orderId, patch)
.catch((e) => console.error(`[email] could not record email status on order ${orderId}:`, e));
} catch (e) { } catch (e) {
console.error(`[email] could not prepare emails for order ${orderId}:`, e); console.error(`[email] could not prepare emails for order ${orderId}:`, e);
for (const kind of kinds) outcomes[kind] ??= 'failed'; for (const kind of kinds) outcomes[kind] ??= 'failed';
} }
return { outcomes, patch };
}
/** Load, send and record the booking emails for an order (admin resend, with the signed-in admin's client). */
export async function sendOrderEmails(
pb: PocketBase,
orderId: string,
kinds: EmailKind[] = ['customer', 'client']
): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
let data: OrderEmailData;
try {
data = await loadOrderEmailData(pb, orderId);
} catch (e) {
console.error(`[email] could not load order ${orderId}:`, e);
return Object.fromEntries(kinds.map((kind) => [kind, 'failed' as const]));
}
const { outcomes, patch } = await sendOrderEmailsFromData(data, kinds);
await pb
.collection('orders')
.update(orderId, patch)
.catch((e) => console.error(`[email] could not record email status on order ${orderId}:`, e));
return outcomes; return outcomes;
} }

View file

@ -0,0 +1,53 @@
import PocketBase, { ClientResponseError } from 'pocketbase';
import { env } from '$env/dynamic/private';
let adminPb: PocketBase | null = null;
let authPromise: Promise<PocketBase> | null = null;
async function authenticate(): Promise<PocketBase> {
const url = env.POCKETBASE_INTERNAL_URL;
const pb = new PocketBase(url);
pb.autoCancellation(false);
const email = env.POCKETBASE_ADMIN_EMAIL;
const password = env.POCKETBASE_ADMIN_PASSWORD;
if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set');
await pb.collection('_superusers').authWithPassword(email, password);
adminPb = pb;
return pb;
}
/**
* Server-only PocketBase client authenticated as admin.
* Used by basket/checkout/webhook API routes that need to bypass
* collection-level API rules (create baskets, hold slots, create orders).
*
* Concurrent callers share one in-flight auth attempt; if the cached token
* has since been invalidated (401 on first use), we re-authenticate once.
*/
export async function getAdminPb(): Promise<PocketBase> {
if (adminPb?.authStore.isValid) return adminPb;
authPromise ??= authenticate().finally(() => {
authPromise = null;
});
return authPromise;
}
/**
* Run `fn` with the admin client; on a 401 (stale/invalidated token),
* re-authenticate and retry exactly once.
*/
export async function withAdminPb<T>(fn: (pb: PocketBase) => Promise<T>): Promise<T> {
const pb = await getAdminPb();
try {
return await fn(pb);
} catch (e) {
if (e instanceof ClientResponseError && e.status === 401) {
pb.authStore.clear();
adminPb = null;
return fn(await getAdminPb());
}
throw e;
}
}

View file

@ -1,52 +0,0 @@
import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb';
import type { ItemRecord, SlotRecord } from '../types';
/**
* Active items and future available slots, shaped for the Shop/Checkout
* blocks. Used by the public layout and the admin draft preview so both
* render the same shop.
*
* Works with an anonymous client: the API rules expose active items,
* available slots and media publicly. Errors propagate.
*/
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> {
const [itemRecords, slotRecords] = await Promise.all([
pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }),
pb.collection('slots').getFullList({
filter: pb.filter("status = 'available' && start >= {:now}", { now: new Date() }),
sort: 'start'
})
]);
const items = itemRecords.map((record): ItemRecord => {
const media = record.expand?.image;
return {
id: record.id,
name: record.name,
description: record.description || '',
price: record.price,
image: record.image || '',
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type,
stock: record.stock ?? null,
duration: record.duration ?? null,
active: record.active
};
});
const slots = slotRecords.map(
(record): SlotRecord => ({
id: record.id,
item: record.item,
start: record.start,
end: record.end || '',
status: record.status,
heldUntil: record.heldUntil || null,
order: record.order || null,
notes: record.notes || ''
})
);
return { items, slots };
}

View file

@ -1,77 +0,0 @@
import { defaultColors, type ColorsGlobal } from './types';
// Site colours (Site design → Colors) as CSS variables, rendered server-side
// into a <style> tag so pages don't flash the default colours on load.
//
// Mapping onto DaisyUI's theme: primary = site Primary, secondary = site
// Accent (so `btn-secondary` follows the site instead of DaisyUI's default
// pink), each with a text colour picked for contrast.
// Colours are admin-entered free text that ends up inside <style>, so only
// plain colour values are allowed through.
const SAFE_COLOR = /^(#[0-9a-f]{3,8}|[a-z]{3,30}|(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch)\([0-9a-z.,%\s/+-]{1,60}\))$/i;
export function safeColor(value: unknown, fallback: string): string {
const color = String(value ?? '').trim();
return SAFE_COLOR.test(color) ? color : fallback;
}
function hexToRgb(hex: string): [number, number, number] | null {
let h = hex.replace('#', '');
if (h.length === 3 || h.length === 4) h = [...h.slice(0, 3)].map((c) => c + c).join('');
if (h.length !== 6 && h.length !== 8) return null;
const n = parseInt(h.slice(0, 6), 16);
return Number.isNaN(n) ? null : [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function luminance([r, g, b]: [number, number, number]) {
const lin = (c: number) => {
const s = c / 255;
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
}
const LIGHT_TEXT = '#ffffff';
const DARK_TEXT = '#1f2937';
/** White or dark text, whichever contrasts more with `color` (white if it isn't a hex colour). */
export function readableTextOn(color: string): string {
const rgb = color.startsWith('#') ? hexToRgb(color) : null;
if (!rgb) return LIGHT_TEXT;
const l = luminance(rgb);
const darkL = luminance(hexToRgb(DARK_TEXT)!);
return (1.05 / (l + 0.05)) >= (l + 0.05) / (darkL + 0.05) ? LIGHT_TEXT : DARK_TEXT;
}
/** DaisyUI brand variables only — used by the admin, whose own text/background stay neutral. */
export function brandThemeVars(colors: Partial<ColorsGlobal> | null | undefined): Record<string, string> {
const primary = safeColor(colors?.primary, defaultColors.primary);
const secondary = safeColor(colors?.accent, defaultColors.accent);
return {
'--color-primary': primary,
'--color-primary-content': readableTextOn(primary),
'--color-secondary': secondary,
'--color-secondary-content': readableTextOn(secondary)
};
}
/** Every site colour variable — public site and the admin preview. */
export function siteThemeVars(colors: Partial<ColorsGlobal> | null | undefined): Record<string, string> {
return {
'--color-bg': safeColor(colors?.background, defaultColors.background),
'--color-heading': safeColor(colors?.heading, defaultColors.heading),
'--color-subheading': safeColor(colors?.subheading, defaultColors.subheading),
'--color-text': safeColor(colors?.text, defaultColors.text),
'--color-accent': safeColor(colors?.accent, defaultColors.accent),
...brandThemeVars(colors)
};
}
/** `<style>` element setting `vars` on :root, for `{@html}` in <svelte:head>. Values are already sanitised. */
export function rootStyleTag(vars: Record<string, string>): string {
const body = Object.entries(vars)
.map(([name, value]) => `${name}:${value}`)
.join(';');
return `<style>:root{${body}}</style>`;
}

View file

@ -60,13 +60,9 @@
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": {} "options": {}
}, }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
],
"indexes": [
"CREATE UNIQUE INDEX `idx_pages_slug_unique` ON `pages` (`slug`)"
], ],
"indexes": [],
"options": {} "options": {}
}, },
{ {
@ -106,13 +102,9 @@
"options": { "options": {
"maxSize": 1000000 "maxSize": 1000000
} }
}, }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
],
"indexes": [
"CREATE UNIQUE INDEX `idx_globals_key_unique` ON `globals` (`key`)"
], ],
"indexes": [],
"options": {} "options": {}
}, },
{ {
@ -170,9 +162,7 @@
"max": 180, "max": 180,
"pattern": "" "pattern": ""
} }
}, }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [], "indexes": [],
"options": {} "options": {}
@ -302,9 +292,7 @@
"presentable": false, "presentable": false,
"unique": false, "unique": false,
"options": {} "options": {}
}, }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_events_start` ON `events` (`start`)", "CREATE INDEX `idx_events_start` ON `events` (`start`)",
@ -331,9 +319,7 @@
{ "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] }, { "id": "sel_itemtype001", "name": "type", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "item_with_time"] },
{ "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
{ "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, { "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
{ "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [], "indexes": [],
"autodate": true, "autodate": true,
@ -357,9 +343,7 @@
{ "id": "sel_slotstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["available", "held", "booked"] }, { "id": "sel_slotstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["available", "held", "booked"] },
{ "id": "date_slotheldun0", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_slotheldun0", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "rel_slotorder01", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_slotorder01", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, { "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)", "CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)",
@ -375,8 +359,8 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": null, "createRule": "",
"updateRule": null, "updateRule": "",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
@ -384,9 +368,7 @@
{ "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } }, { "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
{ "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } }, { "id": "json_basketcust", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } },
{ "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, { "id": "text_basketstrip", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_baskets_status` ON `baskets` (`status`)" "CREATE INDEX `idx_baskets_status` ON `baskets` (`status`)"
@ -401,18 +383,16 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": null, "createRule": "",
"updateRule": null, "updateRule": "",
"deleteRule": null, "deleteRule": "",
"fields": [ "fields": [
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
{ "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
{ "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, { "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } },
{ "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, { "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)", "CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
@ -428,7 +408,7 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": null, "createRule": "",
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
@ -441,9 +421,7 @@
{ "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }, { "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } },
{ "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }, { "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)" "CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)"
@ -458,9 +436,9 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": null, "createRule": "",
"updateRule": null, "updateRule": "",
"deleteRule": null, "deleteRule": "",
"fields": [ "fields": [
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" }, { "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
{ "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
@ -470,9 +448,7 @@
{ "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, { "id": "sel_ollinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] },
{ "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } }, { "id": "text_olname00001", "name": "name", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
{ "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "num_olprice00001", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
{ "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, { "id": "date_olstart0001", "name": "start", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)" "CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)"
@ -496,9 +472,7 @@
{ "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } }, { "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } },
{ "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } }, { "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } },
{ "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, { "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } },
{ "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, { "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }
{"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false},
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
], ],
"indexes": [ "indexes": [
"CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)" "CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)"

View file

@ -1,44 +0,0 @@
/// Shop API — see shop/lib.js. The public app proxies to these routes (it
/// holds the basket cookie); they are also reachable directly, so every one
/// treats its input as untrusted. The basket id acts as the customer's
/// bearer token, exactly like the cookie it comes from.
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
shop.sweepExpiredHolds($app);
return e.json(200, { basket: shop.basketPayload($app, shop.loadActiveBasket($app, e.request.pathValue('id'))) });
});
routerAdd('POST', '/api/shop/basket', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, { basket: shop.basketAction($app, e.requestInfo().body) });
});
routerAdd('POST', '/api/shop/checkout', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, shop.startCheckout($app, e.requestInfo().body));
});
routerAdd('POST', '/api/shop/stripe-webhook', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
// The signature covers the exact bytes Stripe sent: read the raw body.
const raw = toString(e.request.body);
return e.json(200, shop.handleStripeWebhook($app, raw, e.request.header.get('Stripe-Signature')));
});
routerAdd('GET', '/api/shop/order', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
return e.json(200, shop.orderStatus($app, e.request.url.query().get('payment_intent')));
});
routerAdd('POST', '/api/shop/order-email-status', (e) => {
const shop = require(`${__hooks}/shop/lib.js`);
shop.recordEmailStatus($app, e.request.header.get('X-Internal-Secret'), e.requestInfo().body);
return e.noContent(204);
});
// Expired holds are also swept before every basket/checkout call; this
// frees slots for the shop listing even when nobody is using a basket.
cronAdd('shopSweepHolds', '* * * * *', () => {
require(`${__hooks}/shop/lib.js`).sweepExpiredHolds($app);
});

View file

@ -1,550 +0,0 @@
// Shop logic, run inside PocketBase (JSVM). Everything that writes commerce
// data — baskets, slot holds, Stripe payments, orders — lives here, so the
// public app needs no privileged credentials: it only proxies requests and
// keeps the basket cookie. Routes are registered in ../shop.pb.js.
//
// JSVM notes (PocketBase 0.23): code is synchronous; route/cron handlers run
// in isolated contexts, so each handler `require()`s this module; `$app` here
// bypasses collection API rules.
const BASKET_TTL_MS = 24 * 60 * 60 * 1000;
/** How long a slot stays held once added to a basket / after a failed payment. */
const SLOT_HOLD_MS = 10 * 60 * 1000;
/** Hold while a payment is in progress (entering card details, retrying a declined card). */
const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000;
/** Stripe's default tolerance for webhook timestamps. */
const WEBHOOK_TOLERANCE_S = 300;
// ── Helpers ─────────────────────────────────────────────────────────────
function isoIn(ms) {
return new Date(Date.now() + ms).toISOString();
}
/** PocketBase datetime string ("2026-01-01 10:00:00.000Z") → epoch ms, NaN if empty. */
function toMs(value) {
const s = String(value || '');
return s ? Date.parse(s.replace(' ', 'T')) : NaN;
}
/** Record → plain JSON object (the same shape the REST API returns, including expand). */
function plain(record) {
return JSON.parse(JSON.stringify(record));
}
function findOrNull(app, collection, id) {
if (!id) return null;
try {
return app.findRecordById(collection, id);
} catch (_) {
return null;
}
}
function findAll(app, collection, filter, params, sort) {
return app.findRecordsByFilter(collection, filter, sort || '', 0, 0, params || {});
}
function newRecord(app, collection, data) {
const record = new Record(app.findCollectionByNameOrId(collection));
record.load(data);
return record;
}
function conflict(message) {
return new ApiError(409, message);
}
// ── Holds and baskets ───────────────────────────────────────────────────
/**
* Release slots whose hold has lapsed (dropping the basket lines holding
* them) and abandon expired baskets. Runs every minute (cron) and before
* basket/checkout operations, so expiry is exact where it matters.
*/
function sweepExpiredHolds(app) {
const now = Date.now();
for (const slot of findAll(app, 'slots', "status = 'held'")) {
const until = toMs(slot.getString('heldUntil'));
// Still valid, or no parseable hold to judge by — leave it alone.
if (Number.isNaN(until) || until > now) continue;
try {
app.runInTransaction((tx) => {
for (const line of findAll(tx, 'basket_lines', 'slot = {:slot}', { slot: slot.id })) tx.delete(line);
const fresh = tx.findRecordById('slots', slot.id);
if (fresh.getString('status') !== 'held') return;
fresh.set('status', 'available');
fresh.set('heldUntil', '');
tx.save(fresh);
});
} catch (e) {
console.error('[shop] could not release slot', slot.id, e);
}
}
for (const basket of findAll(app, 'baskets', "status = 'active' && expiresAt < @now")) {
basket.set('status', 'abandoned');
try {
app.save(basket);
} catch (e) {
console.error('[shop] could not abandon basket', basket.id, e);
}
}
}
function loadActiveBasket(app, basketId) {
const basket = findOrNull(app, 'baskets', String(basketId || ''));
return basket && basket.getString('status') === 'active' ? basket : null;
}
function basketLines(app, basketId) {
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: basketId });
}
/** The basket as returned to the public app, which maps it to the `Basket` type. */
function basketPayload(app, basket) {
if (!basket) return null;
const lines = basketLines(app, basket.id);
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
return { record: plain(basket), lines: lines.map(plain) };
}
function createBasket(app) {
const basket = newRecord(app, 'baskets', { status: 'active', expiresAt: isoIn(BASKET_TTL_MS) });
app.save(basket);
return basket;
}
function releaseSlotHold(app, slotId) {
const slot = findOrNull(app, 'slots', slotId);
if (!slot || slot.getString('status') !== 'held') return;
slot.set('status', 'available');
slot.set('heldUntil', '');
app.save(slot);
}
/**
* Renew the hold on every slot line in a basket whose slot is still `held`
* (nobody else can take a held slot, so renewing is safe). Used at checkout
* start (30 min) and after a failed payment (10 min, so the customer can retry).
*/
function extendBasketHolds(app, basketId, durationMs) {
const until = isoIn(durationMs);
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
const slot = findOrNull(app, 'slots', line.getString('slot'));
if (slot && slot.getString('status') === 'held') {
slot.set('heldUntil', until);
app.save(slot);
}
}
}
/**
* Basket mutations. `body.basketId` is the customer's basket (from their
* cookie); a basket is created on the first add. Returns the basket payload.
*/
function basketAction(app, body) {
sweepExpiredHolds(app);
const action = String(body.action || '');
let basket = loadActiveBasket(app, body.basketId);
if (!basket && (action === 'add_item' || action === 'add_slot')) basket = createBasket(app);
if (!basket) throw new BadRequestError('No active basket — add an item first');
const lines = basketLines(app, basket.id);
switch (action) {
case 'add_item': {
const itemId = String(body.itemId || '');
const quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1);
const item = findOrNull(app, 'items', itemId);
if (!item || !item.getBool('active')) throw new NotFoundError('Item not found');
if (item.getString('type') !== 'item') throw new BadRequestError('Use add_slot for bookable services');
const existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId);
const newQty = (existing ? existing.getInt('quantity') : 0) + quantity;
const stock = item.get('stock');
if (stock != null && stock !== '' && newQty > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
if (existing) {
existing.set('quantity', newQty);
app.save(existing);
} else {
app.save(newRecord(app, 'basket_lines', { basket: basket.id, item: itemId, quantity, lineType: 'item' }));
}
break;
}
case 'add_slot': {
const slotId = String(body.slotId || '');
if (lines.some((l) => l.getString('slot') === slotId)) throw conflict('Slot already in your basket');
const slot = findOrNull(app, 'slots', slotId);
if (!slot) throw new NotFoundError('Slot not found');
if (slot.getString('status') !== 'available') throw conflict('Slot is no longer available');
// Line + hold in one transaction. basket_lines.slot is UNIQUE, so of
// two concurrent requests for the same slot only one can succeed.
try {
app.runInTransaction((tx) => {
const fresh = tx.findRecordById('slots', slotId);
if (fresh.getString('status') !== 'available') throw new Error('taken');
tx.save(newRecord(tx, 'basket_lines', { basket: basket.id, item: fresh.getString('item'), slot: slotId, quantity: 1, lineType: 'slot' }));
fresh.set('status', 'held');
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
tx.save(fresh);
});
} catch (_) {
throw conflict('Slot was just reserved by someone else');
}
break;
}
case 'update_quantity': {
const line = lines.find((l) => l.id === String(body.lineId || ''));
if (!line) throw new NotFoundError('Line not found in your basket');
if (line.getString('lineType') === 'slot') throw new BadRequestError('Slot lines have fixed quantity 1');
const quantity = Number(body.quantity);
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
const item = findOrNull(app, 'items', line.getString('item'));
const stock = item ? item.get('stock') : null;
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
line.set('quantity', quantity);
app.save(line);
break;
}
case 'remove_line': {
const line = lines.find((l) => l.id === String(body.lineId || ''));
if (!line) throw new NotFoundError('Line not found in your basket');
const slotId = line.getString('slot');
app.delete(line);
if (slotId) releaseSlotHold(app, slotId);
break;
}
default:
throw new BadRequestError('Unknown action: ' + action);
}
basket.set('expiresAt', isoIn(BASKET_TTL_MS)); // rolling TTL
app.save(basket);
return basketPayload(app, basket);
}
// ── Stripe ──────────────────────────────────────────────────────────────
/** Stripe's form encoding, including nested objects (`metadata[basket_id]=…`). */
function formEncode(params, prefix) {
const parts = [];
for (const key of Object.keys(params)) {
const value = params[key];
if (value === undefined || value === null) continue;
const name = prefix ? `${prefix}[${key}]` : key;
if (typeof value === 'object') parts.push(formEncode(value, name));
else parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(String(value)));
}
return parts.filter(Boolean).join('&');
}
/** Call the Stripe REST API. Throws an Error with Stripe's message on failure. */
function stripe(method, path, params) {
const key = $os.getenv('STRIPE_SECRET_KEY');
if (!key) throw new InternalServerError('Payments are not configured (STRIPE_SECRET_KEY is not set)');
// STRIPE_API_BASE only exists for local testing against stripe-mock.
const base = ($os.getenv('STRIPE_API_BASE') || 'https://api.stripe.com').replace(/\/$/, '');
const res = $http.send({
url: base + path,
method,
headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/x-www-form-urlencoded' },
body: params ? formEncode(params) : '',
timeout: 20
});
if (res.statusCode < 200 || res.statusCode >= 300) {
const message = (res.json && res.json.error && res.json.error.message) || 'Stripe request failed (HTTP ' + res.statusCode + ')';
throw new Error(message);
}
return res.json;
}
function currency() {
return ($os.getenv('STRIPE_CURRENCY') || 'eur').toLowerCase();
}
/**
* Start (or resume) payment for a basket: validate every line against the
* database (the source of truth for the total), then create or update the
* Stripe PaymentIntent. Returns the client secret for Stripe Elements.
*/
function startCheckout(app, body) {
const basketId = String(body.basketId || '');
// Extend holds BEFORE sweeping, so a slot whose hold just lapsed is rescued
// rather than released at the moment the customer tries to pay.
if (basketId) extendBasketHolds(app, basketId, SLOT_CHECKOUT_HOLD_MS);
sweepExpiredHolds(app);
if (!basketId) throw new BadRequestError('No active basket');
const basket = loadActiveBasket(app, basketId);
if (!basket) throw new BadRequestError('Your session has expired — please re-select your items');
const lines = basketLines(app, basket.id);
if (!lines.length) throw new BadRequestError('Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
const customer = {
name: String(body.name || '').trim(),
email: String(body.email || '').trim(),
phone: String(body.phone || '').trim(),
notes: String(body.notes || '').trim()
};
if (!customer.name) throw new BadRequestError('Name is required');
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email is required');
let totalCents = 0;
const summary = [];
for (const line of lines) {
const item = findOrNull(app, 'items', line.getString('item'));
if (!item || !item.getBool('active')) throw conflict('An item in your basket is no longer available');
const quantity = line.getInt('quantity');
if (line.getString('lineType') === 'slot') {
const slot = findOrNull(app, 'slots', line.getString('slot'));
if (!slot || slot.getString('status') !== 'held') {
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
}
} else {
const stock = item.get('stock');
if (stock != null && stock !== '' && item.getInt('stock') < quantity) {
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
}
}
totalCents += Math.round(item.getFloat('price') * 100) * quantity;
summary.push(`${quantity}× ${item.getString('name')}`);
}
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
let intent = null;
const existingId = basket.getString('stripePaymentIntentId');
if (existingId) {
// Reuse the intent on reload/retry while it can still take a payment.
try {
const existing = stripe('GET', '/v1/payment_intents/' + encodeURIComponent(existingId));
if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') {
intent = stripe('POST', '/v1/payment_intents/' + encodeURIComponent(existingId), {
amount: totalCents,
metadata: { basket_id: basket.id }
});
}
} catch (_) {
// Missing/invalid — create a new one below.
}
}
if (!intent) {
try {
intent = stripe('POST', '/v1/payment_intents', {
amount: totalCents,
currency: currency(),
automatic_payment_methods: { enabled: true },
receipt_email: customer.email,
metadata: { basket_id: basket.id, line_summary: summary.join('; ').slice(0, 450) }
});
} catch (e) {
console.error('[shop] Stripe create intent failed:', e);
throw new ApiError(502, 'Payment could not be started — please try again');
}
}
basket.set('stripePaymentIntentId', intent.id);
basket.set('email', customer.email);
basket.set('customerDetails', customer);
app.save(basket);
return { clientSecret: intent.client_secret };
}
/** Verify a `Stripe-Signature` header (v1 HMAC-SHA256 over "timestamp.body"). */
function verifyStripeSignature(rawBody, header, secret) {
let timestamp = 0;
const signatures = [];
for (const part of String(header || '').split(',')) {
const [k, v] = part.split('=');
if (k === 't') timestamp = Number(v);
else if (k === 'v1' && v) signatures.push(v);
}
if (!timestamp || !signatures.length) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > WEBHOOK_TOLERANCE_S) return false;
const expected = $security.hs256(timestamp + '.' + rawBody, secret);
return signatures.some((sig) => $security.equal(sig, expected));
}
/**
* Stripe webhook. Returns `{ received, orderEmail }`; `orderEmail` is the
* data for the booking emails when this call created a new order (the public
* app renders and sends them — see packages/shared/src/server/email).
*/
function handleStripeWebhook(app, rawBody, signature) {
const secret = $os.getenv('STRIPE_WEBHOOK_SECRET');
if (!secret) throw new InternalServerError('STRIPE_WEBHOOK_SECRET is not configured');
if (!verifyStripeSignature(rawBody, signature, secret)) throw new BadRequestError('Webhook signature verification failed');
const event = JSON.parse(rawBody);
const intent = (event.data && event.data.object) || {};
if (event.type === 'payment_intent.succeeded') {
const orderId = createOrderFromIntent(app, intent);
return { received: true, orderEmail: orderId ? orderEmailData(app, orderId) : null };
}
if (event.type === 'payment_intent.payment_failed') {
const basketId = intent.metadata && intent.metadata.basket_id;
if (basketId) {
// Keep the slots for the customer to retry (fresh 10-minute window);
// starting payment again extends them back to 30 minutes.
extendBasketHolds(app, basketId, SLOT_HOLD_MS);
const basket = findOrNull(app, 'baskets', basketId);
if (basket) {
basket.set('stripePaymentIntentId', '');
app.save(basket);
}
}
}
return { received: true, orderEmail: null };
}
/** Turn a paid basket into an order. Idempotent per PaymentIntent; returns the new order id, or null. */
function createOrderFromIntent(app, intent) {
const basketId = intent.metadata && intent.metadata.basket_id;
if (!basketId || !intent.id) return null; // not one of ours
let orderId = null;
app.runInTransaction((tx) => {
const existing = findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: intent.id });
if (existing.length) return; // Stripe retried — already handled
const basket = findOrNull(tx, 'baskets', basketId);
if (!basket) return;
const lines = basketLines(tx, basketId);
const order = newRecord(tx, 'orders', {
basket: basketId,
email: basket.getString('email') || intent.receipt_email || '',
customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {},
total: intent.amount / 100,
status: 'paid',
stripePaymentIntentId: intent.id
});
tx.save(order);
// Snapshot lines, book slots, decrement stock.
for (const line of lines) {
const item = findOrNull(tx, 'items', line.getString('item'));
const slot = findOrNull(tx, 'slots', line.getString('slot'));
tx.save(
newRecord(tx, 'order_lines', {
order: order.id,
item: line.getString('item'),
slot: line.getString('slot'),
quantity: line.getInt('quantity'),
lineType: line.getString('lineType'),
name: item ? item.getString('name') : 'Unknown item',
price: item ? item.getFloat('price') : 0,
start: slot ? slot.getString('start') : ''
})
);
if (line.getString('lineType') === 'slot' && slot) {
slot.set('status', 'booked');
slot.set('heldUntil', '');
slot.set('order', order.id);
tx.save(slot);
} else if (item && item.get('stock') != null && item.get('stock') !== '') {
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
tx.save(item);
}
}
// Basket done — order_lines hold the snapshot.
for (const line of lines) tx.delete(line);
basket.set('status', 'completed');
tx.save(basket);
orderId = order.id;
});
return orderId;
}
// ── Orders ──────────────────────────────────────────────────────────────
function globalData(app, key) {
try {
return plain(app.findFirstRecordByFilter('globals', 'key = {:key}', { key })).data || null;
} catch (_) {
return null;
}
}
function emailTemplate(app, key) {
try {
return plain(app.findFirstRecordByFilter('email_templates', 'key = {:key}', { key }));
} catch (_) {
return null;
}
}
/** Everything the booking emails need — the shape of `OrderEmailData` in packages/shared/src/server/email. */
function orderEmailData(app, orderId) {
const order = app.findRecordById('orders', orderId);
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start');
for (const line of lines) app.expandRecord(line, ['slot', 'item'], null);
return {
order: plain(order),
lines: lines.map(plain),
templates: {
customer_confirmation: emailTemplate(app, 'customer_confirmation'),
client_alert: emailTemplate(app, 'client_alert')
},
footer: globalData(app, 'footer'),
colors: globalData(app, 'colors')
};
}
/**
* Payment result page. The PaymentIntent id comes from Stripe's redirect;
* it is checked with Stripe first, so made-up ids reveal nothing.
*/
function orderStatus(app, paymentIntentId) {
const id = String(paymentIntentId || '');
if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' };
let intent;
try {
intent = stripe('GET', '/v1/payment_intents/' + encodeURIComponent(id));
} catch (_) {
return { state: 'invalid' };
}
const orders = findAll(app, 'orders', 'stripePaymentIntentId = {:id}', { id });
if (!orders.length) {
// The webhook is the source of truth and may not have landed yet.
if (intent.status === 'succeeded') return { state: 'processing' };
return { state: intent.status === 'canceled' ? 'canceled' : 'failed' };
}
const order = orders[0];
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id');
return { state: 'paid', order: plain(order), lines: lines.map(plain) };
}
/**
* Record the booking-email outcome reported by the public app. Requires the
* shared INTERNAL_API_SECRET and only touches the email status fields.
*/
function recordEmailStatus(app, secretHeader, body) {
const secret = $os.getenv('INTERNAL_API_SECRET');
if (!secret || !$security.equal(String(secretHeader || ''), secret)) throw new ForbiddenError('Forbidden');
const order = findOrNull(app, 'orders', String(body.orderId || ''));
if (!order) throw new NotFoundError('Order not found');
const patch = body.patch || {};
for (const field of ['customerEmailSentAt', 'clientEmailSentAt', 'emailError']) {
if (typeof patch[field] === 'string') order.set(field, patch[field].slice(0, 2000));
}
app.save(order);
}
module.exports = {
sweepExpiredHolds,
loadActiveBasket,
basketPayload,
basketAction,
startCheckout,
handleStripeWebhook,
orderStatus,
recordEmailStatus
};

View file

@ -1,106 +0,0 @@
/// <reference path="../pb_data/types.d.ts" />
// Security + data-integrity fixes (2026-10-06 admin polish review).
// Runs automatically when PocketBase starts (docker-compose mounts this
// directory at /pb_migrations); PocketBase records it so it runs once.
//
// 1. users: no public sign-up. PocketBase's default `users` collection lets
// anyone register, and every CMS rule only checks "signed in" — so a
// stranger could create an account and edit the site / read orders.
// 2. Commerce collections: writes are superuser-only. The public app does
// all basket/order writes server-side with the admin client, so open
// rules only allowed forging orders or tampering with baskets via the API.
// 3. `created`/`updated` autodate fields on content + commerce collections
// (orders had no date and no chronological order).
// 4. Unique indexes on pages.slug and globals.key (skipped, with a log
// line, if duplicates exist).
const AUTODATE_COLLECTIONS = ['pages', 'globals', 'media', 'events', 'items', 'slots', 'baskets', 'basket_lines', 'orders', 'order_lines', 'email_templates'];
// Missing collections are skipped: on a fresh install this runs before
// pb_schema.json is imported (that file already contains these changes).
function find(app, name) {
try {
return app.findCollectionByNameOrId(name);
} catch (e) {
return null;
}
}
function update(app, name, change) {
const collection = find(app, name);
if (!collection) return;
change(collection);
app.save(collection);
}
const UNIQUE_INDEXES = [
{ collection: 'pages', field: 'slug', name: 'idx_pages_slug_unique' },
{ collection: 'globals', field: 'key', name: 'idx_globals_key_unique' }
];
migrate(
(app) => {
// 1. Close public sign-up.
update(app, 'users', (c) => (c.createRule = null));
// 2. Commerce writes: superuser only (null = superusers only).
update(app, 'baskets', (c) => {
c.createRule = null;
c.updateRule = null;
});
update(app, 'basket_lines', (c) => {
c.createRule = null;
c.updateRule = null;
c.deleteRule = null;
});
update(app, 'orders', (c) => (c.createRule = null));
// 3. Autodate fields (existing records keep an empty date).
for (const name of AUTODATE_COLLECTIONS) {
update(app, name, (c) => {
if (!c.fields.getByName('created')) c.fields.add(new AutodateField({ name: 'created', onCreate: true, onUpdate: false }));
if (!c.fields.getByName('updated')) c.fields.add(new AutodateField({ name: 'updated', onCreate: true, onUpdate: true }));
});
}
// 4. Unique indexes. If duplicates already exist, skip the index and
// log why — failing here would stop PocketBase (and the site) from
// starting. The admin app also refuses new duplicates.
for (const { collection: name, field, name: indexName } of UNIQUE_INDEXES) {
const collection = find(app, name);
if (!collection || collection.indexes.some((index) => index.includes(indexName))) continue;
const seen = {};
const duplicates = [];
for (const record of app.findAllRecords(name)) {
const value = record.get(field);
if (seen[value]) duplicates.push(value);
seen[value] = true;
}
if (duplicates.length) {
console.log(`[migration] ${name}.${field} has duplicates ${JSON.stringify(duplicates)} — unique index NOT created. Fix them and add it in the dashboard.`);
continue;
}
collection.indexes = [...collection.indexes, `CREATE UNIQUE INDEX \`${indexName}\` ON \`${name}\` (\`${field}\`)`];
app.save(collection);
}
},
(app) => {
// Revert: restore the previous rules and drop the unique indexes.
// Autodate fields are left in place (dropping them loses data).
update(app, 'users', (c) => (c.createRule = ''));
update(app, 'baskets', (c) => {
c.createRule = '';
c.updateRule = '';
});
update(app, 'basket_lines', (c) => {
c.createRule = '';
c.updateRule = '';
c.deleteRule = '';
});
update(app, 'orders', (c) => (c.createRule = ''));
for (const { collection: name, name: indexName } of UNIQUE_INDEXES) {
update(app, name, (c) => (c.indexes = c.indexes.filter((index) => !index.includes(indexName))));
}
}
);

View file

@ -1,33 +0,0 @@
/// <reference path="../pb_data/types.d.ts" />
// order_lines was writable by anyone (create/update/delete rules were empty
// strings = public), so the line items of real orders could be forged or
// deleted through the REST API. Orders are now created by the shop hooks
// (pb_hooks/shop), which bypass API rules, so writes are superuser-only.
function find(app, name) {
try {
return app.findCollectionByNameOrId(name);
} catch (e) {
return null; // fresh install: pb_schema.json (already fixed) is imported later
}
}
migrate(
(app) => {
const collection = find(app, 'order_lines');
if (!collection) return;
collection.createRule = null;
collection.updateRule = null;
collection.deleteRule = null;
app.save(collection);
},
(app) => {
const collection = find(app, 'order_lines');
if (!collection) return;
collection.createRule = '';
collection.updateRule = '';
collection.deleteRule = '';
app.save(collection);
}
);