diff --git a/AGENTS.md b/AGENTS.md index bb93e42..e14c23f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Stack - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). +- **PocketBase** — server pinned to **0.40.6** (`docker-compose.yml`, image `elestio/pocketbase`, digest-pinned; runs as non-root uid 100 on port 8090), REST API via the `pocketbase` SDK (v0.28). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). @@ -25,15 +25,17 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts, slots.ts) │ ├── routes/ │ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) +│ │ ├── +page.svelte # Dashboard (income + chart, hours, utilisation, customers, codes owed, what sells, needs attention); figures from $lib/server/dashboard.ts. Login lands here │ │ ├── login/ # Admin login │ │ ├── pages/ # Page CRUD + block editor │ │ ├── calendar/ # Event CRUD (menu label: Events) │ │ ├── items/ # Service/product CRUD (menu label: Services & products) +│ │ ├── passes/ # Vouchers & codes: search, void/extend, issue (menu label: Vouchers & codes) │ │ ├── slots/ # Time windows + group sessions: month calendar (?month=YYYY-MM), CRUD, bulk generate/copy/clear │ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── customers/ # Customer personal data (GDPR): search, export, correct, erase, retention settings │ │ ├── emails/ # Block-based booking email editor (live preview, test send) -│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) +│ │ ├── globals/ # Header/footer/colors/style editor (menu label: Site design) │ │ ├── backup/ # Export/import UI (calls api/export, api/import) │ │ ├── preview/ # Draft preview via sessionStorage (same-origin) │ │ └── api/ # upload, export, import, slots (Shop block times in /preview) endpoints @@ -80,7 +82,7 @@ Caddyfile # Subdomain-based routing Caddy routes by `Host` header — no path stripping: - `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app) -- `db.{$DOMAIN}:8080` → `pocketbase:80` (redirects `/` to `/_/`) +- `db.{$DOMAIN}:8080` → `pocketbase:8090` (redirects `/` to `/_/`) - `www.{$DOMAIN}:8080`, `*.{$DOMAIN}:8080` → `app-public:3000` (public app) For local dev, `DOMAIN` defaults to `localhost`, so Caddy serves `admin.localhost:8080`, `db.localhost:8080`, `www.localhost:8080`. Caddy's `.localhost` handling works without DNS or hosts-file changes. @@ -98,12 +100,14 @@ All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `o ### Block System Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `packages/shared/src/types.ts` (re-exported via `$lib/types` in each app): -`text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout` +`text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout | cards | faq | html` - **Renderers (shared)**: `packages/shared/src/blocks/Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers. - **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type - **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults - **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete +- **Settings on every block** (keys starting with `_`, edited below each block's own fields): `_background`, `_foreground` (colours) and `_anchor` (id for `#anchor` links), applied by `BackgroundWrapper.svelte`. +- **Text is edited visually**: `RichTextEditor.svelte` (Tiptap) only produces `p, h2, h3, strong, em, s, a, ul, ol, li, blockquote, br, hr` — no inline styles or layout HTML. That list is `EDITOR_TAGS` in `packages/shared/src/richText.ts`; keep it and the editor's extensions in step. A layout people keep needing becomes a block (as Cards and FAQ did), never HTML in a text block; one-offs and embeds go in an `html` block. Old text blocks holding other HTML are turned into `html` blocks (or centred text) by `upgradeLegacyBlocks()` on backup import and by migration `1793300000_text_blocks_visual_editor.js`. To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`. @@ -127,31 +131,39 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type ### PocketBase Integration - Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie - `$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); commerce: `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`, `passes` (bundle/voucher codes) - 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. +- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Field settings go at the field's top level (`"maxSize": 2000000`), never under `options`: PocketBase has ignored `options` since 0.23. Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. - **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. - **Slot availability** (window start times, group-session places, blocking by overlapping bookings incl. get-ready time) is computed only by `availability()`/`windowStartTimes()`/`checkBooking()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots?item=&minutes=&from=&to=`, `?detail=1` for the admin). Slots are `window`s (services bookable at any of their lengths) or group `session`s; bookings carry their own `start`/`minutes` on basket/order lines. Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*. -- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email` and (during checkout) `baskets`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*. +- **Customer personal data (GDPR)** lives in `orders.customerDetails`/`email`, `passes.email`/`recipientName`/`message` and (during checkout) `baskets` / `basket_lines.giftTo`/`giftMessage`. Admin access, correction, erasure (= anonymise the order, never delete it — the accounts need it) and the retention cron are in `pocketbase/pb_hooks/privacy/`; the admin `/customers` page only calls `/api/privacy/*`. A new place that stores customer details (e.g. a Google Calendar sync) must be covered by export, erase and retention too, and listed in the privacy draft (`app-admin/src/lib/admin/privacyTemplate.ts`). Don't load third-party resources on public pages (fonts are bundled; Stripe.js loads only at Pay) — each one sends visitors' IPs elsewhere and may need consent. See the README's *Personal data (GDPR)*. +- **Bundles and codes** (`passes`): what a code has left is counted from order lines and live holds by `passCredits()` in the shop hooks — never store a counter. A line a code covers has `pass` and costs 0; a basket with nothing to pay is confirmed without Stripe. Bundle parts are JSON, not relations: the `onRecordDelete` hook on `items` (`deleteBlocker`) keeps parts that bundles or codes still need from being deleted, and a bundle with an inactive part isn't sold. PocketBase reads empty numbers back as 0 and treats 0 as blank for required fields: use a flag (like `items.trackStock`) instead of an empty number, and keep fields that can be 0 not required. See the README's *Bundles and codes*. - **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only). ### 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: `font-sans` (body), `font-serif` (headings), chosen in Site design → Style (default DM Sans / Playfair Display). + - **Site design → Style** (`style` global: fonts, corners, text size, shadows, page width) becomes `--site-*` variables (`siteStyleVars` in `$shared/theme`) that the `@theme` tokens in both `app.css` files scale. So in public-site markup use the tokens — `rounded-xl`/`rounded-2xl`/`rounded-card`/`rounded-panel`, `shadow-sm`…`shadow-xl`, `max-w-3xl`/`6xl`/`7xl` — never `rounded-[2rem]` or an arbitrary `shadow-[…]`, which ignore the settings. Buttons, chips and icon buttons are `rounded-button` (a pill when Round, square when Sharp); only dots, avatars and badges stay `rounded-full`. + - Keep scrolling smooth: no `backdrop-blur` on public pages (it is redrawn on every scrolled frame; use a nearly solid background), and keep animations short. The `.reveal` / `.animate-fade-in` animations are switched off for people who ask for reduced motion and, by `scrollReveal.ts`, on devices that stutter (`plain-motion` on ``, rules in both `app.css` files). + - Fonts are bundled `@fontsource-variable/*` packages, imported in each app's `src/lib/fonts.ts` and listed in `SITE_FONTS`; a new one goes in all three places. - **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). Colours come from Site design via `$shared/theme`, rendered as a ` diff --git a/packages/shared/src/blocks/CheckoutBlock.svelte b/packages/shared/src/blocks/CheckoutBlock.svelte index 38b5ecb..8e52dab 100644 --- a/packages/shared/src/blocks/CheckoutBlock.svelte +++ b/packages/shared/src/blocks/CheckoutBlock.svelte @@ -3,7 +3,7 @@ import { browser } from '$app/environment'; import { goto } from '$app/navigation'; import { page } from '$app/state'; - import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, type BasketLine, type CheckoutBlockData } from '$shared/types'; + import { DEFAULT_NOTES_HINT, DEFAULT_PRIVACY_NOTICE, shopLinks, type BasketLine, type CheckoutBlockData } from '$shared/types'; import { getBasketContext } from '$shared/basket.svelte'; import { DEFAULT_CURRENCY, DEFAULT_TIMEZONE, formatInstant, formatPrice } from '$shared/calendar'; import { formatDuration } from '$shared/items'; @@ -15,6 +15,9 @@ const basket = getBasketContext(); // Not set in the admin preview, which has no footer data. const privacyPage = $derived(page.data.footer?.privacyPage || ''); + // On its own basket page there is no shop above, so point to the booking page. + const bookingHref = $derived(shopLinks(page.data.header).booking); + const shopAbove = $derived(page.url.pathname === bookingHref); const customer = $state({ name: '', email: '', phone: '', notes: '' }); let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle'); @@ -47,14 +50,64 @@ // Prices in the shop currency (STRIPE_CURRENCY, via layout data). const currency = $derived(page.data.currency ?? DEFAULT_CURRENCY); + /** Codes cover everything: the order is confirmed without a payment step. */ + const nothingToPay = $derived(basket.lines.length > 0 && basket.total === 0); + const payLabel = $derived( payState === 'confirming' ? 'Confirming…' : payState === 'creating' - ? 'Preparing payment…' - : `Pay ${formatPrice(basket.total, currency)}` + ? nothingToPay + ? 'Confirming…' + : 'Preparing payment…' + : nothingToPay + ? 'Confirm booking' + : `Pay ${formatPrice(basket.total, currency)}` ); + // ── Bundle/voucher code ── + let codeInput = $state(''); + let codeError = $state(''); + let codeBusy = $state(false); + + async function applyCode() { + if (!codeInput.trim() || codeBusy) return; + codeBusy = true; + codeError = ''; + try { + await basket.applyCode(codeInput.trim()); + codeInput = ''; + } catch (e) { + codeError = e instanceof Error ? e.message : 'Could not apply the code.'; + } finally { + codeBusy = false; + } + } + + async function removeCode() { + codeBusy = true; + codeError = ''; + try { + await basket.removeCode(); + } catch (e) { + codeError = e instanceof Error ? e.message : 'Could not remove the code.'; + } finally { + codeBusy = false; + } + } + + // ── Gifts (bundle lines) ── + let giftOpen = $state>({}); + + async function saveGift(line: BasketLine, giftTo: string, giftMessage: string) { + if (giftTo === (line.giftTo ?? '') && giftMessage === (line.giftMessage ?? '')) return; + try { + await basket.setGift(line.id, giftTo, giftMessage); + } catch (e) { + errorMsg = e instanceof Error ? e.message : 'Could not save the gift details.'; + } + } + const timezone = $derived(page.data.timezone ?? DEFAULT_TIMEZONE); /** "Fri 15 Jan, 10:00" in the studio's timezone. */ @@ -179,7 +232,13 @@ `Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.` ); } - const { clientSecret } = await res.json(); + const result = await res.json(); + if (result.free) { + // Paid in full with a code: the order exists, no payment step. + goto('/checkout/return?order=' + encodeURIComponent(result.orderId)); + return; + } + const { clientSecret } = result; // Starting payment holds the slots longer; show the new countdown. await basket.refresh(); @@ -296,7 +355,11 @@ {#if basket.lines.length === 0}

Your basket is empty

-

Pick a service or product above.

+ {#if shopAbove} +

Pick a service or product above.

+ {:else} + Book a session + {/if}
{:else} {#if holdLeftMs !== null && slotLineCount} @@ -317,7 +380,7 @@ {#if ending && payState !== 'confirming'} + {/if} + {/if} - - {#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1} -
- - {line.quantity} - -
- {/if} +
+ + {#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1} +
+ + {line.quantity} + +
+ {/if} -

- {formatPrice((line.itemPrice ?? 0) * line.quantity, currency)} -

+

+ {formatPrice((line.itemPrice ?? 0) * line.quantity, currency)} +

- + +
{/each} @@ -406,6 +506,50 @@ + +
+ {#if basket.pass} + {@const left = basket.pass.parts.filter((p) => p.redeemable)} +
+
+

Code {basket.pass.code} · {basket.pass.name}

+

+ {left.map((p) => `${p.left} × ${p.name} (${formatDuration(p.minutes ?? 0)})`).join(', ')} left after this basket{basket.pass.expiresAt + ? ` · valid until ${formatInstant(basket.pass.expiresAt, timezone, { day: 'numeric', month: 'long', year: 'numeric' })}` + : ''}. +

+ {#if !basket.lines.some((l) => l.passCovered)} +

Nothing in your basket matches this code — book one of the sessions above, at the same length.

+ {/if} +
+ +
+ {:else} +
{ + e.preventDefault(); + applyCode(); + }} + > + + + +
+ {/if} + {#if codeError}{/if} +
+
@@ -508,7 +652,7 @@ {#if payState === 'ready' || payState === 'confirming'}
diff --git a/packages/shared/src/blocks/FaqBlock.svelte b/packages/shared/src/blocks/FaqBlock.svelte new file mode 100644 index 0000000..d5e27bc --- /dev/null +++ b/packages/shared/src/blocks/FaqBlock.svelte @@ -0,0 +1,21 @@ + + +
+
+ {#if data.heading}

{data.heading}

{/if} + {#each data.items || [] as item, i (i)} +
+ + {item.question} + + + {@html item.answer || ''} +
+ {/each} +
+
diff --git a/packages/shared/src/blocks/HeroBlock.svelte b/packages/shared/src/blocks/HeroBlock.svelte index 68af2f6..dd1bdba 100644 --- a/packages/shared/src/blocks/HeroBlock.svelte +++ b/packages/shared/src/blocks/HeroBlock.svelte @@ -1,4 +1,7 @@ + + +
+
+ {@html data.html || ''} +
+
diff --git a/packages/shared/src/blocks/ImageTextBlock.svelte b/packages/shared/src/blocks/ImageTextBlock.svelte index bfd20b4..9b3d048 100644 --- a/packages/shared/src/blocks/ImageTextBlock.svelte +++ b/packages/shared/src/blocks/ImageTextBlock.svelte @@ -8,7 +8,7 @@
-
+
{#if data.url} {data.alt {:else} diff --git a/packages/shared/src/blocks/ShopBlock.svelte b/packages/shared/src/blocks/ShopBlock.svelte index 2971064..916f3c5 100644 --- a/packages/shared/src/blocks/ShopBlock.svelte +++ b/packages/shared/src/blocks/ShopBlock.svelte @@ -1,9 +1,9 @@ -
-
+ +
+
{@html data.content || '

Welcome

Add warm, inviting copy in the CMS.

'}
diff --git a/packages/shared/src/blocks/TimelineBlock.svelte b/packages/shared/src/blocks/TimelineBlock.svelte index 9673c9e..4d3a3a9 100644 --- a/packages/shared/src/blocks/TimelineBlock.svelte +++ b/packages/shared/src/blocks/TimelineBlock.svelte @@ -6,8 +6,9 @@ let items = $derived(data.items?.length ? data.items : [ { title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' } ]); + // Desktop only: cards alternate sides and overlap a little; on a phone they stack in one column. let widths = $derived(items.map((_: TimelineItem, i: number) => { - const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]']; + const opts = ['md:w-[78%]', 'md:w-[85%]', 'md:w-[90%]', 'md:w-[95%]', 'md:w-[98%]']; return opts[(i * 7 + 3) % opts.length]; })); @@ -19,9 +20,9 @@
{#each items as item, index} -
+
-
+

{item.title}

{item.description}

diff --git a/packages/shared/src/blocks/UpcomingCalendarBlock.svelte b/packages/shared/src/blocks/UpcomingCalendarBlock.svelte index 2749794..9f43dd7 100644 --- a/packages/shared/src/blocks/UpcomingCalendarBlock.svelte +++ b/packages/shared/src/blocks/UpcomingCalendarBlock.svelte @@ -4,6 +4,7 @@ dateKey, eventMatchesCategories, eventOverlapsDay, + eventOverlapsRange, eventRange, formatEventDateRange, getCurrentAndNextMonths, @@ -26,6 +27,12 @@ return visibleEvents.filter((event) => eventOverlapsDay(event, date)); } + // On a phone the grid only shows coloured bars; this list under it says what they are. + function eventsInMonth(days: { date: Date; inMonth: boolean }[]) { + const inMonth = days.filter((day) => day.inMonth); + return visibleEvents.filter((event) => eventOverlapsRange(event, inMonth[0].date, inMonth[inMonth.length - 1].date)); + } + function eventStyle(event: CalendarEventRecord) { return `--event-color: ${event.color || '#8a9a7b'};`; } @@ -42,10 +49,11 @@ return { showLabel: visualStart, classes: [ - visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3', - visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3', + // Continuing bars reach across the cell padding and the gap (p-1/p-2 + gap-1). + visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-2 sm:-ml-3', + visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-2 sm:-mr-3', visualStart && visualEnd ? 'mx-0' : '', - !visualStart && !visualEnd ? '-mx-3' : '' + !visualStart && !visualEnd ? '-mx-2 sm:-mx-3' : '' ].filter(Boolean).join(' ') }; } @@ -57,20 +65,20 @@
{#if visibleEvents.length === 0} -
+

No upcoming events are available for the selected categories.

{:else}
{#each months as month} -
+

{month.label}

{#each weekdays as weekday}
{weekday}
{/each}
{#each month.days as day} -
+
{day.dayNumber}
@@ -81,7 +89,7 @@ {@const segment = segmentMeta(event, day.date)} {#if href} - {segment.showLabel ? event.name : '\u00a0'} - {:else} - {segment.showLabel ? event.name : '\u00a0'} -
{/each}
+ {#if eventsInMonth(month.days).length} +
    + {#each eventsInMonth(month.days) as event} + {@const href = normalizeLink(event.link)} +
  • + +
    + {#if href} + {event.name} + {:else} + {event.name} + {/if} + · {formatEventDateRange(event)} + {#if event.description}

    {event.description}

    {/if} +
    +
  • + {/each} +
+ {/if}
{/each}
diff --git a/packages/shared/src/email/render.ts b/packages/shared/src/email/render.ts index 4a1086e..4f1dbbe 100644 --- a/packages/shared/src/email/render.ts +++ b/packages/shared/src/email/render.ts @@ -1,4 +1,5 @@ import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types'; +import { formatDuration } from '../items'; // Pure email rendering — no server or browser APIs, so the admin editor can // render its live preview client-side with exactly the code that sends. @@ -12,6 +13,18 @@ export type EmailLine = { quantity: number; start: string | null; end: string | null; + /** The code that paid for this booking. */ + passCode?: string; +}; + +/** A bundle/voucher code bought in this order. */ +export type EmailPass = { + code: string; // ABCD-2345 + name: string; + expiresAt: string; // ISO, '' = no expiry + recipientName: string; + message: string; + parts: { name: string; minutes: number | null; count: number }[]; }; export type EmailContext = { @@ -20,6 +33,8 @@ export type EmailContext = { currency: string; customer: CustomerDetails; lines: EmailLine[]; + /** Codes bought in this order — shown under the booking details. */ + passes?: EmailPass[]; business: FooterGlobal; colors: ColorsGlobal; siteUrl: string; @@ -97,6 +112,20 @@ function formatTime(iso: string, timezone: string): string { }).format(new Date(iso)); } +function formatDate(iso: string, timezone: string): string { + return new Intl.DateTimeFormat('en-GB', { timeZone: safeTimeZone(timezone), day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(iso)); +} + +/** "Valid until 25 October 2027" / "No expiry". */ +function passValidity(pass: EmailPass, timezone: string) { + return pass.expiresAt ? `Valid until ${formatDate(pass.expiresAt, timezone)}` : 'No expiry'; +} + +/** "3× Massage (1 hour)" / "1× Oil — handed over with this order". */ +function passPartLabel(part: EmailPass['parts'][number]) { + return `${part.count}× ${part.name}${part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with this order'}`; +} + /** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */ export function formatLineWhen(line: EmailLine, timezone: string): string { if (!line.start) return ''; @@ -236,6 +265,7 @@ function renderBookingDetails(block: EmailBlock, ctx: EmailContext): string {
${escapeHtml(qty + line.name)}
${when ? `
${escapeHtml(when)}
` : ''} +${line.passCode ? `
Paid with code ${escapeHtml(line.passCode)}
` : ''} ${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))} `; @@ -243,7 +273,25 @@ ${when ? `
Total paid${escapeHtml(formatMoney(ctx.total, ctx.currency))}`; const table = `${lines}${total}
`; - return boxed(sectionTitle(block.data.title ?? '', ctx) + table, ctx); + return boxed(sectionTitle(block.data.title ?? '', ctx) + table + renderPasses(ctx), ctx); +} + +/** The codes an order bought, under its booking details. */ +function renderPasses(ctx: EmailContext): string { + if (!ctx.passes?.length) return ''; + const small = `font-family:${FONT_BODY};font-size:14px;line-height:1.5;color:${ctx.colors.subheading};margin:4px 0 0;`; + const cards = ctx.passes + .map( + (pass) => `
+
${escapeHtml(pass.code)}
+
${escapeHtml(pass.name)}${pass.recipientName ? ` · for ${escapeHtml(pass.recipientName)}` : ''}
+${pass.message ? `

“${escapeHtml(pass.message).replace(/\n/g, '
')}”

` : ''} +

${pass.parts.map((part) => escapeHtml(passPartLabel(part))).join('
')}

+

${escapeHtml(passValidity(pass, ctx.timezone))}. Enter the code in the basket when booking.

+
` + ) + .join(''); + return `
Your ${ctx.passes.length === 1 ? 'code' : 'codes'}
${cards}`; } function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string { @@ -323,9 +371,20 @@ function renderBlockText(block: EmailBlock, ctx: EmailContext, values: Record { const when = formatLineWhen(line, ctx.timezone); const qty = line.quantity > 1 ? `${line.quantity}× ` : ''; - return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}`; + return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}${line.passCode ? `\n Paid with code ${line.passCode}` : ''}`; }); - return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}`; + const passes = (ctx.passes ?? []).map((pass) => + [ + `\n${pass.code} — ${pass.name}${pass.recipientName ? ` (for ${pass.recipientName})` : ''}`, + pass.message && `"${pass.message}"`, + ...pass.parts.map((part) => ` ${passPartLabel(part)}`), + ` ${passValidity(pass, ctx.timezone)}. Enter the code in the basket when booking.` + ] + .filter(Boolean) + .join('\n') + ); + const codes = passes.length ? `\n\nYOUR ${passes.length === 1 ? 'CODE' : 'CODES'}${passes.join('\n')}` : ''; + return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}${codes}`; } case 'customer_details': { const { name, email, phone, notes } = ctx.customer; diff --git a/packages/shared/src/items.ts b/packages/shared/src/items.ts index 2d1fd5c..4f8f4a6 100644 --- a/packages/shared/src/items.ts +++ b/packages/shared/src/items.ts @@ -2,7 +2,7 @@ // the Shop block and the checkout. Which duration costs what is decided // (and charged) by the shop hooks in PocketBase; this only reads and shows it. -import type { ItemDuration } from './types'; +import type { BundlePart, ItemDuration, ItemRecord, ShopSort } from './types'; /** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */ export function parseDurations(raw: unknown): ItemDuration[] { @@ -27,3 +27,59 @@ export function formatDuration(minutes: number) { export function lowestPrice(durations: ItemDuration[]) { return durations.length ? Math.min(...durations.map((d) => d.price)) : null; } + +/** A stored code `ABCD2345` → `ABCD-2345`, as shown to people (the shop hooks format it the same way). */ +export function formatCode(code: string) { + return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code; +} + +/** + * What a bundle's parts cost bought one by one (each service at the part's + * length), to show next to the bundle price — or null when a part isn't on + * sale (not in `items`, or a length the service no longer has). + */ +export function bundleListPrice(parts: BundlePart[], items: ItemRecord[]) { + let total = 0; + for (const part of parts) { + const item = items.find((candidate) => candidate.id === part.item); + if (!item || item.type === 'bundle') return null; + const unit = item.type === 'item_with_time' ? item.durations.find((d) => d.minutes === part.minutes)?.price : item.price; + if (unit == null) return null; + total += unit * part.count; + } + return Math.round(total * 100) / 100; +} + +/** The Shop block's sort choices, in menu order, with what visitors see. */ +export const SHOP_SORTS: { value: ShopSort; label: string }[] = [ + { value: 'recommended', label: 'Recommended' }, + { value: 'popular', label: 'Most popular' }, + { value: 'price_asc', label: 'Price: low to high' }, + { value: 'price_desc', label: 'Price: high to low' }, + { value: 'name', label: 'Name (A–Z)' } +]; + +const byName = (a: ItemRecord, b: ItemRecord) => a.name.localeCompare(b.name, 'en-GB', { sensitivity: 'base' }); +const byPriority = (a: ItemRecord, b: ItemRecord) => b.priority - a.priority || byName(a, b); + +/** + * `items` in the Shop block's `sort` order (a new array). Ties — and, for + * "Most popular", items that haven't sold lately — fall back to Recommended, + * so the admin's priorities still decide whatever the numbers don't. + * Services sort by their lowest price (what "from …" shows). + */ +export function sortItems(items: ItemRecord[], sort: ShopSort = 'recommended') { + const list = [...items]; + switch (sort) { + case 'popular': + return list.sort((a, b) => (a.popularRank ?? Infinity) - (b.popularRank ?? Infinity) || byPriority(a, b)); + case 'price_asc': + return list.sort((a, b) => a.price - b.price || byPriority(a, b)); + case 'price_desc': + return list.sort((a, b) => b.price - a.price || byPriority(a, b)); + case 'name': + return list.sort(byName); + default: + return list.sort(byPriority); + } +} diff --git a/packages/shared/src/pb.ts b/packages/shared/src/pb.ts index 0797bb5..c8ac7a7 100644 --- a/packages/shared/src/pb.ts +++ b/packages/shared/src/pb.ts @@ -20,3 +20,14 @@ export function createPocketBase(authCookie?: string, url = pbUrl) { export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) { return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`; } + +/** + * A small version of an uploaded image: PocketBase makes thumbnails of media + * files in the sizes listed on the field (`media.file` has 300x300, cropped + * to fill). Other URLs (and SVGs, which PocketBase doesn't resize) are + * returned as they are. + */ +export function thumbUrl(url: string, size: '300x300' | '1200x0' = '300x300') { + if (!url.includes('/api/files/') || /\.svg(\?|$)/i.test(url)) return url; + return `${url}${url.includes('?') ? '&' : '?'}thumb=${size}`; +} diff --git a/packages/shared/src/richText.ts b/packages/shared/src/richText.ts new file mode 100644 index 0000000..4a39e46 --- /dev/null +++ b/packages/shared/src/richText.ts @@ -0,0 +1,46 @@ +import type { ContentBlock } from './types'; + +// Text blocks hold the HTML the admin's visual editor (Tiptap, see +// app-admin RichTextEditor.svelte) produces: these tags, and attributes only +// on links. Anything else (layouts, inline styles, embeds) belongs in an HTML +// block. Keep this list and the editor's extensions in step, and mirror changes +// in pocketbase/pb_migrations/1793300000_text_blocks_visual_editor.js. +const EDITOR_TAGS = new Set(['p', 'h2', 'h3', 'strong', 'b', 'em', 'i', 's', 'a', 'ul', 'ol', 'li', 'blockquote', 'br', 'hr']); +const LINK_ATTRS = new Set(['href', 'target', 'rel']); + +/** Whether `html` only uses what the visual editor can produce (so editing it loses nothing). */ +export function isEditorHtml(html: string): boolean { + for (const [, name, attrs] of html.matchAll(/<\/?([a-zA-Z][a-zA-Z0-9]*)([^>]*)>/g)) { + const tag = name.toLowerCase(); + if (!EDITOR_TAGS.has(tag)) return false; + for (const [, attr] of attrs.matchAll(/([a-zA-Z-]+)\s*=/g)) { + if (tag !== 'a' || !LINK_ATTRS.has(attr.toLowerCase())) return false; + } + } + return true; +} + +const CENTRED = /\s+style="text-align:\s*center;?"/gi; +const BLOCK_START = /<(p|h2|h3|ul|ol|blockquote)\b/gi; + +/** + * Text blocks written before the visual editor (raw HTML) become what they can + * be without losing anything: clean text (with `align: 'center'` when every + * paragraph and heading was centred), or else an HTML block that renders them + * exactly as before. Other blocks are returned unchanged. + */ +export function upgradeLegacyBlock(block: ContentBlock): ContentBlock { + if (block.type !== 'text') return block; + const { content = '', ...rest } = block.data; + if (isEditorHtml(content)) return block; + const centred = (content.match(CENTRED) || []).length; + const stripped = content.replace(CENTRED, ''); + if (centred && centred === (stripped.match(BLOCK_START) || []).length && isEditorHtml(stripped)) { + return { ...block, data: { ...rest, content: stripped, align: 'center' } }; + } + return { ...block, type: 'html', data: { ...rest, html: content } }; +} + +export function upgradeLegacyBlocks(blocks: ContentBlock[]): ContentBlock[] { + return Array.isArray(blocks) ? blocks.map(upgradeLegacyBlock) : blocks; +} diff --git a/packages/shared/src/scrollReveal.ts b/packages/shared/src/scrollReveal.ts index 016ba88..9d35606 100644 --- a/packages/shared/src/scrollReveal.ts +++ b/packages/shared/src/scrollReveal.ts @@ -2,9 +2,88 @@ * Scroll reveal Svelte action — applies a CSS class when the element enters the viewport. * Usage:
...
* The `reveal` class is hidden initially; `reveal-visible` is added on intersection. + * + * On a device that can't keep up, the animations are switched off for the rest + * of the visit (`plain-motion` on , see app.css): one with very few cores + * or little memory straight away, any other once scrolling is seen to stutter. */ +const PLAIN = 'plain-motion'; +const STORAGE_KEY = 'plain-motion'; +/** Scrolled frames to look at before deciding, and how many may run late. */ +const SAMPLE_FRAMES = 120; +const LATE_SHARE = 0.1; +/** A frame this long missed at least one refresh of a 60 Hz screen. */ +const LATE_MS = 25; + +let watching = false; + +function usePlainMotion() { + document.documentElement.classList.add(PLAIN); + try { + sessionStorage.setItem(STORAGE_KEY, '1'); + } catch { + // Storage blocked: decided again on the next page. + } +} + +function weakHardware() { + const memory = (navigator as Navigator & { deviceMemory?: number }).deviceMemory; + return (navigator.hardwareConcurrency || 8) <= 2 || (memory !== undefined && memory <= 2); +} + +/** Times frames while the page scrolls; too many late ones switch the animations off. */ +function watchScrolling() { + if (watching || typeof window === 'undefined') return; + watching = true; + + let stored = false; + try { + stored = sessionStorage.getItem(STORAGE_KEY) === '1'; + } catch { + // Storage blocked: measure instead. + } + if (stored || weakHardware()) { + usePlainMotion(); + return; + } + + let frames = 0; + let late = 0; + let last = 0; + let lastScroll = 0; + let running = false; + + function tick(now: number) { + if (last) { + frames++; + if (now - last > LATE_MS) late++; + } + last = now; + if (frames >= SAMPLE_FRAMES) { + window.removeEventListener('scroll', onScroll); + if (late / frames > LATE_SHARE) usePlainMotion(); + return; + } + // Only frames while scrolling count; stop shortly after it ends. + if (now - lastScroll < 300) requestAnimationFrame(tick); + else running = false; + } + + function onScroll() { + lastScroll = performance.now(); + if (running) return; + running = true; + last = 0; + requestAnimationFrame(tick); + } + + window.addEventListener('scroll', onScroll, { passive: true }); +} + export function scrollReveal(node: HTMLElement, delay: number = 0) { + watchScrolling(); + const observer = new IntersectionObserver( (entries) => { for (const entry of entries) { diff --git a/packages/shared/src/server/email/index.ts b/packages/shared/src/server/email/index.ts index 26c284e..e1b03f2 100644 --- a/packages/shared/src/server/email/index.ts +++ b/packages/shared/src/server/email/index.ts @@ -11,7 +11,8 @@ import { type FooterGlobal } from '../../types'; import { normalizeEmailTemplate } from '../../email/defaults'; -import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine } from '../../email/render'; +import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine, type EmailPass } from '../../email/render'; +import { formatCode } from '../../items'; import { buildIcs } from './ics'; import { sendEmail, type SendResult } from './transport'; @@ -113,8 +114,10 @@ function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSetting */ export type OrderEmailData = { order: Record; - /** order_lines with `expand.slot` and `expand.item` */ + /** order_lines with `expand.slot`, `expand.item` and `expand.pass` */ lines: Record[]; + /** passes this order bought (codes) */ + passes?: Record[]; templates: Partial | null>>; footer: Partial | null; colors: Partial | null; @@ -132,15 +135,16 @@ export async function loadOrderEmailData(pb: PocketBase, orderId: string): Promi .collection('email_templates') .getFirstListItem(pb.filter('key = {:key}', { key })) .catch(() => null); - const [order, lines, customer_confirmation, client_alert, footer, colors] = await Promise.all([ + const [order, lines, passes, customer_confirmation, client_alert, footer, colors] = await Promise.all([ pb.collection('orders').getOne(orderId), - pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' }), + pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item,pass', sort: 'start' }), + pb.collection('passes').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), sort: 'created' }), template('customer_confirmation'), template('client_alert'), globalData('footer'), globalData('colors') ]); - return { order, lines, templates: { customer_confirmation, client_alert }, footer, colors }; + return { order, lines, passes, templates: { customer_confirmation, client_alert }, footer, colors }; } function orderEmailContext(data: OrderEmailData, settings: EmailSettings) { @@ -159,10 +163,24 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) { price: Number(line.price) || 0, quantity: Number(line.quantity) || 1, start, - end + end, + passCode: line.expand?.pass?.code ? formatCode(String(line.expand.pass.code)) : undefined }; }); + const passes: EmailPass[] = (data.passes ?? []).map((pass) => ({ + code: formatCode(String(pass.code || '')), + name: String(pass.name || ''), + expiresAt: pass.expiresAt ? new Date(String(pass.expiresAt).replace(' ', 'T')).toISOString() : '', + recipientName: String(pass.recipientName || ''), + message: String(pass.message || ''), + parts: (Array.isArray(pass.parts) ? pass.parts : []).map((part: Record) => ({ + name: String(part.name || ''), + minutes: part.minutes ? Number(part.minutes) : null, + count: Number(part.count) || 0 + })) + })); + const details = (order.customerDetails || {}) as Partial; const customer: CustomerDetails = { name: String(details.name || ''), @@ -176,6 +194,7 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) { total: Number(order.total) || 0, customer, lines, + passes, ...settings }; return { ctx, lineIds: lineRecords.map((line) => line.id) }; diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts index 0fbfe2a..cfcfe45 100644 --- a/packages/shared/src/server/shop.ts +++ b/packages/shared/src/server/shop.ts @@ -1,12 +1,19 @@ import type PocketBase from 'pocketbase'; import { getFileUrl } from '../pb'; -import { parseDurations } from '../items'; -import type { BookableTime, ItemRecord } from '../types'; +import { bundleListPrice, parseDurations } from '../items'; +import type { BookableTime, BundlePart, ItemRecord, ItemType } from '../types'; + +/** A bundle's `bundleParts` field (JSON) → valid parts. */ +export function parseBundleParts(raw: unknown): BundlePart[] { + return (Array.isArray(raw) ? raw : []) + .map((p) => ({ item: String(p?.item || ''), minutes: p?.minutes ? Math.floor(Number(p.minutes)) : null, count: Math.floor(Number(p?.count)) || 0 })) + .filter((p) => p.item && p.count > 0); +} /** An `items` record (with `expand.image`) → `ItemRecord`. */ export function mapItemRecord(record: Record): ItemRecord { const media = record.expand?.image; - const type = record.type === 'item_with_time' ? 'item_with_time' : 'item'; + const type: ItemType = record.type === 'item_with_time' || record.type === 'bundle' ? record.type : 'item'; return { id: record.id, name: String(record.name || ''), @@ -15,11 +22,18 @@ export function mapItemRecord(record: Record): ItemRecord { image: String(record.image || ''), imageUrl: media ? getFileUrl('media', media.id, media.file) : '', type, - stock: record.stock ?? null, + // null = unlimited: PocketBase reads an empty number back as 0, so `trackStock` says whether it counts. + stock: type === 'item' && record.trackStock ? Number(record.stock) || 0 : null, durations: type === 'item_with_time' ? parseDurations(record.durations) : [], - bufferMinutes: record.bufferMinutes ?? null, - capacity: record.capacity ?? null, - active: record.active !== false + bundleParts: type === 'bundle' ? parseBundleParts(record.bundleParts) : [], + validMonths: type === 'bundle' ? Number(record.validMonths) || null : null, + // PocketBase reads an empty number back as 0, never null: 0 means "not set" for both + // (and a 0 in the admin form would fail capacity's min of 1, blocking every save). + bufferMinutes: Number(record.bufferMinutes) || null, + capacity: Number(record.capacity) || null, + active: record.active !== false, + priority: Number(record.priority) || 0, + popularRank: null }; } @@ -31,8 +45,19 @@ export function mapItemRecord(record: Record): ItemRecord { * (see `loadBookableTimes`). Errors propagate. */ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> { - const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }); - return { items: records.map(mapItemRecord) }; + const [records, popular] = await Promise.all([ + pb.collection('items').getFullList({ filter: 'active = true', sort: '-priority,name', expand: 'image' }), + // Only orders the "Most popular" sort; without it the shop still works. + pb.send<{ items: string[] }>('/api/shop/popular', { requestKey: null }).catch((e) => { + console.warn('Best sellers unavailable ("Most popular" falls back to Recommended):', e instanceof Error ? e.message : e); + return { items: [] as string[] }; + }) + ]); + const rank = new Map(popular.items.map((id, i) => [id, i])); + const items = records.map((record) => ({ ...mapItemRecord(record), popularRank: rank.get(record.id) ?? null })); + // A bundle with a part that isn't on sale (inactive, deleted, or a length + // the service dropped) can't be bought — the shop hook refuses it too. + return { items: items.filter((item) => item.type !== 'bundle' || bundleListPrice(item.bundleParts, items) !== null) }; } export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string }; diff --git a/packages/shared/src/theme.ts b/packages/shared/src/theme.ts index 86708e5..5375ce8 100644 --- a/packages/shared/src/theme.ts +++ b/packages/shared/src/theme.ts @@ -1,4 +1,4 @@ -import { defaultColors, type ColorsGlobal } from './types'; +import { defaultColors, defaultStyle, type ColorsGlobal, type StyleGlobal } from './types'; // Site colours (Site design → Colors) as CSS variables, rendered server-side // into a