Compare commits

..

9 commits

Author SHA1 Message Date
47a1250b46 Docs: admin UI conventions, timezone rule, PocketBase migrations
- AGENTS.md: new routes/labels, DaisyUI 5 + admin conventions (fieldset,
  Modal, SegmentedControl/ColorField, confirmSubmit, attempt), site-timezone
  rule, pb.filter rule, migration + pb_schema.json workflow, API-rule
  invariants (no public users sign-up).
- README: how migrations are applied and the users sign-up warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 11:02:03 +00:00
fbcc71672b Admin navigation: grouped sidebar, plainer labels, Backup page
Agreed with the site owner:
- Grouped sidebar (Website / Bookings / Settings) instead of a flat top
  bar that overflowed on phones; a drawer with a hamburger below lg.
  Signed-in email and Log out at the bottom.
- Labels: Globals → Site design, Items → Services & products,
  Calendar → Events, Export/Import → Backup (URLs unchanged); page headings
  and cross-references updated to match.
- Export/import moved from a navbar dropdown to a /backup page that says
  what is and isn't included.
- Admin event calendar starts weeks on Monday (createCalendarMonth gains an
  optional weekStartsOn; the public block is unchanged).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 11:00:01 +00:00
9264289813 PocketBase: close public sign-up, lock commerce writes, add dates/unique keys
Security:
- PocketBase's default `users` collection allows anonymous sign-up, and
  every CMS rule only checks "signed in" (the admin login also accepts
  `users`). Anyone could register via the public API and edit the site,
  read orders/customer details, or log into the admin. Sign-up is now
  superuser-only.
- orders.create, baskets.create/update and basket_lines.create/update/
  delete were open to anonymous requests, allowing forged "paid" orders in
  the admin and basket tampering. The public app performs all of these
  server-side with the admin client, so they are now superuser-only
  (basket add-item/add-slot verified still working).

Data:
- created/updated autodate fields on all app collections; orders are now
  listed newest-first by date (ids are random, '-id' was not chronological).
- Unique indexes on pages.slug and globals.key (skipped with a log line if
  existing data has duplicates, so PocketBase still starts).

Delivered as a JS migration in pocketbase/pb_migrations, mounted into the
container (the image already passes --migrationsDir=/pb_migrations), so it
applies once on the next start. pb_schema.json carries the same changes for
fresh installs, where the migration runs before the schema is imported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:55:12 +00:00
af7b4af5de Admin UI consistency: DaisyUI 5 forms, shared modal and setting rows
- Migrate all DaisyUI 4 form markup (form-control, label-text, *-bordered —
  removed in v5) to v5 fieldset/legend; labels sat inline beside inputs
  and inputs fell back to a fixed 20rem width.
- One Modal component (native <dialog>: Escape, focus trap) for page,
  event, item and slot editors; destructive actions confirmed everywhere.
  The page Delete confirm was ignored — returning false from onsubmit
  doesn't cancel — so Cancel still deleted the page.
- Block editor follows the background-picker style throughout:
  SegmentedControl rows (title-cased options, clearer selected state) and
  a new ColorField row with reset; image position is Left/Right like the
  alignment controls.
- Globals keep their layout; readable field labels, save feedback without
  reload, hints wrap.
- Pages list: fixed broken Preview link (VITE_PUBLIC_SITE_URL was
  undefined → "undefined/slug"), shown for published pages only; action
  column no longer breaks row alignment; empty states on all tables.
- Items: image picker instead of a raw media-id field, upload errors shown
  (were swallowed), prices in the shop currency instead of hard-coded EUR.
- Slots/orders/calendar: times shown in the site timezone with a fixed
  locale (server and browser render the same text).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:46:40 +00:00
cfe4e2062d Page editor: save in place, unsaved-changes guard, safer block list
- Saving no longer reloads the page: a validation error (empty title,
  duplicate slug) used to re-render from the server and silently discard
  every unsaved block edit. Shows saving/saved/error feedback like the
  email editor, an "Unsaved changes" badge, and warns before leaving.
- Status shown in the header; on a published page "Save draft" was
  misleading (changes go live immediately), so it now says so and the
  button reads "Save". Publish is a named submit (no DOM mutation).
- Block list: selected block is visible again (Tailwind v4's default
  border colour is currentColor, so every item had a heavy black border);
  drag & drop works in Firefox (needs dataTransfer data) with a drop
  indicator; Alt+↑/↓ keyboard reorder; hold-to-delete works from the
  keyboard, is cancelled on pointercancel/unmount, and no longer selects
  the wrong neighbour afterwards.
- Shared warnOnUnsavedChanges helper; the email editor uses it too
  (confirm() is ignored on tab close — cancel() triggers the browser prompt).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:46:40 +00:00
1eb58c71ba Export/import: fix lost images and malformed-file crashes
- An image URL used more than once in the same string (e.g. rich text) was
  only replaced once, leaving broken __IMG__ placeholders after import.
- Images that failed to export were still replaced by placeholders that the
  import could never resolve; keep the original URL instead.
- Validate the uploaded file's shape and JSON (was a 500 on bad input).
- Build lookup filters with pb.filter so names/slugs with quotes don't
  create duplicates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:46:24 +00:00
ff54adb00c Admin server actions: handled errors, timezone-correct times, safer writes
- Slot and timed-event times were parsed in the server's zone (UTC in the
  container) while the form sent the admin's local wall-clock time, so every
  save shifted them by the UTC offset (10:00 → 12:00 in Oslo, again on each
  save). Inputs are now interpreted in SITE_TIMEZONE (shared helpers with
  DST handling), the same setting the booking emails use.
- PocketBase failures in actions (duplicate, validation, relation in use,
  DB down) now return a readable `fail()` instead of a 500 page.
- Pages: 404 for unknown slugs, slug filters built with pb.filter (quotes
  broke them), duplicate-slug check on create/rename (no unique index),
  invalid block JSON rejected instead of throwing; save returns a result so
  the editor can stay on the page.
- Globals: only create a missing record on 404 — any other error (DB
  hiccup) used to create duplicates; save reports success/failure.
- Slots: status is never taken from the form; re-read before update so a
  slot booked or held since the page loaded isn't overwritten; don't delete
  actively held slots.
- Orders: load all order lines in one request instead of one per order.
- Layout exposes site timezone and shop currency for display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:46:24 +00:00
52d7a5e3e2 Admin shell: standalone login/preview, fixed admin theme
- /login and /preview no longer render the admin navbar (the login page
  showed Pages/Export/Logout to signed-out users; the page preview iframe
  showed the whole admin shell above the draft).
- Site colours from Globals were written onto --color-primary/--color-accent
  of the admin document, which are DaisyUI's theme variables — so the brand
  colour restyled every admin button (low-contrast white-on-sage) and flashed
  after hydration. Apply them only inside /preview; give the admin its own
  sage primary at ~5:1 contrast.
- Login page redesigned with DaisyUI 5 markup (full-width inputs, labels
  above), autocomplete hints, pending state.
- Navbar: active-route highlight, consistent button sizes, wraps instead of
  overflowing on narrow screens.
- Import: confirm before overwriting, show per-item errors instead of
  auto-reloading them away, friendly message for invalid JSON.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:35:15 +00:00
1518f1bbbe Fix admin login/logout over HTTP and stale sessions
- Auth cookie was always exported with the SDK default `Secure` flag, so
  browsers dropped it over plain HTTP (CADDY_SCHEME=http) and login
  looped back to /login. Set `secure` from the real request scheme.
- Logout never ran: the hook redirected every authenticated request to
  /login (including POST /login?/logout) back to /pages. Only redirect GET.
- Refresh the token per request so revoked tokens log the user out instead
  of surfacing as 500s, and sessions slide instead of expiring mid-edit.
- Use `_superusers` instead of the deprecated `pb.admins` alias; keep the
  entered email on a failed login.
- docker-compose: fully-qualified image names (podman rejects short names).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
2026-10-06 10:35:15 +00:00
45 changed files with 3169 additions and 2446 deletions

View file

@ -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, editors) │ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers)
│ │ ├── 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,17 +22,18 @@ 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 (pb-admin, basket) │ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts)
│ ├── routes/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout) │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview)
│ │ ├── login/ # Admin login │ │ ├── login/ # Admin login
│ │ ├── pages/ # Page CRUD + block editor │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── calendar/ # Event CRUD │ │ ├── calendar/ # Event CRUD (menu label: Events)
│ │ ├── items/ # Service/product CRUD │ │ ├── items/ # Service/product CRUD (menu label: Services & products)
│ │ ├── 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 │ │ ├── globals/ # Header/footer/colors editor (menu label: Site design)
│ │ ├── 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
@ -67,7 +68,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_data/ # PocketBase data (volume-mounted) pocketbase/pb_migrations/ # JS migrations, mounted at /pb_migrations; applied on PocketBase start
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
``` ```
@ -124,14 +125,24 @@ 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, baskets, basket_lines) are superuser-only; the public app does them server-side via `getAdminPb()`.
### 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 utility classes (`btn`, `card`, `input`, `select`, `rounded-box`, etc.) - **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). The admin has its own fixed theme in `app.css`; the site's Globals colours are applied only inside `/preview` (their CSS variables collide with DaisyUI's `--color-primary`/`--color-accent`). Conventions:
- 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`. 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). - **Admin app** (`app-admin`): All routes except `/login` are auth-guarded in `hooks.server.ts` (which also refreshes the token per request and sets the cookie's `Secure` flag from the real scheme). The root layout renders the admin shell (grouped sidebar) except on `/login` and `/preview`. The `/preview` route reads `sessionStorage` set by the page editor (same-origin, so it works).
- **Public app** (`app-public`): No auth guard. The root layout always renders Header/Footer. `+layout.server.ts` fetches header/footer/colors globals + basket/items/slots for every page. - **Public app** (`app-public`): No auth guard. The root layout always renders Header/Footer. `+layout.server.ts` fetches header/footer/colors globals + basket/items/slots for every page.
- `+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

View file

@ -77,6 +77,12 @@ 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.
> **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:

View file

@ -1,140 +1,157 @@
@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;
} }
@theme { /* Admin UI theme: DaisyUI light with a fixed sage primary. Deliberately NOT
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif; tied to the site's colours (Site design → Colors) (those only apply inside /preview), so
--font-serif: 'Playfair Display', Georgia, serif; a light brand colour can't make admin buttons unreadable. #647556 on white
--color-warm: var(--color-bg, #faf8f5); text is ~5:1 contrast (WCAG AA). */
--color-charcoal: var(--color-heading, #2c2c2c); @plugin 'daisyui/theme' {
--color-sage: var(--color-primary, #8a9a7b); name: 'light';
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000); default: true;
--color-terracotta: var(--color-accent, #c9825f); --color-primary: #647556;
} --color-primary-content: #ffffff;
}
@keyframes shrink {
from { scale: 0 1; } /* Hint text under form fields: DaisyUI's .label is nowrap, which stretched
to { scale: 1 1; } fields to fit long hints. */
} .fieldset .label {
white-space: normal;
.delete-fill { }
position: absolute;
inset: 0; @theme {
background: transparent; --font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
transform-origin: left; --font-serif: 'Playfair Display', Georgia, serif;
} --color-warm: var(--color-bg, #faf8f5);
--color-charcoal: var(--color-heading, #2c2c2c);
.delete-fill.animating { --color-sage: var(--color-primary, #8a9a7b);
animation: shrink 1s ease-in-out forwards; --color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
background: var(--error, #f43f5e); --color-terracotta: var(--color-accent, #c9825f);
} }
.btn.delete-holding { @keyframes shrink {
color: white !important; from { scale: 0 1; }
} to { scale: 1 1; }
}
.btn.delete-holding .text-error {
color: white !important; .delete-fill {
} position: absolute;
inset: 0;
:root { background: transparent;
--fg-heading: var(--color-heading, #2c2c2c); transform-origin: left;
--fg-subheading: var(--color-subheading, #4a4a4a); }
--fg-body: var(--color-text, #2c2c2c);
background: var(--color-bg, #faf8f5); .delete-fill.animating {
color: var(--fg-body); animation: shrink 1s ease-in-out forwards;
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif; background: var(--error, #f43f5e);
} }
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */ .btn.delete-holding {
.text-fg-body { color: var(--fg-body, #2c2c2c); } color: white !important;
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); } }
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); } .btn.delete-holding .text-error {
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); } color: white !important;
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); } }
.text-fg-heading { color: var(--fg-heading, #2c2c2c); }
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); } :root {
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); } --fg-heading: var(--color-heading, #2c2c2c);
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); } --fg-subheading: var(--color-subheading, #4a4a4a);
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); } --fg-body: var(--color-text, #2c2c2c);
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); } background: var(--color-bg, #faf8f5);
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); } color: var(--fg-body);
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
body { }
min-height: 100vh;
margin: 0; /* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
background: .text-fg-body { color: var(--fg-body, #2c2c2c); }
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem), .text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
var(--color-bg, #faf8f5); .text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, 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); }
h1, .text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
h2, .text-fg-heading { color: var(--fg-heading, #2c2c2c); }
h3, .text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
h4 { .text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
font-family: 'Playfair Display', Georgia, serif; .text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
color: var(--fg-heading, #2c2c2c); .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); }
.prose-wellness p {
margin: 0.75rem 0; body {
line-height: 1.8; min-height: 100vh;
} margin: 0;
background:
.prose-wellness h2 { radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
margin: 1.25rem 0 0.5rem; var(--color-bg, #faf8f5);
font-size: clamp(2rem, 4vw, 3.25rem); }
line-height: 1.05;
} h1,
h2,
.prose-wellness h3 { h3,
margin: 1rem 0 0.5rem; h4 {
font-size: 1.6rem; font-family: 'Playfair Display', Georgia, serif;
} color: var(--fg-heading, #2c2c2c);
}
.prose-wellness ul {
list-style: disc; .prose-wellness p {
padding-left: 1.5rem; margin: 0.75rem 0;
} line-height: 1.8;
}
.prose-wellness a {
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000); .prose-wellness h2 {
text-decoration: underline; margin: 1.25rem 0 0.5rem;
text-underline-offset: 3px; font-size: clamp(2rem, 4vw, 3.25rem);
} line-height: 1.05;
}
/* ── Scroll-reveal animations ── */
.reveal { .prose-wellness h3 {
opacity: 0; margin: 1rem 0 0.5rem;
transform: translateY(30px); font-size: 1.6rem;
transition: }
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1); .prose-wellness ul {
} list-style: disc;
padding-left: 1.5rem;
.reveal-visible { }
opacity: 1;
transform: translateY(0); .prose-wellness a {
} color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
text-decoration: underline;
/* ── Hero fade-in stagger ── */ text-underline-offset: 3px;
.animate-fade-in { }
opacity: 0;
transform: translateY(20px); /* ── Scroll-reveal animations ── */
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards; .reveal {
} opacity: 0;
transform: translateY(30px);
@keyframes fadeInUp { transition:
to { opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
opacity: 1; transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
transform: translateY(0); }
}
} .reveal-visible {
opacity: 1;
/* ── Smooth scroll ── */ transform: translateY(0);
html { }
scroll-behavior: smooth;
} /* ── Hero fade-in stagger ── */
.animate-fade-in {
opacity: 0;
transform: translateY(20px);
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
}
@keyframes fadeInUp {
to {
opacity: 1;
transform: translateY(0);
}
}
/* ── Smooth scroll ── */
html {
scroll-behavior: smooth;
}

View file

@ -7,6 +7,18 @@ 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;
@ -17,11 +29,17 @@ export const handle: Handle = async ({ event, resolve }) => {
throw redirect(303, '/login'); throw redirect(303, '/login');
} }
if (isLoginRoute && isAuthed) { if (isLoginRoute && isAuthed && event.request.method === 'GET') {
throw redirect(303, '/pages'); throw redirect(303, '/pages');
} }
const response = await resolve(event); const response = await resolve(event);
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth')); // The SDK defaults to `Secure`, which browsers drop over plain HTTP — that
// 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,64 +1,115 @@
<script lang="ts"> <script lang="ts">
import type { ContentBlock, EmailBlock } from '$lib/types'; import { onDestroy } from 'svelte';
import { blockLabels } from '$lib/admin/blockDefaults'; import type { ContentBlock, EmailBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults';
let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
blocks: (ContentBlock | EmailBlock)[]; let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
labels?: Record<string, string>; blocks: (ContentBlock | EmailBlock)[];
selectedId?: string; labels?: Record<string, string>;
onSelect?: (id: string) => void; selectedId?: string;
onDelete?: (id: string) => void; onSelect?: (id: string) => void;
onMove?: (from: number, to: number) => void; onDelete?: (id: string) => void;
}>(); onMove?: (from: number, to: number) => void;
}>();
let dragIndex = $state<number | null>(null);
let holdingId = $state(''); let dragIndex = $state<number | null>(null);
let holdTimer: ReturnType<typeof setTimeout> | null = null; let dropIndex = $state<number | null>(null);
let holdingId = $state('');
function startHold(id: string) { let holdTimer: ReturnType<typeof setTimeout> | null = null;
holdingId = id;
holdTimer = setTimeout(() => { // Delete is press-and-hold (1s) so a stray click can't remove a block.
const idx = blocks.findIndex((b: ContentBlock | EmailBlock) => b.id === id); // The parent picks the next selection.
onDelete(id); function startHold(id: string) {
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || ''); endHold();
holdingId = ''; holdingId = id;
}, 1000); holdTimer = setTimeout(() => {
} holdTimer = null;
holdingId = '';
function endHold() { onDelete(id);
if (holdTimer) clearTimeout(holdTimer); }, 1000);
holdingId = ''; }
}
</script> function endHold() {
if (holdTimer) clearTimeout(holdTimer);
<div class="space-y-3"> holdTimer = null;
{#each blocks as block, i (block.id)} holdingId = '';
<div }
role="listitem"
class="rounded-box border bg-base-100 p-3 shadow-sm cursor-pointer" onDestroy(endHold);
class:border-primary={selectedId === block.id}
draggable="true" function drop(index: number) {
onclick={() => onSelect(block.id)} if (dragIndex !== null && dragIndex !== index) onMove(dragIndex, index);
ondragstart={() => (dragIndex = i)} dragIndex = null;
ondragover={(e) => e.preventDefault()} dropIndex = null;
ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }} }
>
<div class="flex items-center gap-2"> function moveBy(index: number, delta: number) {
<span class="cursor-grab text-xl text-base-content/40">☰</span> const to = index + delta;
<div class="flex-1 font-semibold">{labels[block.type] ?? block.type}</div> if (to >= 0 && to < blocks.length) onMove(index, to);
<button }
class="btn btn-xs btn-error btn-outline relative overflow-hidden" </script>
class:btn-disabled={holdingId && holdingId !== block.id}
class:delete-holding={holdingId === block.id} <ul class="space-y-2">
type="button" {#each blocks as block, i (block.id)}
onpointerdown={() => startHold(block.id)} <li
onpointerup={endHold} class="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'}"
onpointerleave={endHold} class:opacity-50={dragIndex === i}
> class:border-dashed={dropIndex === i && dragIndex !== i}
<span class="delete-fill" class:animating={holdingId === block.id}></span> draggable="true"
<span class="relative z-10 text-error">Delete</span> ondragstart={(e) => {
</button> dragIndex = i;
</div> // Firefox won't start a drag without data.
</div> e.dataTransfer?.setData('text/plain', block.id);
{/each} if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
</div> }}
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

@ -0,0 +1,33 @@
<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

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

@ -0,0 +1,37 @@
<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,6 +4,7 @@
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;
@ -17,15 +18,10 @@
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 Globals → Footer.' contact_info: 'Filled in automatically from the business name, address, phone and email in Site design → Footer.'
}; };
</script> </script>
@ -42,46 +38,38 @@
<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 })} formatLabel={titleCase} /> <SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} />
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Link (optional)</span></div> <span class="fieldset-legend">Link (optional)</span>
<input class="input input-bordered w-full" placeholder="https://… or /page" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} /> <input class="input 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="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Button label</span></div> <span class="fieldset-legend">Button label</span>
<input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} /> <input class="input w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
</label> </label>
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">URL</span></div> <span class="fieldset-legend">URL</span>
<input class="input input-bordered w-full" placeholder={'https://…, /page or {{site_url}}'} value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} /> <input class="input 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 })} formatLabel={titleCase} /> <SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} />
<div class="form-control"> <ColorField label="Color" value={block.data.color || ''} fallback={primaryColor} placeholder="Site primary color" onChange={(color) => updateData({ color })} />
<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="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Height (px)</span></div> <span class="fieldset-legend">Height (px)</span>
<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 })} /> <input type="number" min="0" class="input 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="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Section title</span></div> <span class="fieldset-legend">Section title</span>
<input class="input input-bordered w-full" placeholder="Leave empty for no title" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} /> <input class="input 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,105 +1,107 @@
<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;
emitChange(); // Keep a hand-written alt text; otherwise use the one derived from the filename.
} catch (e) { if (!localAlt) localAlt = result.record?.alt || '';
error = e instanceof Error ? e.message : 'Upload failed'; emitChange();
console.error('Image upload error:', e); } catch (e) {
} finally { error = e instanceof Error ? e.message : 'Upload failed';
uploading = false; console.error('Image upload error:', e);
} } finally {
} uploading = false;
}
function removeImage() { }
localUrl = '';
localAlt = ''; function removeImage() {
emitChange(); localUrl = '';
if (fileInput) fileInput.value = ''; localAlt = '';
} emitChange();
</script> if (fileInput) fileInput.value = '';
}
<div class="grid grid-cols-[1fr_1.5fr] gap-4"> </script>
<!-- Drop zone / upload area -->
<div <div class="grid grid-cols-[1fr_1.5fr] gap-4">
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'}" <!-- Drop zone / upload area -->
role="button" <div
tabindex="0" 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'}"
onclick={() => fileInput?.click()} role="button"
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()} tabindex="0"
> onclick={() => fileInput?.click()}
{#if uploading} onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
<span class="loading loading-spinner loading-lg text-primary"></span> >
<p class="mt-3 text-sm text-base-content/60">Uploading…</p> {#if uploading}
{:else if localUrl} <span class="loading loading-spinner loading-lg text-primary"></span>
<div class="relative w-full"> <p class="mt-3 text-sm text-base-content/60">Uploading…</p>
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} /> {:else if localUrl}
<button <div class="relative w-full">
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1" <img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
type="button" <button
onclick={(e) => { e.stopPropagation(); removeImage(); }} class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
title="Remove image" type="button"
>✕</button> onclick={(e) => { e.stopPropagation(); removeImage(); }}
</div> title="Remove image"
{:else} >✕</button>
<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"> </div>
<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" /> {:else}
</svg> <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">
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p> <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-xs text-base-content/40">PNG, JPG, WebP</p> </svg>
{/if} <p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
</div> <p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
{/if}
{#if error} </div>
<div class="alert alert-error col-span-full text-sm">{error}</div>
{/if} {#if error}
<div class="alert alert-error col-span-full text-sm">{error}</div>
<input {/if}
class="hidden"
type="file" <input
accept="image/*" class="hidden"
onchange={handleFile} type="file"
disabled={uploading} accept="image/*"
bind:this={fileInput} onchange={handleFile}
/> disabled={uploading}
bind:this={fileInput}
<!-- URL & Alt fields --> />
<div class="space-y-3">
<label class="form-control w-full"> <!-- URL & Alt fields -->
<div class="label"><span class="label-text">Image URL</span></div> <div>
<input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} /> <label class="fieldset pt-0">
</label> <span class="fieldset-legend">Image URL</span>
<label class="form-control w-full"> <input class="input w-full" bind:value={localUrl} oninput={() => emitChange()} />
<div class="label"><span class="label-text">Alt text</span></div> </label>
<input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} /> <label class="fieldset">
</label> <span class="fieldset-legend">Alt text</span>
</div> <input class="input w-full" bind:value={localAlt} oninput={() => emitChange()} />
</div> </label>
</div>
</div>

View file

@ -1,38 +1,46 @@
<script lang="ts"> <script lang="ts">
let { // One row of mutually exclusive options with an optional label column on
label, // the left — the standard "setting row" in the block editors (see
options, // ColorField for the colour variant; both share the label column width).
value, let {
onChange, label,
formatLabel = (v: string | number) => String(v), options,
labelStyle = '', value,
class: className = '' onChange,
}: { formatLabel = (v: string | number) => {
label?: string; const text = String(v);
options: (string | number)[]; return text.charAt(0).toUpperCase() + text.slice(1);
value: string | number; },
onChange: (value: string | number) => void; strong = false,
formatLabel?: (value: string | number) => string; class: className = ''
labelStyle?: string; }: {
class?: string; label?: string;
} = $props(); options: (string | number)[];
</script> value: string | number;
onChange: (value: string | number) => void;
<div class="form-control {className}"> formatLabel?: (value: string | number) => string;
<div class="flex items-center justify-between"> /** Bold label, for section-level settings like Background/Foreground. */
{#if label} strong?: boolean;
<span class="label-text w-24" style={labelStyle}>{label}</span> class?: string;
{/if} } = $props();
<div class="grid flex-1" style="grid-template-columns: repeat({options.length}, 1fr)"> </script>
{#each options as option, i}
<button <div class="flex items-center gap-3 {className}" role="group" aria-label={label}>
type="button" {#if label}
class="btn btn-sm {i === 0 ? 'rounded-r-none' : ''} {i === options.length - 1 ? 'rounded-l-none' : ''} {value === option ? 'btn-active' : ''}" <span class="w-28 shrink-0 text-sm" class:font-bold={strong} class:font-medium={!strong}>{label}</span>
onclick={() => onChange(option)} {/if}
> <div class="join grid flex-1" style="grid-template-columns: repeat({options.length}, minmax(0, 1fr))">
{formatLabel(option)} {#each options as option}
</button> <button
{/each} type="button"
</div> class="btn btn-sm join-item px-1"
</div> class:btn-active={value === option}
</div> class:btn-primary={value === option}
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="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Title</span></div> <span class="fieldset-legend">Title</span>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} /> <input class="input 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">No items yet — create some under Items in the admin.</p> <p class="text-sm text-base-content/60">Nothing to sell yet — add some under Services & products.</p>
{/if} {/if}
</div> </div>

View file

@ -0,0 +1,15 @@
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,139 +1,150 @@
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.replace(url, `__IMG__${key}__`); result = result.replaceAll(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.replace(`__IMG__${key}__`, url); result = result.replaceAll(`__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. */
* Convert a base64 data-URI back to a File object for upload. export function validateSiteExport(body: unknown): string | null {
*/ if (!body || typeof body !== 'object') return 'The file is not a CMS export.';
export function dataUriToFile(dataUri: string, filename: string): File { const b = body as Partial<SiteExport>;
const [header, base64] = dataUri.split(','); if (b.version !== 1) return 'Unsupported export version.';
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png'; if (!Array.isArray(b.pages) || !Array.isArray(b.globals)) return 'The export is missing pages or globals.';
const binary = atob(base64); if (b.events !== undefined && !Array.isArray(b.events)) return 'The export has an invalid events list.';
const bytes = new Uint8Array(binary.length); if (!b.images || typeof b.images !== 'object' || Array.isArray(b.images)) return 'The export is missing its images.';
for (let i = 0; i < binary.length; i++) { return null;
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

@ -0,0 +1,32 @@
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

@ -0,0 +1,23 @@
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

@ -1,9 +1,10 @@
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(`key = "${key}"`); const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
return record.data || fallback; return record.data || fallback;
} catch { } catch {
return fallback; return fallback;
@ -12,5 +13,12 @@ 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 { user: locals.user, colors }; return {
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,78 +1,55 @@
<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 { onMount } from 'svelte';
let { children, data } = $props(); let { children, data } = $props();
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
let importing = $state(false); // Routes rendered without the admin shell: the login screen, and the
// 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));
// 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>
@ -80,48 +57,50 @@
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</svelte:head> </svelte:head>
<div class="min-h-screen bg-base-200"> {#if bare}
<div class="navbar bg-base-100 shadow-sm"> {@render children()}
<div class="flex-1"> {:else}
<a class="btn btn-ghost text-xl" href="/pages">Massage CMS</a> <div class="drawer lg:drawer-open">
<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">
<a class="btn btn-ghost" href="/pages">Pages</a> <div class="drawer-side z-40">
<a class="btn btn-ghost" href="/calendar">Calendar</a> <label for="admin-nav" class="drawer-overlay" aria-label="Close menu"></label>
<a class="btn btn-ghost" href="/items">Items</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="/slots">Slots</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="/orders">Orders</a> <nav class="flex-1" aria-label="Main">
<a class="btn btn-ghost" href="/emails">Emails</a> <ul class="menu w-full gap-0.5 px-3">
<a class="btn btn-ghost" href="/globals">Globals</a> {#each navGroups as group (group.title)}
<div class="dropdown dropdown-end"> <li class="menu-title mt-3 first:mt-0">{group.title}</li>
<button class="btn btn-ghost btn-sm" type="button" tabindex="0"> {#each group.links as link (link.href)}
<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> <li>
Export/Import <a href={link.href} class={isActive(link.href) ? 'bg-primary/10 font-semibold text-primary' : ''} aria-current={isActive(link.href) ? 'page' : undefined}>{link.label}</a>
</button> </li>
<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> {/each}
<li> </ul>
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}> </nav>
{importing ? 'Importing…' : 'Import'} <div class="border-t border-base-300 p-4">
</button> {#if data.user?.email}
</li> <p class="mb-2 truncate text-sm text-base-content/60" title={data.user.email}>{data.user.email}</p>
</ul> {/if}
</div> <form method="POST" action="/login?/logout">
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} /> <button class="btn btn-outline btn-sm w-full" type="submit">Log out</button>
<form class="inline" method="POST" action="/login?/logout"> </form>
<button class="btn btn-outline btn-sm" type="submit">Logout</button> </div>
</form> </aside>
</div> </div>
</div> </div>
{#if importStatus} {/if}
<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,98 +1,101 @@
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 // Build URL → key mapping — only for images that were actually exported.
const urlToKeyMap = new Map<string, string>(); // A URL whose image couldn't be fetched is left as-is rather than turned
for (const url of allUrls) { // into a placeholder the import could never resolve.
urlToKeyMap.set(url, urlToKey(url)); const urlToKeyMap = new Map<string, string>();
} for (const url of allUrls) {
const key = urlToKey(url);
// Replace URLs with placeholders in pages if (key in images) urlToKeyMap.set(url, key);
const exportPages = pages.map((p) => ({ }
slug: p.slug,
title: p.title, // Replace URLs with placeholders in pages
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks, const exportPages = pages.map((p) => ({
published: p.published slug: p.slug,
})); title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
// Replace URLs with placeholders in globals published: p.published
const exportGlobals = globals.map((g) => ({ }));
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown> // Replace URLs with placeholders in globals
})); const exportGlobals = globals.map((g) => ({
key: g.key,
const exportEvents = events.map((record) => { data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
const event = normalizeEvent(record); }));
return {
name: event.name, const exportEvents = events.map((record) => {
start: event.start, const event = normalizeEvent(record);
end: event.end, return {
description: event.description, name: event.name,
color: event.color, start: event.start,
link: event.link, end: event.end,
categories: event.categories, description: event.description,
published: event.published, color: event.color,
allDay: event.allDay link: event.link,
}; categories: event.categories,
}); published: event.published,
allDay: event.allDay
const exportData: SiteExport = { };
version: 1, });
exportedAt: new Date().toISOString(),
pages: exportPages, const exportData: SiteExport = {
globals: exportGlobals, version: 1,
events: exportEvents, exportedAt: new Date().toISOString(),
images pages: exportPages,
}; globals: exportGlobals,
events: exportEvents,
return json(exportData, { images
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,140 +1,146 @@
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,
type SiteExport validateSiteExport,
} from '$lib/exportImport'; type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport; export const POST: RequestHandler = async ({ request, locals }) => {
let body: SiteExport;
if (!body || body.version !== 1) { try {
throw error(400, 'Invalid or unsupported export file.'); body = await request.json();
} } catch {
throw error(400, 'The file is not valid JSON.');
const results = { }
imagesUploaded: 0, const invalid = validateSiteExport(body);
pagesImported: 0, if (invalid) throw error(400, invalid);
globalsImported: 0,
eventsImported: 0, const results = {
errors: [] as string[] imagesUploaded: 0,
}; pagesImported: 0,
globalsImported: 0,
// 1. Upload images to PocketBase media collection eventsImported: 0,
// Build a map: placeholder key → new PocketBase URL errors: [] as string[]
const keyToUrl = new Map<string, string>(); };
for (const [key, dataUri] of Object.entries(body.images)) { // 1. Upload images to PocketBase media collection
try { // Build a map: placeholder key → new PocketBase URL
// Derive a filename from the key (e.g. "abc12345_logo.png") const keyToUrl = new Map<string, string>();
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename); for (const [key, dataUri] of Object.entries(body.images)) {
try {
const formData = new FormData(); // Derive a filename from the key (e.g. "abc12345_logo.png")
formData.append('file', file); const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); const file = dataUriToFile(dataUri, filename);
const record = await locals.pb.collection('media').create(formData); const formData = new FormData();
const publicUrl = env.PUBLIC_POCKETBASE_URL; formData.append('file', file);
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
keyToUrl.set(key, newUrl); const record = await locals.pb.collection('media').create(formData);
results.imagesUploaded++; const publicUrl = env.PUBLIC_POCKETBASE_URL;
} catch (e) { const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
} keyToUrl.set(key, newUrl);
} results.imagesUploaded++;
} catch (e) {
// 2. Import pages results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
for (const page of body.pages) { }
try { }
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// 2. Import pages
// Try to find existing page by slug for (const page of body.pages) {
let existing; try {
try { const blocks = restorePlaceholders(page.blocks, keyToUrl);
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch { // Try to find existing page by slug
existing = null; let existing;
} try {
existing = await locals.pb.collection('pages').getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: page.slug }));
if (existing) { } catch {
await locals.pb.collection('pages').update(existing.id, { existing = null;
title: page.title, }
blocks,
published: page.published if (existing) {
}); await locals.pb.collection('pages').update(existing.id, {
} else { title: page.title,
await locals.pb.collection('pages').create({ blocks,
slug: page.slug, published: page.published
title: page.title, });
blocks, } else {
published: page.published await locals.pb.collection('pages').create({
}); slug: page.slug,
} title: page.title,
results.pagesImported++; blocks,
} catch (e) { published: page.published
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`); });
} }
} results.pagesImported++;
} catch (e) {
// 3. Import globals results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
for (const g of body.globals) { }
try { }
const data = restorePlaceholders(g.data, keyToUrl);
// 3. Import globals
let existing; for (const g of body.globals) {
try { try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`); const data = restorePlaceholders(g.data, keyToUrl);
} catch {
existing = null; let existing;
} try {
existing = await locals.pb.collection('globals').getFirstListItem(locals.pb.filter('key = {:key}', { key: g.key }));
if (existing) { } catch {
await locals.pb.collection('globals').update(existing.id, { data }); existing = null;
} else { }
await locals.pb.collection('globals').create({ key: g.key, data });
} if (existing) {
results.globalsImported++; await locals.pb.collection('globals').update(existing.id, { data });
} catch (e) { } else {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`); await locals.pb.collection('globals').create({ key: g.key, data });
} }
} results.globalsImported++;
} catch (e) {
// 4. Import events results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
for (const event of body.events || []) { }
try { }
let existing;
try { // 4. Import events
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`); for (const event of body.events || []) {
} catch { try {
existing = null; let existing;
} try {
existing = await locals.pb
const payload = { .collection('events')
name: event.name, .getFirstListItem(locals.pb.filter('name = {:name} && start = {:start}', { name: event.name, start: event.start }));
start: event.start, } catch {
end: event.end || null, existing = null;
description: event.description || '', }
color: event.color || '#8a9a7b',
link: event.link || '', const payload = {
categories: event.categories || [], name: event.name,
published: Boolean(event.published), start: event.start,
allDay: event.allDay !== false end: event.end || null,
}; description: event.description || '',
color: event.color || '#8a9a7b',
if (existing) { link: event.link || '',
await locals.pb.collection('events').update(existing.id, payload); categories: event.categories || [],
} else { published: Boolean(event.published),
await locals.pb.collection('events').create(payload); allDay: event.allDay !== false
} };
results.eventsImported++;
} catch (e) { if (existing) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`); await locals.pb.collection('events').update(existing.id, payload);
} } else {
} await locals.pb.collection('events').create(payload);
}
return json(results); results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
}; };

View file

@ -0,0 +1,112 @@
<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,54 +1,62 @@
import { fail } from '@sveltejs/kit'; import { env } from '$env/dynamic/private';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar'; import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types'; import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import { attempt } from '$lib/server/actions';
function eventPayload(data: FormData) { import type { Actions, PageServerLoad } from './$types';
const allDay = String(data.get('allDay')) === 'true';
const start = String(data.get('start') || '').trim(); function eventPayload(data: FormData) {
const end = String(data.get('end') || '').trim(); const allDay = String(data.get('allDay')) === 'true';
const name = String(data.get('name') || '').trim(); const start = String(data.get('start') || '').trim();
const end = String(data.get('end') || '').trim();
return { const name = String(data.get('name') || '').trim();
name, const timeZone = env.SITE_TIMEZONE || 'Europe/Oslo';
start: dateInputToPocketBase(start, allDay),
end: end ? dateInputToPocketBase(end, allDay) : null, return {
description: String(data.get('description') || '').trim(), name,
color: String(data.get('color') || '#8a9a7b').trim(), start: dateInputToPocketBase(start, allDay, timeZone),
link: String(data.get('link') || '').trim(), end: end ? dateInputToPocketBase(end, allDay, timeZone) : null,
categories: normalizeCategories(String(data.get('categories') || '')), description: String(data.get('description') || '').trim(),
published: String(data.get('published')) === 'true', color: String(data.get('color') || '#8a9a7b').trim(),
allDay link: String(data.get('link') || '').trim(),
}; 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));
return { events }; 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 actions: Actions = { return { events };
create: async ({ request, locals }) => { };
const data = await request.formData();
const payload = eventPayload(data); export const actions: Actions = {
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); create: async ({ request, locals }) => {
await locals.pb.collection('events').create(payload); const data = await request.formData();
return { ok: true }; const payload = eventPayload(data);
}, if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
update: async ({ request, locals }) => { if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' });
const data = await request.formData(); const result = await attempt('Could not create the event.', () => locals.pb.collection('events').create(payload));
const id = String(data.get('id') || ''); if (!result.ok) return result.failure;
const payload = eventPayload(data); return { ok: true };
if (!id) return fail(400, { message: 'Event id is required.' }); },
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); update: async ({ request, locals }) => {
await locals.pb.collection('events').update(id, payload); const data = await request.formData();
return { ok: true }; const id = String(data.get('id') || '');
}, const payload = eventPayload(data);
delete: async ({ request, locals }) => { if (!id) return fail(400, { message: 'Event id is required.' });
const data = await request.formData(); if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
const id = String(data.get('id') || ''); if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' });
if (!id) return fail(400, { message: 'Event id is required.' }); const result = await attempt('Could not save the event.', () => locals.pb.collection('events').update(id, payload));
await locals.pb.collection('events').delete(id); if (!result.ok) return result.failure;
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,236 +1,229 @@
<script lang="ts"> <script lang="ts">
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar'; import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toZonedDatetimeInput } from '$lib/calendar';
import type { CalendarEventRecord } from '$lib/types'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
let { data, form } = $props(); import type { CalendarEventRecord } from '$lib/types';
let events = $derived(sortEvents(data.events || []));
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1)); let { data, form } = $props();
let showEditor = $state(false); let events = $derived(sortEvents(data.events || []));
let draft = $state<CalendarEventRecord>({ let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
id: '', let showEditor = $state(false);
name: '', let draft = $state<CalendarEventRecord>({
start: toDateInput(new Date().toISOString()), id: '',
end: '', name: '',
description: '', start: toDateInput(new Date().toISOString()),
color: '#8a9a7b', end: '',
link: '', description: '',
categories: [], color: '#8a9a7b',
published: false, link: '',
allDay: true categories: [],
}); published: false,
let categoryText = $state(''); allDay: true
});
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; let categoryText = $state('');
let month = $derived(createCalendarMonth(viewDate));
let action = $derived(draft.id ? '?/update' : '?/create'); const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local'); let month = $derived(createCalendarMonth(viewDate, new Date(), 1));
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start)); let action = $derived(draft.id ? '?/update' : '?/create');
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end)); let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b))); let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toZonedDatetimeInput(draft.start, data.timezone));
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toZonedDatetimeInput(draft.end, data.timezone));
function eventsForDay(date: Date) { let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
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 {
id: '', function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
name: '', return {
start, id: '',
end: '', name: '',
description: '', start,
color: '#8a9a7b', end: '',
link: '', description: '',
categories: [], color: '#8a9a7b',
published: false, link: '',
allDay: true categories: [],
}; published: false,
} allDay: true
};
function createEvent(start?: string) { }
draft = emptyDraft(start);
categoryText = ''; function createEvent(start?: string) {
showEditor = true; draft = emptyDraft(start);
} categoryText = '';
showEditor = true;
function editEvent(event: CalendarEventRecord) { }
draft = structuredClone(event);
categoryText = event.categories.join(', '); function editEvent(event: CalendarEventRecord) {
showEditor = true; draft = structuredClone(event);
} 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;
draft = { ...draft, categories: [...draft.categories, category] }; function addCategory(category: string) {
categoryText = draft.categories.join(', '); if (!category || draft.categories.includes(category)) return;
} draft = { ...draft, categories: [...draft.categories, category] };
categoryText = draft.categories.join(', ');
function removeCategory(category: string) { }
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
categoryText = draft.categories.join(', '); function removeCategory(category: string) {
} draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
categoryText = draft.categories.join(', ');
function syncCategoryText(value: string) { }
categoryText = value;
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) }; function syncCategoryText(value: string) {
} categoryText = value;
</script> draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
}
<svelte:head><title>Calendar | CMS</title></svelte:head> </script>
<div class="space-y-6"> <svelte:head><title>Events | CMS</title></svelte:head>
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div> <div class="space-y-6">
<h1 class="text-3xl font-bold">Calendar</h1> <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p> <div>
</div> <h1 class="text-3xl font-bold">Events</h1>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button> <p class="text-base-content/60">Workshops and events shown in Upcoming Calendar blocks.</p>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if} </div>
<div class="rounded-box bg-base-100 p-5 shadow"> {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button> <div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="text-2xl font-bold">{month.label}</h2> <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button> <button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
</div> <h2 class="text-2xl font-bold">{month.label}</h2>
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
<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> <div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
<div class="mt-2 grid grid-cols-7 gap-2"> {#each weekdays as weekday}<div>{weekday}</div>{/each}
{#each month.days as day} </div>
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}> <div class="mt-2 grid grid-cols-7 gap-2">
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button> {#each month.days as day}
<div class="space-y-1"> <div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
{#each eventsForDay(day.date) as event} <button class="btn btn-circle btn-xs mb-1 {day.isToday ? 'btn-primary' : 'btn-ghost'}" type="button" title="Create an event on this day" aria-current={day.isToday ? 'date' : undefined} onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
<button class="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)}> <div class="space-y-1">
<span class="block truncate">{event.name}</span> {#each eventsForDay(day.date) as event}
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</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)}>
</button> <span class="block truncate">{event.name}</span>
{/each} <span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
</div> </button>
</div> {/each}
{/each} </div>
</div> </div>
</div> {/each}
</div>
<div class="rounded-box bg-base-100 p-5 shadow"> </div>
<h2 class="mb-4 text-xl font-bold">All events</h2>
<div class="overflow-x-auto"> <div class="rounded-box bg-base-100 p-5 shadow">
<table class="table"> <h2 class="mb-4 text-xl font-bold">All events</h2>
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead> <div class="overflow-x-auto">
<tbody> <table class="table">
{#each events as event} <thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
<tr> <tbody>
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td> {#each events as event (event.id)}
<td>{formatEventDateRange(event)}</td> <tr>
<td>{event.categories.join(', ')}</td> <td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td> <td>{formatEventDateRange(event)}</td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td> <td>{event.categories.join(', ')}</td>
</tr> <td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
{/each} <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
</tbody> </tr>
</table> {:else}
</div> <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>
</table>
{#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>
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2> <Modal bind:open={showEditor} title={draft.id ? 'Edit event' : 'Create event'} wide>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button> <form method="POST" action={action} class="space-y-1">
</div> <input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<form method="POST" action={action} class="space-y-4"> <input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
<input type="hidden" name="id" value={draft.id} /> <input type="hidden" name="categories" value={categoryText} />
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} /> <label class="fieldset">
<input type="hidden" name="categories" value={categoryText} /> <span class="fieldset-legend">Name</span>
<input class="input w-full" name="name" required bind:value={draft.name} />
<label class="form-control w-full"> </label>
<div class="label"><span class="label-text">Name</span></div>
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} /> <div class="grid gap-x-4 md:grid-cols-2">
</label> <label class="fieldset">
<span class="fieldset-legend">Start{draft.allDay ? '' : ` (${data.timezone})`}</span>
<div class="grid gap-4 md:grid-cols-2"> <input class="input w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
<label class="form-control w-full"> </label>
<div class="label"><span class="label-text">Start</span></div> <label class="fieldset">
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} /> <span class="fieldset-legend">End <span class="font-normal text-base-content/50">(optional)</span></span>
</label> <input class="input w-full" type={dateInputType} name="end" min={startValue} value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
<label class="form-control w-full"> </label>
<div class="label"><span class="label-text">End optional</span></div> </div>
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
</label> <div class="flex flex-wrap gap-6 py-2">
</div> <label class="label cursor-pointer gap-3 text-base-content">
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
<div class="flex flex-wrap gap-4"> All-day event
<label class="label cursor-pointer justify-start gap-3"> </label>
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} /> <label class="label cursor-pointer gap-3 text-base-content">
<span class="label-text">All-day event</span> <input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
</label> Published
<label class="label cursor-pointer justify-start gap-3"> </label>
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} /> </div>
<span class="label-text">Published</span>
</label> <label class="fieldset">
</div> <span class="fieldset-legend">Description</span>
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
<label class="form-control w-full"> </label>
<div class="label"><span class="label-text">Description</span></div>
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea> <div class="grid gap-x-4 md:grid-cols-2">
</label> <div class="fieldset">
<span class="fieldset-legend">Color</span>
<div class="grid gap-4 md:grid-cols-2"> <div class="flex gap-2">
<label class="form-control w-full"> <input class="input w-14 cursor-pointer p-1" type="color" aria-label="Pick color" bind:value={draft.color} />
<div class="label"><span class="label-text">Color</span></div> <input class="input flex-1 font-mono" name="color" aria-label="Color value" bind:value={draft.color} />
<div class="flex gap-2"> </div>
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} /> </div>
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} /> <label class="fieldset">
</div> <span class="fieldset-legend">Link <span class="font-normal text-base-content/50">(optional)</span></span>
</label> <input class="input w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
<label class="form-control w-full"> </label>
<div class="label"><span class="label-text">Link optional</span></div> </div>
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
</label> <div class="fieldset">
</div> <label class="fieldset-legend" for="event-categories">Categories <span class="font-normal text-base-content/50">(comma-separated)</span></label>
<input id="event-categories" class="input w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
<div class="rounded-box border border-base-300 p-4"> {#if allCategories.length}
<label class="form-control w-full"> <div class="mt-1 flex flex-wrap gap-2">
<div class="label"><span class="label-text">Categories comma-separated</span></div> {#each allCategories as category}
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} /> <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>
</label> {/each}
{#if allCategories.length} </div>
<div class="mt-3 flex flex-wrap gap-2"> {/if}
{#each allCategories as category} </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>
{/each} <div class="modal-action justify-between">
</div> {#if draft.id}
{/if} <button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit(`Delete the event "${draft.name}"?`)}>Delete</button>
</div> {:else}
<span></span>
<div class="flex justify-between gap-2 pt-2"> {/if}
{#if draft.id} <div class="flex gap-2">
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button> <button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
{:else} <button class="btn btn-primary" type="submit">Save event</button>
<span></span> </div>
{/if} </div>
<div class="flex gap-2"> </form>
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> </Modal>
<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,9 +31,7 @@
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');
beforeNavigate(({ cancel, type }) => { warnOnUnsavedChanges(() => dirty);
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);
@ -46,8 +44,9 @@
} }
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[0]?.id || ''; if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || '';
} }
function moveBlock(from: number, to: number) { function moveBlock(from: number, to: number) {
@ -100,24 +99,22 @@
<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="rounded-box space-y-4 bg-base-100 p-5 shadow"> <div class="space-y-2 rounded-box bg-base-100 p-5 shadow">
<label class="label cursor-pointer justify-start gap-3"> <label class="label cursor-pointer gap-3 text-base-content">
<input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} /> <input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} />
<span class="label-text">{enabled ? 'This email is sent automatically' : 'This email is turned off'}</span> {enabled ? 'This email is sent automatically' : 'This email is turned off'}
</label> </label>
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Subject</span></div> <span class="fieldset-legend">Subject</span>
<input class="input input-bordered w-full" name="subject" bind:value={subject} /> <input class="input w-full" name="subject" bind:value={subject} />
</label> </label>
{#if isAlert} {#if isAlert}
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Send to (comma-separated)</span></div> <span class="fieldset-legend">Send to (comma-separated)</span>
<input class="input input-bordered w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} /> <input class="input w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} />
<div class="label"> <span class="label">
<span class="label-text-alt text-base-content/60"> {#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}
{#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>
</span>
</div>
</label> </label>
{:else} {:else}
<input type="hidden" name="recipients" value="" /> <input type="hidden" name="recipients" value="" />
@ -209,7 +206,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 input-bordered flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required /> <input class="input 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,31 +1,55 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types'; import { ClientResponseError } from 'pocketbase';
import { attempt } from '$lib/server/actions';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
try { import type { Actions, PageServerLoad } from './$types';
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
} catch { const SECTIONS = ['header', 'footer', 'colors'] as const;
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 }));
export const load: PageServerLoad = async ({ locals }) => { } catch (e) {
const [header, footer, colors] = await Promise.all([ // Only create the record when it genuinely doesn't exist — any other
getGlobal(locals.pb, 'header', defaultHeader), // error (PocketBase down, auth) must not create duplicates.
getGlobal(locals.pb, 'footer', defaultFooter), if (e instanceof ClientResponseError && e.status === 404) {
getGlobal(locals.pb, 'colors', defaultColors) return await pb.collection('globals').create({ key, data: fallback });
]); }
throw e;
// Fetch all pages for the home page selector }
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); }
return { header, footer, colors, pages }; export const load: PageServerLoad = async ({ locals }) => {
}; const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
export const actions: Actions = { getGlobal(locals.pb, 'footer', defaultFooter),
save: async ({ request, locals }) => { getGlobal(locals.pb, 'colors', defaultColors)
const data = await request.formData(); ]);
const id = String(data.get('id'));
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) }); // Fetch all pages for the home page selector
} 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,96 +1,148 @@
<script lang="ts"> <script lang="ts">
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte'; import { enhance } from '$app/forms';
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
let { data } = $props(); import type { SubmitFunction } from '@sveltejs/kit';
let header = $state(structuredClone(data.header.data));
let footer = $state(structuredClone(data.footer.data)); let { data, form } = $props();
let colors = $state(structuredClone(data.colors.data)); let header = $state(structuredClone(data.header.data));
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; } let footer = $state(structuredClone(data.footer.data));
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; } let colors = $state(structuredClone(data.colors.data));
</script> let saving = $state('');
// Older records may predate the CTA button; the inputs below need an object.
<svelte:head><title>Globals | CMS</title></svelte:head> header.ctaButton ??= { label: '', href: '' };
<div class="mb-6"> function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
<h1 class="text-3xl font-bold">Global sections</h1> function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
</div> const footerFields = [
{ key: 'businessName', label: 'Business name' },
<div class="grid gap-6 xl:grid-cols-3"> { key: 'tagline', label: 'Tagline' },
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save"> { key: 'address', label: 'Address' },
<input type="hidden" name="id" value={data.header.id} /> { key: 'phone', label: 'Phone' },
<input type="hidden" name="data" value={JSON.stringify(header)} /> { key: 'email', label: 'Email', hint: 'Also used as the reply-to and alert address for booking emails.' },
<h2 class="mb-4 text-2xl font-bold">Header</h2> { key: 'copyrightText', label: 'Copyright text' }
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} /> ];
<h3 class="mt-6 font-bold">Navigation</h3>
{#each header.navLinks || [] as link, i} const colorFields = [
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2"> { key: 'background', label: 'Background' },
<input class="input input-bordered" bind:value={link.label} placeholder="Label" /> { key: 'heading', label: 'Headings' },
<input class="input input-bordered" bind:value={link.href} placeholder="Href" /> { key: 'subheading', label: 'Subheadings' },
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button> { key: 'text', label: 'Body text' },
</div> { key: 'primary', label: 'Primary', hint: 'Buttons and links' },
{/each} { key: 'accent', label: 'Accent', hint: 'Highlights' }
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button> ];
<h3 class="mt-6 font-bold">CTA button</h3>
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" /> const isHex = (value: unknown) => typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value);
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
<h3 class="mt-6 font-bold">Home page</h3> const submit: SubmitFunction = ({ formData }) => {
<select class="select select-bordered w-full" bind:value={header.homePage}> saving = String(formData.get('section'));
<option value="">— Select a page —</option> return async ({ update }) => {
{#each data.pages as page} await update({ reset: false, invalidateAll: 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,5 +1,6 @@
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';
@ -51,8 +52,9 @@ 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)) return fail(400, { message: 'Name and price are required.' }); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
await locals.pb.collection('items').create(payload); const result = await attempt('Could not create the item.', () => 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 }) => {
@ -60,15 +62,17 @@ 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)) return fail(400, { message: 'Name and price are required.' }); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
await locals.pb.collection('items').update(id, payload); const result = await attempt('Could not save the item.', () => 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.' });
await locals.pb.collection('items').delete(id); 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));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -1,10 +1,15 @@
<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;
@ -22,7 +27,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');
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }); let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft { function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true }; return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true };
@ -30,6 +35,7 @@
function createItem() { function createItem() {
draft = emptyDraft(); draft = emptyDraft();
uploadError = '';
showEditor = true; showEditor = true;
} }
@ -46,6 +52,7 @@
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;
} }
@ -54,16 +61,12 @@
const file = input.files?.[0]; const file = input.files?.[0];
if (!file) return; if (!file) return;
uploading = true; uploading = true;
uploadError = '';
try { try {
const formData = new FormData(); const result = await uploadMedia(file);
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) {
console.error(err); uploadError = err instanceof Error ? err.message : 'Upload failed.';
} finally { } finally {
uploading = false; uploading = false;
input.value = ''; input.value = '';
@ -71,41 +74,45 @@
} }
</script> </script>
<svelte:head><title>Items | CMS</title></svelte:head> <svelte:head><title>Services & products | 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">Items</h1> <h1 class="text-3xl font-bold">Services & products</h1>
<p class="text-base-content/60">Manage services and products shown in Shop blocks.</p> <p class="text-base-content/60">Bookable services and products, shown in Shop blocks.</p>
</div> </div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Create item</button> <button class="btn btn-primary" type="button" onclick={() => createItem()}>Add service or product</button>
</div> </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="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} {#each items as item (item.id)}
<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="h-10 w-10 rounded-box object-cover" src={item.imageUrl} alt="" /> <img class="size-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>{eur.format(item.price)}</td> <td>{money.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '—') : '—'}</td> <td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</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>
@ -113,87 +120,84 @@
</div> </div>
</div> </div>
{#if showEditor} <Modal bind:open={showEditor} title={draft.id ? `Edit “${draft.name}”` : 'New service or product'} wide>
<div class="fixed inset-0 z-50 bg-black/50 p-4"> <form method="POST" action={action} class="space-y-1">
<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="id" value={draft.id} />
<div class="mb-4 flex items-center justify-between gap-3"> <input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
<h2 class="text-2xl font-bold">{draft.id ? 'Edit item' : 'Create item'}</h2> <input type="hidden" name="image" value={draft.image} />
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<form method="POST" action={action} class="space-y-4"> <label class="fieldset">
<input type="hidden" name="id" value={draft.id} /> <span class="fieldset-legend">Name</span>
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} /> <input class="input w-full" name="name" required bind:value={draft.name} />
</label>
<label class="form-control w-full"> <label class="fieldset">
<div class="label"><span class="label-text">Name</span></div> <span class="fieldset-legend">Description</span>
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} /> <textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label> </label>
<label class="form-control w-full"> <div class="grid gap-x-4 md:grid-cols-2">
<div class="label"><span class="label-text">Description</span></div> <label class="fieldset">
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea> <span class="fieldset-legend">Price ({data.currency})</span>
</label> <input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label>
<div class="grid gap-4 md:grid-cols-2"> <label class="fieldset">
<label class="form-control w-full"> <span class="fieldset-legend">Type</span>
<div class="label"><span class="label-text">Price</span></div> <select class="select w-full" name="type" bind:value={draft.type}>
<input class="input input-bordered w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} /> <option value="item">Product</option>
</label> <option value="item_with_time">Service (bookable)</option>
<label class="form-control w-full"> </select>
<div class="label"><span class="label-text">Type</span></div> </label>
<select class="select select-bordered w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service</option>
</select>
</label>
</div>
{#if draft.type === 'item'}
<label class="form-control w-full">
<div class="label"><span class="label-text">Stock</span></div>
<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="form-control w-full">
<div class="label"><span class="label-text">Image</span></div>
<div class="flex items-start gap-3">
{#if draft.imageUrl}
<img class="h-16 w-16 rounded-box object-cover" src={draft.imageUrl} alt="" />
{/if}
<div class="flex-1 space-y-2">
<input class="input input-bordered w-full" name="image" placeholder="Media record id" bind:value={draft.image} />
<input class="file-input file-input-bordered file-input-sm w-full" type="file" accept="image/*" disabled={uploading} onchange={onImageSelected} />
<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>
</div>
{/if} {#if draft.type === 'item'}
<label class="fieldset">
<span class="fieldset-legend">Stock</span>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
{:else}
<label class="fieldset">
<span class="fieldset-legend">Duration (minutes)</span>
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} />
</label>
{/if}
<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>
<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">
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} />
Active <span class="text-base-content/60">— inactive items are hidden from the shop</span>
</label>
<div class="modal-action justify-between">
{#if draft.id}
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit(`Delete "${draft.name}"?`)}>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" disabled={uploading}>Save</button>
</div>
</div>
</form>
</Modal>

View file

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

View file

@ -1,26 +1,38 @@
<script lang="ts"> <script lang="ts">
let { form } = $props(); let { form } = $props();
</script> let submitting = $state(false);
</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">
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login"> <div class="grid min-h-screen place-items-center bg-base-200 p-4">
<div class="card-body"> <div class="w-full max-w-sm">
<h1 class="card-title text-3xl">Sign in</h1> <p class="mb-6 text-center text-lg font-bold tracking-tight">Massage CMS</p>
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p> <form class="card bg-base-100 shadow-xl" method="POST" action="?/login" onsubmit={() => (submitting = true)}>
{#if form?.message} <div class="card-body gap-4">
<div class="alert alert-error mt-4">{form.message}</div> <div>
{/if} <h1 class="text-2xl font-bold">Sign in</h1>
<label class="form-control mt-4"> <p class="text-sm text-base-content/60">Use your CMS account to manage the website.</p>
<span class="label-text">Email</span> </div>
<input class="input input-bordered" name="email" type="email" required /> {#if form?.message}
</label> <div class="alert alert-error text-sm" role="alert">{form.message}</div>
<label class="form-control"> {/if}
<span class="label-text">Password</span> <fieldset class="fieldset gap-3 p-0">
<input class="input input-bordered" name="password" type="password" required /> <label class="flex flex-col gap-1">
</label> <span class="fieldset-legend p-0">Email</span>
<button class="btn btn-primary mt-4" type="submit">Login</button> <!-- svelte-ignore a11y_autofocus -->
</div> <input class="input w-full" name="email" type="email" autocomplete="username" defaultValue={form?.email ?? ''} required autofocus />
</form> </label>
</div> <label class="flex flex-col gap-1">
<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,38 +3,45 @@ 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 }) => {
// Sort by id, not 'created' — commerce collections were imported without // Newest first. `created` comes from the 1791244800 migration; orders made
// autodate fields. PocketBase ids are time-sortable ULIDs. // before it have no date and sort last (PocketBase ids are random, so they
const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []); // can't be ordered chronologically).
const records = await locals.pb.collection('orders').getFullList({ sort: '-created,-id' }).catch(() => []);
const orders = []; // All lines in one request (previously one request per order).
for (const record of records) { const lineRecords = records.length
const lineRecords = await locals.pb ? await locals.pb
.collection('order_lines') .collection('order_lines')
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) }) .getFullList({ sort: 'start' })
.catch(() => []); .catch(() => [])
: [];
orders.push({ const linesByOrder = new Map<string, typeof lineRecords>();
id: record.id, for (const line of lineRecords) {
email: String(record.email || ''), const list = linesByOrder.get(line.order) ?? [];
customerDetails: record.customerDetails || {}, list.push(line);
total: Number(record.total) || 0, linesByOrder.set(line.order, list);
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,11 +1,12 @@
<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('');
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }); let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
</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)}
@ -23,7 +24,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 ? new Date(sentAt).toLocaleString() : 'Not sent'}> <span class="badge badge-sm" class:badge-success={sentAt} class:badge-ghost={!sentAt} title={sentAt ? `Sent ${formatDateTime(sentAt, data.timezone)}` : '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 !== ''}>
@ -37,14 +38,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">Confirmed bookings and purchases.</p> <p class="text-base-content/60">Bookings and purchases from the shop.</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} {#each orders as order (order.id)}
<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>
@ -52,7 +53,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} · {new Date(order.created).toLocaleString()}{/if} {#if order.created} · {formatDateTime(order.created, data.timezone)}{/if}
</p> </p>
</div> </div>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
@ -62,16 +63,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">{eur.format(order.total)}</span> <span class="text-lg font-bold">{money.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} — {eur.format(line.price)} {line.quantity}× {line.name} — {money.format(line.price)}
{#if line.lineType === 'slot' && line.start} {#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{new Date(line.start).toLocaleString()}</span> <span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}</span>
{/if} {/if}
</li> </li>
{/each} {/each}

View file

@ -1,29 +1,39 @@
import { fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types'; import { attempt } from '$lib/server/actions';
import { normalizeSlug, slugTaken } from '$lib/server/pages';
export const load: PageServerLoad = async ({ locals }) => { import type { Actions, PageServerLoad } from './$types';
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { pages }; export const load: PageServerLoad = async ({ locals }) => {
}; const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
return { pages };
export const actions: Actions = { };
create: async ({ request, locals }) => {
const data = await request.formData(); export const actions: Actions = {
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-'); create: async ({ request, locals }) => {
const title = String(data.get('title') || '').trim(); const data = await request.formData();
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); const slug = normalizeSlug(data.get('slug'));
const title = String(data.get('title') || '').trim();
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false }); if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
throw redirect(303, `/pages/${slug}`); if (await slugTaken(locals.pb, slug)) return fail(400, { message: `A page with the slug "${slug}" already exists.` });
},
toggle: async ({ request, locals }) => { const result = await attempt('Could not create the page.', () =>
const data = await request.formData(); locals.pb.collection('pages').create({ slug, title, blocks: [], published: false })
await locals.pb.collection('pages').update(String(data.get('id')), { );
published: String(data.get('published')) !== 'true' if (!result.ok) return result.failure;
}); throw redirect(303, `/pages/${slug}`);
}, },
delete: async ({ request, locals }) => { toggle: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
await locals.pb.collection('pages').delete(String(data.get('id'))); const result = await attempt('Could not change the publish status.', () =>
} 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,65 +1,79 @@
<script lang="ts"> <script lang="ts">
let { data, form } = $props(); import { env } from '$env/dynamic/public';
</script> import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte';
<svelte:head><title>Pages | CMS</title></svelte:head>
let { data, form } = $props();
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center"> let showCreate = $state(false);
<div>
<h1 class="text-3xl font-bold">Pages</h1> const siteUrl = (env.PUBLIC_SITE_URL || '').replace(/\/$/, '');
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p> const publicUrl = (slug: string) => `${siteUrl}/${slug === 'home' ? '' : slug}`;
</div> </script>
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
</div> <svelte:head><title>Pages | CMS</title></svelte:head>
{#if form?.message} <div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
<div class="alert alert-error mb-4">{form.message}</div> <div>
{/if} <h1 class="text-3xl font-bold">Pages</h1>
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
<div class="overflow-x-auto rounded-box bg-base-100 shadow"> </div>
<table class="table"> <button class="btn btn-primary" type="button" onclick={() => (showCreate = true)}>New page</button>
<thead> </div>
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
</thead> {#if form?.message}
<tbody> <div class="alert alert-error mb-4" role="alert">{form.message}</div>
{#each data.pages as page} {/if}
<tr>
<td class="font-mono">{page.slug}</td> <div class="overflow-x-auto rounded-box bg-base-100 shadow">
<td>{page.title}</td> <table class="table">
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td> <thead>
<td class="flex justify-end gap-2"> <tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a> </thead>
<a class="btn btn-sm" href={`${import.meta.env.VITE_PUBLIC_SITE_URL}/${page.slug === 'home' ? '' : page.slug}`} target="_blank">Preview</a> <tbody>
<form method="POST" action="?/toggle"> {#each data.pages as page (page.id)}
<input type="hidden" name="id" value={page.id} /> <tr>
<input type="hidden" name="published" value={page.published} /> <td class="font-mono">{page.slug}</td>
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button> <td>{page.title}</td>
</form> <td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}> <td>
<input type="hidden" name="id" value={page.id} /> <div class="flex flex-wrap justify-end gap-2">
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button> <a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
</form> {#if siteUrl && page.published}
</td> <a class="btn btn-sm" href={publicUrl(page.slug)} target="_blank" rel="noopener" title="Open on the live site">View</a>
</tr> {/if}
{/each} <form method="POST" action="?/toggle">
</tbody> <input type="hidden" name="id" value={page.id} />
</table> <input type="hidden" name="published" value={page.published} />
</div> <button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
</form>
<dialog id="new-page" class="modal"> <form method="POST" action="?/delete" onsubmit={confirmSubmit(`Delete the page "${page.title}"? This cannot be undone.`)}>
<form class="modal-box" method="POST" action="?/create"> <input type="hidden" name="id" value={page.id} />
<h2 class="text-2xl font-bold">Create page</h2> <button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
<label class="form-control w-full mt-4"> </form>
<div class="label"><span class="label-text">Slug</span></div> </div>
<input class="input input-bordered w-full" name="slug" placeholder="about" required /> </td>
</label> </tr>
<label class="form-control w-full"> {:else}
<div class="label"><span class="label-text">Title</span></div> <tr><td colspan="4" class="py-10 text-center text-base-content/60">No pages yet — create your first one.</td></tr>
<input class="input input-bordered w-full" name="title" placeholder="About" required /> {/each}
</label> </tbody>
<div class="modal-action"> </table>
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button> </div>
<button class="btn btn-primary" type="submit">Create</button>
</div> <Modal bind:open={showCreate} title="Create page">
</form> <form method="POST" action="?/create" class="space-y-1">
</dialog> <label class="fieldset">
<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,30 +1,56 @@
import { fail, redirect } from '@sveltejs/kit'; import { error, fail, redirect } from '@sveltejs/kit';
import { extractCategories, normalizeEvent } from '$lib/calendar'; import { ClientResponseError } from 'pocketbase';
import type { Actions, PageServerLoad } from './$types'; import { extractCategories, normalizeEvent } from '$lib/calendar';
import { attempt } from '$lib/server/actions';
export const load: PageServerLoad = async ({ params, locals }) => { import { normalizeSlug, slugTaken } from '$lib/server/pages';
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`); import type { Actions, PageServerLoad } from './$types';
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event))); export const load: PageServerLoad = async ({ params, locals }) => {
const items = await locals.pb const page = await locals.pb
.collection('items') .collection('pages')
.getFullList({ sort: 'name' }) .getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: params.slug }))
.then((records) => records.map(({ id, name, type }) => ({ id, name, type }))) .catch((e) => {
.catch(() => []); if (e instanceof ClientResponseError && e.status === 404) throw error(404, `No page with the slug "${params.slug}".`);
return { page, eventCategories, items }; throw e;
}; });
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
export const actions: Actions = { const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
save: async ({ request, locals }) => { const items = await locals.pb
const data = await request.formData(); .collection('items')
const id = String(data.get('id')); .getFullList({ sort: 'name' })
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-'); .then((records) => records.map(({ id, name, type }) => ({ id, name, type })))
const title = String(data.get('title') || '').trim(); .catch(() => []);
const blocks = JSON.parse(String(data.get('blocks') || '[]')); return { page, eventCategories, items };
const publish = String(data.get('publish')) === 'true'; };
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
export const actions: Actions = {
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) }); save: async ({ params, request, locals }) => {
throw redirect(303, `/pages/${slug}`); const data = await request.formData();
} 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,104 +1,156 @@
<script lang="ts"> <script lang="ts">
import BlockList from '$lib/admin/BlockList.svelte'; import { enhance } from '$app/forms';
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults'; import BlockList from '$lib/admin/BlockList.svelte';
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte'; import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
import type { ContentBlock } from '$lib/types'; import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
import { warnOnUnsavedChanges } from '$lib/admin/unsaved.svelte';
let { data, form } = $props(); import type { ContentBlock } from '$lib/types';
let page = $state(data.page);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || [])); let { data, form } = $props();
let selectedId = $state(blocks[0]?.id || ''); // Local editable copies; the server data is only the starting point.
let previewMode = $state<'desktop' | 'mobile'>('desktop'); let slug = $state(data.page.slug);
let showPreview = $state(false); let title = $state(data.page.title);
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null); let selectedId = $state(data.page.blocks?.[0]?.id || '');
let published = $derived(data.page.published);
function addBlock(type: keyof typeof blockLabels) { let previewMode = $state<'desktop' | 'mobile'>('desktop');
const block = createBlock(type); let showPreview = $state(false);
blocks = [...blocks, block]; let saving = $state<'' | 'save' | 'publish'>('');
selectedId = block.id;
} const serialize = () => JSON.stringify({ slug, title, blocks });
let savedSnapshot = $state(serialize());
function updateBlock(updated: ContentBlock) { let dirty = $derived(serialize() !== savedSnapshot);
blocks = blocks.map((block) => (block.id === updated.id ? updated : block)); warnOnUnsavedChanges(() => dirty);
}
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id); function addBlock(type: keyof typeof blockLabels) {
if (selectedId === id) selectedId = blocks[0]?.id || ''; const block = createBlock(type);
} blocks = [...blocks, block];
selectedId = block.id;
function moveBlock(from: number, to: number) { (document.activeElement as HTMLElement | null)?.blur(); // close the dropdown
const copy = [...blocks]; }
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item); function updateBlock(updated: ContentBlock) {
blocks = copy; blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
} }
function openPreview() { function deleteBlock(id: string) {
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks)); const index = blocks.findIndex((block) => block.id === id);
showPreview = true; blocks = blocks.filter((block) => block.id !== id);
} if (selectedId === id) selectedId = (blocks[index] ?? blocks[index - 1])?.id || '';
}
function markPublish(event: MouseEvent) {
const form = (event.currentTarget as HTMLButtonElement).form; function moveBlock(from: number, to: number) {
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null; const copy = [...blocks];
if (input) input.value = 'true'; const [item] = copy.splice(from, 1);
} copy.splice(to, 0, item);
</script> blocks = copy;
}
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
function openPreview() {
<form method="POST" action="?/save" class="space-y-6"> sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
<input type="hidden" name="id" value={page.id} /> showPreview = true;
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} /> }
<input type="hidden" name="publish" value="false" /> </script>
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <svelte:head><title>Edit {title || 'page'} | CMS</title></svelte:head>
<div>
<h1 class="text-3xl font-bold">Edit page</h1> <svelte:window onkeydown={(e) => showPreview && e.key === 'Escape' && (showPreview = false)} />
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
</div> <form
<div class="flex flex-wrap gap-2"> method="POST"
<button class="btn" type="button" onclick={openPreview}>Preview</button> action="?/save"
<button class="btn btn-outline" type="submit">Save draft</button> class="space-y-6"
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button> use:enhance={({ submitter }) => {
</div> saving = submitter?.getAttribute('value') === 'publish' ? 'publish' : 'save';
</div> return async ({ result, update }) => {
await update({ reset: false });
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if} saving = '';
if (result.type === 'success' || result.type === 'redirect') {
<div class="grid gap-4 md:grid-cols-2"> // Adopt what the server stored (it normalises the 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> slug = data.page.slug;
<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> title = data.page.title;
</div> savedSnapshot = serialize();
}
<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"> <input type="hidden" name="id" value={data.page.id} />
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button> <input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each blockTypes as type} <div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li> <div>
{/each} <a class="link link-hover text-sm text-base-content/60" href="/pages">← Pages</a>
</ul> <div class="flex flex-wrap items-center gap-3">
</div> <h1 class="text-3xl font-bold">Edit page</h1>
</div> <span class="badge" class:badge-success={published}>{published ? 'Published' : 'Draft'}</span>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} /> </div>
</aside> <p class="text-base-content/60">
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} /> {published ? 'This page is live — saved changes appear on the site immediately.' : 'Not visible on the site until you publish it.'}
</div> </p>
</form> </div>
<div class="flex flex-wrap items-center gap-2">
{#if showPreview} {#if dirty}<span class="badge badge-warning">Unsaved changes</span>{/if}
<div class="fixed inset-0 z-50 bg-black/60 p-4"> <button class="btn" type="button" onclick={openPreview}>Preview</button>
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl"> <button class="btn btn-outline" type="submit" name="intent" value="save" disabled={saving !== ''}>
<div class="mb-3 flex items-center justify-between gap-3"> {#if saving === 'save'}<span class="loading loading-spinner loading-sm"></span>{/if}
<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> {published ? 'Save' : 'Save draft'}
<button class="btn" onclick={() => (showPreview = false)}>Close</button> </button>
</div> {#if !published}
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe> <button class="btn btn-primary" type="submit" name="intent" value="publish" disabled={saving !== ''}>
</div> {#if saving === 'publish'}<span class="loading loading-spinner loading-sm"></span>{/if}
</div> Save & publish
{/if} </button>
{/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-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#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,25 +1,46 @@
<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';
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(() => {
}); // Apply the site's colors so the preview matches the public site. Only
</script> // here: these variable names overlap DaisyUI's theme (--color-primary,
// --color-accent), so setting them in the admin shell restyled the admin.
<svelte:head> if (data.colors) {
<title>Preview</title> const root = document.documentElement;
</svelte:head> root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
{#if blocks.length} root.style.setProperty('--color-subheading', data.colors.subheading);
<BlockRenderer {blocks} /> root.style.setProperty('--color-text', data.colors.text);
{:else} root.style.setProperty('--color-primary', data.colors.primary);
<section class="mx-auto max-w-3xl px-6 py-20 text-center"> root.style.setProperty('--color-accent', data.colors.accent);
<h1 class="text-4xl">No preview content</h1> }
<p class="mt-4 text-charcoal/65">Open preview from the page editor to view the current draft.</p>
</section> const raw = sessionStorage.getItem('cms-preview-blocks');
{/if} if (!raw) return;
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) blocks = parsed;
} catch {
error = 'The preview data could not be read. Close the preview and open it again.';
}
});
</script>
<svelte:head>
<title>Preview</title>
</svelte:head>
{#if blocks.length}
<BlockRenderer {blocks} />
{: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,24 +1,37 @@
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; status: string; notes: string } } | { payload: { item: string; start: string; end: 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.' };
const start = new Date(startValue); // The form sends a wall-clock time in the site's timezone.
if (Number.isNaN(start.getTime())) return { error: 'Invalid start time.' }; const startIso = zonedInputToIso(startValue, siteTimezone());
if (!startIso) return { error: 'Invalid start time.' };
const start = new Date(startIso);
let item: Record<string, any>; let item: Record<string, any>;
try { try {
@ -31,9 +44,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);
return { // Status is never taken from the form: it is owned by the booking flow
payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), status, notes } // (held by a basket, booked by a paid order). New slots start available.
}; return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } };
} }
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
@ -49,7 +62,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,
@ -72,16 +85,33 @@ 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 });
await locals.pb.collection('slots').create(result.payload); const created = await attempt('Could not create the slot.', () =>
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);
if ('error' in result) return fail(400, { message: result.error }); // Re-read the slot: the page may be stale, and a customer may have
await locals.pb.collection('slots').update(id, result.payload); // held or booked it since. Only notes can change while it's held.
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 }) => {
@ -89,8 +119,10 @@ 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.' });
await locals.pb.collection('slots').delete(id); if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' });
const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
if (!deleted.ok) return deleted.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

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

View file

@ -1,95 +1,97 @@
services: services:
pocketbase: pocketbase:
image: spectado/pocketbase:latest image: docker.io/spectado/pocketbase:latest
container_name: massage-pocketbase container_name: massage-pocketbase
restart: unless-stopped restart: unless-stopped
# Internal only — accessed via the caddy reverse proxy # Internal only — accessed via the caddy reverse proxy
expose: expose:
- "80" - "80"
volumes: volumes:
- pocketbase:/pb_data - pocketbase:/pb_data
# Versioned schema changes; PocketBase applies pending ones on start.
app-admin: - ./pocketbase/pb_migrations:/pb_migrations:ro,Z
build:
context: . app-admin:
dockerfile: app-admin/Dockerfile build:
container_name: massage-app-admin context: .
restart: unless-stopped dockerfile: app-admin/Dockerfile
depends_on: container_name: massage-app-admin
- pocketbase restart: unless-stopped
environment: depends_on:
PORT: 3001 - pocketbase
POCKETBASE_INTERNAL_URL: http://pocketbase:80 environment:
PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 PORT: 3001
ORIGIN: http://admin.${DOMAIN:-localhost}:8080 POCKETBASE_INTERNAL_URL: http://pocketbase:80
PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080
BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 ORIGIN: http://admin.${DOMAIN:-localhost}:8080
# Commerce (reservation & payment system) — set these in a root-level .env PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080
POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64
POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} # Commerce (reservation & payment system) — set these in a root-level .env
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
# Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
SMTP_HOST: ${SMTP_HOST:-} STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
SMTP_PORT: ${SMTP_PORT:-587} # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends
SMTP_USER: ${SMTP_USER:-} SMTP_HOST: ${SMTP_HOST:-}
SMTP_PASS: ${SMTP_PASS:-} SMTP_PORT: ${SMTP_PORT:-587}
EMAIL_FROM: ${EMAIL_FROM:-} SMTP_USER: ${SMTP_USER:-}
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} SMTP_PASS: ${SMTP_PASS:-}
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} EMAIL_FROM: ${EMAIL_FROM:-}
# Internal only — served via the caddy reverse proxy EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
expose: SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
- "3001" # Internal only — served via the caddy reverse proxy
expose:
app-public: - "3001"
build:
context: . app-public:
dockerfile: app-public/Dockerfile build:
container_name: massage-app-public context: .
restart: unless-stopped dockerfile: app-public/Dockerfile
depends_on: container_name: massage-app-public
- pocketbase restart: unless-stopped
environment: depends_on:
PORT: 3000 - pocketbase
POCKETBASE_INTERNAL_URL: http://pocketbase:80 environment:
PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 PORT: 3000
ORIGIN: http://www.${DOMAIN:-localhost}:8080 POCKETBASE_INTERNAL_URL: http://pocketbase:80
# Commerce (reservation & payment system) — set these in a root-level .env PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080
POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} ORIGIN: http://www.${DOMAIN:-localhost}:8080
POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} # Commerce (reservation & payment system) — set these in a root-level .env
STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-}
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
# Booking emails (Brevo SMTP relay) — sent from the Stripe webhook PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-}
SMTP_HOST: ${SMTP_HOST:-} STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
SMTP_PORT: ${SMTP_PORT:-587} # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook
SMTP_USER: ${SMTP_USER:-} SMTP_HOST: ${SMTP_HOST:-}
SMTP_PASS: ${SMTP_PASS:-} SMTP_PORT: ${SMTP_PORT:-587}
EMAIL_FROM: ${EMAIL_FROM:-} SMTP_USER: ${SMTP_USER:-}
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} SMTP_PASS: ${SMTP_PASS:-}
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} EMAIL_FROM: ${EMAIL_FROM:-}
# Internal only — served via the caddy reverse proxy EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
expose: SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
- "3000" # Internal only — served via the caddy reverse proxy
expose:
caddy: - "3000"
image: caddy:2-alpine
container_name: massage-caddy caddy:
restart: unless-stopped image: docker.io/library/caddy:2-alpine
ports: container_name: massage-caddy
- "8080:8080" restart: unless-stopped
environment: ports:
DOMAIN: ${DOMAIN:-localhost} - "8080:8080"
# Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 environment:
# (matches the ORIGIN vars below). Switch to "https" only if you also DOMAIN: ${DOMAIN:-localhost}
# update ORIGIN/PUBLIC_* URLs and provide a cert issuer. # Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080
CADDY_SCHEME: ${CADDY_SCHEME:-http} # (matches the ORIGIN vars below). Switch to "https" only if you also
volumes: # update ORIGIN/PUBLIC_* URLs and provide a cert issuer.
- ./Caddyfile:/etc/caddy/Caddyfile:ro,Z CADDY_SCHEME: ${CADDY_SCHEME:-http}
depends_on: volumes:
- app-admin - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
- app-public depends_on:
- pocketbase - app-admin
- app-public
volumes: - pocketbase
pocketbase:
volumes:
pocketbase:

View file

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

@ -60,9 +60,13 @@
"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": {}
}, },
{ {
@ -102,9 +106,13 @@
"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": {}
}, },
{ {
@ -162,7 +170,9 @@
"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": {}
@ -292,7 +302,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": [ "indexes": [
"CREATE INDEX `idx_events_start` ON `events` (`start`)", "CREATE INDEX `idx_events_start` ON `events` (`start`)",
@ -319,7 +331,9 @@
{ "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,
@ -343,7 +357,9 @@
{ "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`)",
@ -359,8 +375,8 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": "", "createRule": null,
"updateRule": "", "updateRule": null,
"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]+$" },
@ -368,7 +384,9 @@
{ "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`)"
@ -383,16 +401,18 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": "", "createRule": null,
"updateRule": "", "updateRule": null,
"deleteRule": "", "deleteRule": null,
"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`)",
@ -408,7 +428,7 @@
"system": false, "system": false,
"listRule": "@request.auth.id != ''", "listRule": "@request.auth.id != ''",
"viewRule": "@request.auth.id != ''", "viewRule": "@request.auth.id != ''",
"createRule": "", "createRule": null,
"updateRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''",
"deleteRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''",
"fields": [ "fields": [
@ -421,7 +441,9 @@
{ "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`)"
@ -448,7 +470,9 @@
{ "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`)"
@ -472,7 +496,9 @@
{ "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

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