diff --git a/.env.example b/.env.example index 65b8615..9211223 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,23 @@ STRIPE_CURRENCY=eur POCKETBASE_ADMIN_EMAIL=admin@example.com POCKETBASE_ADMIN_PASSWORD=changeme +# Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP). +# Leave SMTP_HOST empty in development: emails are then written to the +# app logs instead of being sent. +# Brevo: smtp-relay.brevo.com +SMTP_HOST= +# 587 (STARTTLS); use 2525 if your network blocks 587, or 465 for implicit TLS +SMTP_PORT=587 +# The SMTP login Brevo shows (xxxx@smtp-brevo.com), NOT your account email +SMTP_USER= +# The SMTP key generated in Brevo (not your account password) +SMTP_PASS= +# Must be a sender on a domain authenticated in Brevo +EMAIL_FROM=bookings@example.com +EMAIL_FROM_NAME=Eva Shafik +# Timezone used for booking times in emails (IANA name) +SITE_TIMEZONE=Europe/Oslo + # Caddy scheme for the reverse proxy on port 8080. # http (default) — plain HTTP; matches the ORIGIN vars in docker-compose.yml # https — HTTPS on :8080 (self-signed unless you add a cert issuer; diff --git a/.gitignore b/.gitignore index c79fcd9..e1b48b4 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ Thumbs.db # Vite vite.config.js.timestamp-* vite.config.ts.timestamp-* + +# Local project notes +status.md diff --git a/AGENTS.md b/AGENTS.md index 5858e05..d34dda3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,155 +1,167 @@ -# Massage Studio Website CMS — Agent Guidelines - -## Stack - -- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. -- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. -- **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). - -## Project Structure - -``` -packages/shared/src/ # Shared code (types, calendar utils, blocks, pb, basket, stripe) -app-admin/ # SvelteKit admin app (serves admin.) -├── src/ -│ ├── lib/ -│ │ ├── admin/ # Admin UI components (BlockList, editors) -│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) -│ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia -│ │ ├── types.ts # Re-exports from $shared -│ │ ├── calendar.ts # Re-exports from $shared -│ │ ├── scrollReveal.ts # Re-exports from $shared -│ │ ├── stripe-client.ts # Re-exports from $shared -│ │ ├── basket.svelte.ts # Re-exports from $shared -│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket) -│ ├── routes/ -│ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout) -│ │ ├── login/ # Admin login -│ │ ├── pages/ # Page CRUD + block editor -│ │ ├── calendar/ # Event CRUD -│ │ ├── items/ # Service/product CRUD -│ │ ├── slots/ # Bookable time slot CRUD -│ │ ├── orders/ # Read-only order list -│ │ ├── globals/ # Header/footer/colors editor -│ │ ├── preview/ # Draft preview via sessionStorage (same-origin) -│ │ └── api/ # upload, export, import endpoints -│ ├── hooks.server.ts # Auth guard — all routes except /login -│ └── app.css # Tailwind + DaisyUI + custom theme -├── static/ # Static assets -├── build/ # Production build output -├── svelte.config.js # Adapter-node, runes mode forced, $shared alias -├── vite.config.ts # Tailwind v4 + SvelteKit plugins -└── package.json -app-public/ # SvelteKit public app (serves *.) -├── src/ -│ ├── lib/ -│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) -│ │ ├── components/ # Header.svelte, Footer.svelte -│ │ ├── pb.ts # Re-exports from $shared/pb -│ │ ├── types.ts # Re-exports from $shared -│ │ ├── calendar.ts # Re-exports from $shared -│ │ ├── scrollReveal.ts # Re-exports from $shared -│ │ ├── stripe-client.ts # Re-exports from $shared -│ │ ├── basket.svelte.ts # Re-exports from $shared -│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket); stripe.server.ts is public-only -│ ├── routes/ -│ │ ├── +layout.svelte # Root layout (always renders Header/Footer) -│ │ ├── +page.svelte # Home page (slug=home) -│ │ ├── [slug]/ # Dynamic CMS pages -│ │ ├── api/ # basket, checkout, webhooks endpoints -│ │ └── checkout/return/ # Stripe return URL -│ ├── hooks.server.ts # Creates PB client in locals (no auth guard) -│ └── app.css # Tailwind + DaisyUI + custom theme -├── static/ # Static assets -├── build/ # Production build output -├── svelte.config.js # Adapter-node, runes mode forced, $shared alias -├── vite.config.ts # Tailwind v4 + SvelteKit plugins -└── package.json -pocketbase/pb_data/ # PocketBase data (volume-mounted) -docker-compose.yml # app-admin + app-public + pocketbase + caddy services -Caddyfile # Subdomain-based routing -``` - -## Subdomain Routing - -Caddy routes by `Host` header — no path stripping: - -- `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app) -- `db.{$DOMAIN}:8080` → `pocketbase:80` (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. - -## Key Conventions - -### Svelte 5 Runes Mode -All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use: -- `$props()` for component props -- `$state()` for reactive local state -- `$derived()` for computed values -- `$effect()` / `onMount` for side effects -- `{@render children()}` for slots -- `onclick={handler}` (not `on:click`) - -### 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` - -- **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 - -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`. - -### Shared Code -- `packages/shared/src/types.ts` — all type definitions -- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) -- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` -- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work - -### 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) -- Server load functions use `locals.pb.collection('pages').getFirstListItem()` - -### Styling -- **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.) -- **Prose**: `.prose-wellness` class for rich text content styling - -### 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). -- **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` -- `[slug]/+page.server.ts` fetches by dynamic slug - -## Build & Dev Commands - -```sh -# Full stack (single entry point on port 8080) — the only supported way to run/develop -# Source changes require rebuilding; the container runs `node build`, not a dev server. -DOMAIN=localhost docker compose up --build -# Admin app: http://admin.localhost:8080 -# Public app: http://www.localhost:8080 -# PocketBase: http://db.localhost:8080/_/ - -# Type checking (can run on the host with node_modules present) -cd app-admin && npm run check -cd app-public && npm run check - -# Production build only (run by each app's Dockerfile) -cd app-admin && npm run build -cd app-public && npm run build -``` - -## Environment - -- `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`. -- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`http://db.${DOMAIN}:8080`). Set in `docker-compose.yml`. -- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`. -- `ORIGIN` — SvelteKit origin for SSR. Differs per app: `http://admin.${DOMAIN}:8080` (admin), `http://www.${DOMAIN}:8080` (public). -- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`http://www.${DOMAIN}:8080`). -- Stripe + PocketBase admin secrets are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. +# Massage Studio Website CMS — Agent Guidelines + +## Stack + +- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. +- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. +- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. +- **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). + +## Project Structure + +``` +packages/shared/src/ # Shared code (types, calendar utils, blocks, pb, basket, stripe) +app-admin/ # SvelteKit admin app (serves admin.) +├── src/ +│ ├── lib/ +│ │ ├── admin/ # Admin UI components (BlockList, editors) +│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) +│ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia +│ │ ├── types.ts # Re-exports from $shared +│ │ ├── calendar.ts # Re-exports from $shared +│ │ ├── scrollReveal.ts # Re-exports from $shared +│ │ ├── stripe-client.ts # Re-exports from $shared +│ │ ├── basket.svelte.ts # Re-exports from $shared +│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket) +│ ├── routes/ +│ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout) +│ │ ├── login/ # Admin login +│ │ ├── pages/ # Page CRUD + block editor +│ │ ├── calendar/ # Event CRUD +│ │ ├── items/ # Service/product CRUD +│ │ ├── slots/ # Bookable time slot CRUD +│ │ ├── orders/ # Order list + booking-email status/resend +│ │ ├── emails/ # Block-based booking email editor (live preview, test send) +│ │ ├── globals/ # Header/footer/colors editor +│ │ ├── preview/ # Draft preview via sessionStorage (same-origin) +│ │ └── api/ # upload, export, import endpoints +│ ├── hooks.server.ts # Auth guard — all routes except /login +│ └── app.css # Tailwind + DaisyUI + custom theme +├── static/ # Static assets +├── build/ # Production build output +├── svelte.config.js # Adapter-node, runes mode forced, $shared alias +├── vite.config.ts # Tailwind v4 + SvelteKit plugins +└── package.json +app-public/ # SvelteKit public app (serves *.) +├── src/ +│ ├── lib/ +│ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) +│ │ ├── components/ # Header.svelte, Footer.svelte +│ │ ├── pb.ts # Re-exports from $shared/pb +│ │ ├── types.ts # Re-exports from $shared +│ │ ├── calendar.ts # Re-exports from $shared +│ │ ├── scrollReveal.ts # Re-exports from $shared +│ │ ├── stripe-client.ts # Re-exports from $shared +│ │ ├── basket.svelte.ts # Re-exports from $shared +│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket); stripe.server.ts is public-only +│ ├── routes/ +│ │ ├── +layout.svelte # Root layout (always renders Header/Footer) +│ │ ├── +page.svelte # Home page (slug=home) +│ │ ├── [slug]/ # Dynamic CMS pages +│ │ ├── api/ # basket, checkout, webhooks endpoints +│ │ └── checkout/return/ # Stripe return URL +│ ├── hooks.server.ts # Creates PB client in locals (no auth guard) +│ └── app.css # Tailwind + DaisyUI + custom theme +├── static/ # Static assets +├── build/ # Production build output +├── svelte.config.js # Adapter-node, runes mode forced, $shared alias +├── vite.config.ts # Tailwind v4 + SvelteKit plugins +└── package.json +pocketbase/pb_data/ # PocketBase data (volume-mounted) +docker-compose.yml # app-admin + app-public + pocketbase + caddy services +Caddyfile # Subdomain-based routing +``` + +## Subdomain Routing + +Caddy routes by `Host` header — no path stripping: + +- `admin.{$DOMAIN}:8080` → `app-admin:3001` (admin app) +- `db.{$DOMAIN}:8080` → `pocketbase:80` (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. + +## Key Conventions + +### Svelte 5 Runes Mode +All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `on:click`. Use: +- `$props()` for component props +- `$state()` for reactive local state +- `$derived()` for computed values +- `$effect()` / `onMount` for side effects +- `{@render children()}` for slots +- `onclick={handler}` (not `on:click`) + +### 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` + +- **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 + +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`. + +### Booking Emails +Email templates use a separate `EmailBlock[]` / `EmailBlockType` (`text | image | button | spacer | divider | booking_details | customer_details | contact_info`) because email clients need table layouts with inline styles — page block renderers can't be reused. + +- **Rendering (pure, shared)**: `packages/shared/src/email/render.ts` — `renderEmail(template, ctx)` returns `{ subject, html, text }`. Used by the admin live preview (client-side) and by sending, so they always match. Defaults for each template key live in `email/defaults.ts`. +- **Sending (server)**: `packages/shared/src/server/email/` — nodemailer SMTP transport (Brevo), `.ics` builder, `sendOrderEmails(pb, orderId, kinds?)` (never throws; records status on the order) and `sendTestEmail`. Called from the Stripe webhook and the admin `/orders` resend action. +- **Admin**: `/emails/[key]` editor, `app-admin/src/lib/admin/editors/EmailBlockEditor.svelte`, `app-admin/src/lib/admin/emailBlockDefaults.ts`. + +To add an email block type: add to `EmailBlockType` in `packages/shared/src/types.ts`, add HTML + text cases in `render.ts`, an editor case in `EmailBlockEditor.svelte`, and a label/default in `emailBlockDefaults.ts`. + +### Shared Code +- `packages/shared/src/types.ts` — all type definitions +- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block) +- Each app's `svelte.config.js` declares `kit.alias.$shared → '../packages/shared/src'` +- Each app's `src/lib/types.ts` and `src/lib/calendar.ts` re-export from `$shared` so existing `$lib/types` and `$lib/calendar` imports work + +### 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) +- Server load functions use `locals.pb.collection('pages').getFirstListItem()` + +### Styling +- **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.) +- **Prose**: `.prose-wellness` class for rich text content styling + +### 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). +- **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` +- `[slug]/+page.server.ts` fetches by dynamic slug + +## Build & Dev Commands + +```sh +# Full stack (single entry point on port 8080) — the only supported way to run/develop +# Source changes require rebuilding; the container runs `node build`, not a dev server. +DOMAIN=localhost docker compose up --build +# Admin app: http://admin.localhost:8080 +# Public app: http://www.localhost:8080 +# PocketBase: http://db.localhost:8080/_/ + +# Type checking (can run on the host with node_modules present) +cd app-admin && npm run check +cd app-public && npm run check + +# Production build only (run by each app's Dockerfile) +cd app-admin && npm run build +cd app-public && npm run build +``` + +## Environment + +- `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`. +- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`http://db.${DOMAIN}:8080`). Set in `docker-compose.yml`. +- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`. +- `ORIGIN` — SvelteKit origin for SSR. Differs per app: `http://admin.${DOMAIN}:8080` (admin), `http://www.${DOMAIN}:8080` (public). +- `PUBLIC_SITE_URL` — public site URL used by the admin app for cross-subdomain preview links (`http://www.${DOMAIN}:8080`). +- `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASS`, `EMAIL_FROM`, `EMAIL_FROM_NAME` — Brevo SMTP relay for booking emails (both apps). Empty `SMTP_HOST` = log emails instead of sending. +- `SITE_TIMEZONE` — IANA timezone for booking times in emails (default `Europe/Oslo`). +- Stripe + PocketBase admin secrets are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`. diff --git a/README.md b/README.md index 0b2dc14..103a542 100644 --- a/README.md +++ b/README.md @@ -1,153 +1,176 @@ -# Massage Studio Website CMS - -A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components. - -## Stack - -- SvelteKit + SSR (two apps: admin and public) -- PocketBase REST API via the `pocketbase` SDK -- Tailwind CSS v4 + DaisyUI -- Docker Compose with four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy) - -## Architecture - -The project is split into two independent SvelteKit apps, each serving its own subdomain: - -- **`app-admin`** — serves `admin.` (admin UI, page editor, CRUD) -- **`app-public`** — serves `*.` (public CMS pages, shop, checkout) -- **PocketBase** — serves `db.` (auth, DB, image storage) - -Shared types and calendar utilities live in `packages/shared/` and are imported via the `$shared` alias declared in each app's `svelte.config.js`. - -## Development - -The project runs exclusively through Docker Compose. There is no bare host dev mode. - -1. Copy the env file and fill in the secrets: - ```sh - cp .env.example .env - ``` -2. Build and start the full stack: - ```sh - DOMAIN=localhost docker compose up --build - ``` -3. Visit: - - Admin app: `http://admin.localhost:8080` - - Public app: `http://www.localhost:8080` - - PocketBase admin: `http://db.localhost:8080/_/` - -Caddy's `.localhost` handling works without DNS or hosts-file changes. Source changes require rebuilding (`docker compose up --build`); the containers run the production build (`node build`), not a dev server. - -## Docker Compose - -Run the full stack: - -```sh -DOMAIN=localhost docker compose up --build -``` - -If dependency installation is slow on the first build, enable BuildKit explicitly: - -```sh -DOCKER_BUILDKIT=1 docker compose build --progress=plain app-admin app-public -docker compose up -``` - -Subsequent builds reuse the npm cache declared in each app's `Dockerfile`. - -- **Admin app**: `http://admin.localhost:8080` → `app-admin:3001` -- **Public app**: `http://www.localhost:8080` → `app-public:3000` -- **PocketBase admin UI**: `http://db.localhost:8080/_/` (redirects `/` to `/_/`) -- **PocketBase REST API**: `http://db.localhost:8080/api/` - -The app containers use two PocketBase URLs: - -- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app containers when using the included `spectado/pocketbase` image. -- `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain. - -## PocketBase setup - -1. Open `http://db.localhost:8080/_/`. -2. Create the first PocketBase admin user when prompted. -3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below. -4. Create starter records: - - `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. - - `globals`: key `header`, data matching the header JSON in the project prompt. - - `globals`: key `footer`, data matching the footer JSON in the project prompt. - -If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. - -### Manual collection fields fallback - -If schema import fails because of a PocketBase version mismatch, create these collections manually: - -- `pages` - - `slug`: text, required, unique - - `title`: text, required - - `blocks`: json - - `published`: bool -- `globals` - - `key`: text, required, unique - - `data`: json -- `media` - - `file`: file, required, max select `1`, image mime types - - `alt`: text - -Commerce collections (see the Stripe section above for context): - -- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `active` bool -- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text -- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text -- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot` -- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text -- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot) - -> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Relation and select fields carry their config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`) at the field top level, not nested under `options`. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass. - -## Authentication - -Admin routes live in the `app-admin` app. Login accepts either: - -- a PocketBase admin account, or -- a record from a `users` auth collection if you create one. - -All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. - -## CMS routes (admin app) - -- `/login` — sign in -- `/pages` — list/create pages -- `/pages/[slug]` — block editor with draft preview -- `/calendar` — events shown by Upcoming Calendar blocks -- `/items` — services and products shown in Shop blocks -- `/slots` — manually created bookable time slots for services -- `/orders` — read-only list of confirmed bookings and purchases -- `/globals` — header/footer/colors editor - -## Reservations & payments (Stripe) - -The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client). - -Setup: - -1. Add the Stripe + PocketBase-admin vars from `.env.example` to `.env` at the project root. -2. `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are the credentials of the PocketBase superuser you created — the basket/checkout/webhook APIs use a server-side admin client so collection rules can stay admin-only. -3. For local webhook testing, forward Stripe events with the CLI: - ```sh - stripe listen --forward-to www.localhost:8080/api/webhooks/stripe - ``` - Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`. -4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). The `basket_lines.slot` partial unique index guarantees two visitors can't hold the same slot. -5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it. - -## Public routes (public app) - -- `/` renders `pages.slug = "home"` -- `/[slug]` renders any other published page -- Unpublished pages return `404` - -## Notes - -- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON. -- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe (same-origin on the admin subdomain). -- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired. +# Massage Studio Website CMS + +A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase provides auth, database records, and image storage. The public site is warm and minimal; the admin UI uses DaisyUI components. + +## Stack + +- SvelteKit + SSR (two apps: admin and public) +- PocketBase REST API via the `pocketbase` SDK +- Tailwind CSS v4 + DaisyUI +- Docker Compose with four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy) + +## Architecture + +The project is split into two independent SvelteKit apps, each serving its own subdomain: + +- **`app-admin`** — serves `admin.` (admin UI, page editor, CRUD) +- **`app-public`** — serves `*.` (public CMS pages, shop, checkout) +- **PocketBase** — serves `db.` (auth, DB, image storage) + +Shared types and calendar utilities live in `packages/shared/` and are imported via the `$shared` alias declared in each app's `svelte.config.js`. + +## Development + +The project runs exclusively through Docker Compose. There is no bare host dev mode. + +1. Copy the env file and fill in the secrets: + ```sh + cp .env.example .env + ``` +2. Build and start the full stack: + ```sh + DOMAIN=localhost docker compose up --build + ``` +3. Visit: + - Admin app: `http://admin.localhost:8080` + - Public app: `http://www.localhost:8080` + - PocketBase admin: `http://db.localhost:8080/_/` + +Caddy's `.localhost` handling works without DNS or hosts-file changes. Source changes require rebuilding (`docker compose up --build`); the containers run the production build (`node build`), not a dev server. + +## Docker Compose + +Run the full stack: + +```sh +DOMAIN=localhost docker compose up --build +``` + +If dependency installation is slow on the first build, enable BuildKit explicitly: + +```sh +DOCKER_BUILDKIT=1 docker compose build --progress=plain app-admin app-public +docker compose up +``` + +Subsequent builds reuse the npm cache declared in each app's `Dockerfile`. + +- **Admin app**: `http://admin.localhost:8080` → `app-admin:3001` +- **Public app**: `http://www.localhost:8080` → `app-public:3000` +- **PocketBase admin UI**: `http://db.localhost:8080/_/` (redirects `/` to `/_/`) +- **PocketBase REST API**: `http://db.localhost:8080/api/` + +The app containers use two PocketBase URLs: + +- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app containers when using the included `spectado/pocketbase` image. +- `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain. + +## PocketBase setup + +1. Open `http://db.localhost:8080/_/`. +2. Create the first PocketBase admin user when prompted. +3. Import `pb_schema.json` from the PocketBase admin UI collection settings/import flow. This file uses the newer PocketBase `fields` schema format; if PocketBase still reports `Invalid collections configuration`, create the three collections manually using the fields below. +4. Create starter records: + - `pages`: slug `home`, title `Home`, `published: true`, and a blocks JSON array. + - `globals`: key `header`, data matching the header JSON in the project prompt. + - `globals`: key `footer`, data matching the footer JSON in the project prompt. + +If the `globals` records do not exist, the app falls back to safe defaults and the admin globals page will create them. + +### Manual collection fields fallback + +If schema import fails because of a PocketBase version mismatch, create these collections manually: + +- `pages` + - `slug`: text, required, unique + - `title`: text, required + - `blocks`: json + - `published`: bool +- `globals` + - `key`: text, required, unique + - `data`: json +- `media` + - `file`: file, required, max select `1`, image mime types + - `alt`: text + +Commerce collections (see the Stripe section above for context): + +- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `active` bool +- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text +- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text +- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot` +- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text +- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot) +- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool + +> **Schema format note:** `pb_schema.json` targets PocketBase 0.23+ using the `fields` array (not the legacy `schema` array). Relation and select fields carry their config (`collectionId`, `cascadeDelete`, `maxSelect`, `values`) at the field top level, not nested under `options`. Importing the whole file via the PocketBase admin UI or `PUT /api/collections/import` creates or updates all collections in one pass. + +## Authentication + +Admin routes live in the `app-admin` app. Login accepts either: + +- a PocketBase admin account, or +- a record from a `users` auth collection if you create one. + +All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`. + +## CMS routes (admin app) + +- `/login` — sign in +- `/pages` — list/create pages +- `/pages/[slug]` — block editor with draft preview +- `/calendar` — events shown by Upcoming Calendar blocks +- `/items` — services and products shown in Shop blocks +- `/slots` — manually created bookable time slots for services +- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons +- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send) +- `/globals` — header/footer/colors editor + +## Reservations & payments (Stripe) + +The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client). + +Setup: + +1. Add the Stripe + PocketBase-admin vars from `.env.example` to `.env` at the project root. +2. `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are the credentials of the PocketBase superuser you created — the basket/checkout/webhook APIs use a server-side admin client so collection rules can stay admin-only. +3. For local webhook testing, forward Stripe events with the CLI: + ```sh + stripe listen --forward-to www.localhost:8080/api/webhooks/stripe + ``` + Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`. +4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). The `basket_lines.slot` partial unique index guarantees two visitors can't hold the same slot. +5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it. + +## Booking emails (Brevo) + +After the Stripe webhook creates an order it sends two emails through an SMTP relay (Brevo) with `nodemailer`: + +- **Booking confirmation** to the customer, with a `booking.ics` calendar attachment for booked time slots. Reply-To is the footer email. +- **New booking alert** to the studio (the template's recipients, or the footer email). Reply-To is the customer. + +Both are edited in the admin under **Emails** using email blocks (text, image, button, spacer, divider, and auto-filled booking details / customer details / contact info). Text and subjects support placeholders like `{{customer_first_name}}` and `{{booking_date}}`. Until a template is saved, a built-in default is used. Rendering lives in `packages/shared/src/email/` (pure, used by both the admin live preview and sending); sending lives in `packages/shared/src/server/email/`. + +The result is recorded on the order (`customerEmailSentAt`, `clientEmailSentAt`, `emailError`); a failed email never fails the webhook and can be resent from `/orders`. + +Setup: + +1. Import the updated `pb_schema.json` (adds `email_templates` and the email fields on `orders`). +2. In Brevo: **Settings → Senders, Domains & Dedicated IPs → Domains → Add a domain**, then add the DNS records it shows (Brevo code TXT, the DKIM CNAMEs, DMARC TXT on `_dmarc`) and click *Authenticate*. Add a sender such as `bookings@yourdomain.com`. +3. **SMTP & API → SMTP → Generate a new SMTP key**. Put the values in `.env`: `SMTP_HOST=smtp-relay.brevo.com`, `SMTP_PORT=587`, `SMTP_USER` = the SMTP *login* shown there (`…@smtp-brevo.com`, not your account email), `SMTP_PASS` = the key, `EMAIL_FROM` / `EMAIL_FROM_NAME` = the sender. +4. Set `SITE_TIMEZONE` (IANA name, default `Europe/Oslo`) — booking times in emails are shown in this zone. +5. Rebuild, open **Emails** in the admin, and use **Send test email**. + +With `SMTP_HOST` empty (local dev) emails are written to the app container logs instead of being sent. + +## Public routes (public app) + +- `/` renders `pages.slug = "home"` +- `/[slug]` renders any other published page +- Unpublished pages return `404` + +## Notes + +- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON. +- Draft preview writes current blocks to `sessionStorage` and opens `/preview` in an iframe (same-origin on the admin subdomain). +- The page editor includes draggable reordering using native HTML drag events for compatibility; the requested DnD packages are installed and can be swapped in later if desired. diff --git a/app-admin/package-lock.json b/app-admin/package-lock.json index 640d51f..85cdb4e 100644 --- a/app-admin/package-lock.json +++ b/app-admin/package-lock.json @@ -19,6 +19,7 @@ "@tiptap/extension-placeholder": "^3.23.4", "@tiptap/starter-kit": "^3.23.4", "daisyui": "^5.5.19", + "nodemailer": "^10.0.12", "pocketbase": "^0.26.9", "svelte-tiptap": "^3.0.1", "tailwindcss": "^4.3.0", @@ -28,6 +29,7 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", + "@types/nodemailer": "^8.0.2", "@types/uuid": "^10.0.0", "svelte": "^5.55.2", "svelte-check": "^4.4.6", @@ -1683,6 +1685,16 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/resolve": { "version": "1.20.2", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", @@ -2269,6 +2281,15 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/nodemailer": { + "version": "10.0.12", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.12.tgz", + "integrity": "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/obug": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", diff --git a/app-admin/package.json b/app-admin/package.json index f96292f..f2205ab 100644 --- a/app-admin/package.json +++ b/app-admin/package.json @@ -13,6 +13,7 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", + "@types/nodemailer": "^8.0.2", "@types/uuid": "^10.0.0", "svelte": "^5.55.2", "svelte-check": "^4.4.6", @@ -23,14 +24,15 @@ "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", "@dnd-kit/utilities": "^3.2.2", - "@sveltejs/adapter-node": "^5.5.4", "@stripe/stripe-js": "^9.12.1", + "@sveltejs/adapter-node": "^5.5.4", "@tailwindcss/vite": "^4.3.0", "@tiptap/core": "^3.23.4", "@tiptap/extension-link": "^3.23.4", "@tiptap/extension-placeholder": "^3.23.4", "@tiptap/starter-kit": "^3.23.4", "daisyui": "^5.5.19", + "nodemailer": "^10.0.12", "pocketbase": "^0.26.9", "svelte-tiptap": "^3.0.1", "tailwindcss": "^4.3.0", diff --git a/app-admin/src/lib/admin/BlockList.svelte b/app-admin/src/lib/admin/BlockList.svelte index 5542697..761a929 100644 --- a/app-admin/src/lib/admin/BlockList.svelte +++ b/app-admin/src/lib/admin/BlockList.svelte @@ -1,9 +1,10 @@ + +{#if !block} +
Select a block to edit.
+{:else} +
+

{emailBlockLabels[block.type as EmailBlockType]}

+ + {#if block.type === 'text'} + updateData({ content })} /> +

Use placeholders like {'{{customer_first_name}}'} — see the list above.

+ {:else if block.type === 'image'} +
+ updateData(image)} /> + updateData({ width: v })} formatLabel={(v) => `${v}%`} /> + updateData({ alignment: v })} formatLabel={titleCase} /> + +

Images load from the public media server, so they only appear in real inboxes once the site runs on a public domain.

+
+ {:else if block.type === 'button'} +
+ + + updateData({ alignment: v })} formatLabel={titleCase} /> +
+
+ Color +
+ updateData({ color: e.currentTarget.value })} /> + updateData({ color: e.currentTarget.value })} /> +
+
+
+
+ {:else if block.type === 'spacer'} + + {:else if block.type === 'divider'} +

A thin horizontal line. No settings.

+ {:else} +
+ +

{autoFilled[block.type]}

+
+ {/if} +
+{/if} diff --git a/app-admin/src/lib/admin/emailBlockDefaults.ts b/app-admin/src/lib/admin/emailBlockDefaults.ts new file mode 100644 index 0000000..c6743ab --- /dev/null +++ b/app-admin/src/lib/admin/emailBlockDefaults.ts @@ -0,0 +1,43 @@ +import { v4 as uuid } from 'uuid'; +import type { EmailBlock, EmailBlockType } from '$lib/types'; + +export const emailBlockLabels: Record = { + text: 'Text', + image: 'Image', + button: 'Button', + spacer: 'Spacer', + divider: 'Divider', + booking_details: 'Booking details', + customer_details: 'Customer details', + contact_info: 'Contact info' +}; + +export const emailBlockTypes = Object.keys(emailBlockLabels) as EmailBlockType[]; + +export function createEmailBlock(type: EmailBlockType): EmailBlock { + const base: EmailBlock = { id: uuid(), type, data: {} }; + switch (type) { + case 'text': + base.data = { content: '

Hi {{customer_first_name}},

Add your message here.

' }; + break; + case 'image': + base.data = { url: '', alt: '', width: 100, alignment: 'center', href: '' }; + break; + case 'button': + base.data = { label: 'Visit our website', href: '{{site_url}}', alignment: 'center', color: '' }; + break; + case 'spacer': + base.data = { height: 24 }; + break; + case 'booking_details': + base.data = { title: 'Your booking' }; + break; + case 'customer_details': + base.data = { title: 'Customer' }; + break; + case 'contact_info': + base.data = { title: 'Where to find us' }; + break; + } + return base; +} diff --git a/app-admin/src/lib/email.ts b/app-admin/src/lib/email.ts new file mode 100644 index 0000000..987f22e --- /dev/null +++ b/app-admin/src/lib/email.ts @@ -0,0 +1 @@ +export * from '$shared/email'; diff --git a/app-admin/src/lib/server/email.ts b/app-admin/src/lib/server/email.ts new file mode 100644 index 0000000..f8d7657 --- /dev/null +++ b/app-admin/src/lib/server/email.ts @@ -0,0 +1 @@ +export * from '$shared/server/email'; diff --git a/app-admin/src/routes/+layout.svelte b/app-admin/src/routes/+layout.svelte index cd7cd75..93aa833 100644 --- a/app-admin/src/routes/+layout.svelte +++ b/app-admin/src/routes/+layout.svelte @@ -91,6 +91,7 @@ Items Slots Orders + Emails Globals + + + {#if form?.action === 'save' && form.message} +
{form.message}
+ {/if} + +
+ + + {#if isAlert} + + {:else} + +

Sent to the email address the customer entered at checkout. Replies go to {data.settings.business.email || 'the footer email (not set yet)'}.

+ {/if} + +
+ Placeholders +
+

Type these into the subject or any text block; they're replaced with the booking's details. Click one to copy it.

+
+ {#each emailPlaceholders as placeholder} + + {/each} +
+
+
+
+ +
+ + +
+ + +
+
+
+

Preview

+

With a sample booking. Subject: {rendered.subject}

+
+
+
+ + +
+
+ + +
+
+
+ {#if previewFormat === 'html'} + + {:else} +
{rendered.text}
+ {/if} +
+ +
{ + testing = true; + return async ({ update }) => { + testing = false; + await update({ reset: false, invalidateAll: false }); + }; + }} + > +

Send a test email

+

Sends the current (unsaved) version with the sample booking{data.key === 'customer_confirmation' ? ', including the calendar attachment' : ''}.

+ {#if !data.smtpConfigured} +
SMTP is not configured, so the test email will only be written to the server log.
+ {/if} + + +
+ + +
+ {#if form?.action === 'test' && form.message} +
{form.message}
+ {/if} +
+ + {#if data.customised} +
{ + if (!confirm('Replace this email with the built-in default? Your changes will be lost.')) e.preventDefault(); + }} + > + +
+ {/if} + diff --git a/app-admin/src/routes/orders/+page.server.ts b/app-admin/src/routes/orders/+page.server.ts index 97607eb..91b97fa 100644 --- a/app-admin/src/routes/orders/+page.server.ts +++ b/app-admin/src/routes/orders/+page.server.ts @@ -1,4 +1,6 @@ -import type { PageServerLoad } from './$types'; +import { fail } from '@sveltejs/kit'; +import { sendOrderEmails, type EmailKind } from '$lib/server/email'; +import type { Actions, PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ locals }) => { // Sort by id, not 'created' — commerce collections were imported without @@ -9,7 +11,7 @@ export const load: PageServerLoad = async ({ locals }) => { for (const record of records) { const lineRecords = await locals.pb .collection('order_lines') - .getFullList({ filter: `order = "${record.id}"` }) + .getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) }) .catch(() => []); orders.push({ @@ -19,6 +21,9 @@ export const load: PageServerLoad = async ({ locals }) => { total: Number(record.total) || 0, status: String(record.status || 'pending'), created: String(record.created || ''), + customerEmailSentAt: String(record.customerEmailSentAt || ''), + clientEmailSentAt: String(record.clientEmailSentAt || ''), + emailError: String(record.emailError || ''), lines: lineRecords.map((line) => ({ id: line.id, name: String(line.name || ''), @@ -32,3 +37,25 @@ export const load: PageServerLoad = async ({ locals }) => { return { orders }; }; + +const OUTCOME_MESSAGES: Record = { + sent: 'sent', + logged: 'not sent — SMTP is not configured (written to the server log)', + disabled: 'not sent — this email is turned off in Emails', + failed: 'failed — see the error on the order' +}; + +export const actions: Actions = { + resend: async ({ request, locals }) => { + const data = await request.formData(); + const orderId = String(data.get('orderId') || ''); + const kind = String(data.get('kind') || ''); + if (!orderId || (kind !== 'customer' && kind !== 'client')) { + return fail(400, { orderId, ok: false, message: 'Invalid resend request.' }); + } + const outcomes = await sendOrderEmails(locals.pb, orderId, [kind as EmailKind]); + const outcome = outcomes[kind as EmailKind] ?? 'failed'; + const label = kind === 'customer' ? 'Customer confirmation' : 'Booking alert'; + return { orderId, ok: outcome === 'sent', message: `${label} ${OUTCOME_MESSAGES[outcome]}.` }; + } +}; diff --git a/app-admin/src/routes/orders/+page.svelte b/app-admin/src/routes/orders/+page.svelte index f5dc5f7..32e2af8 100644 --- a/app-admin/src/routes/orders/+page.svelte +++ b/app-admin/src/routes/orders/+page.svelte @@ -1,10 +1,37 @@ +{#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)} +
{ + resending = `${order.id}-${kind}`; + return async ({ update }) => { + resending = ''; + await update(); + }; + }} + > + + + + {label}: {sentAt ? 'sent' : 'not sent'} + + +
+{/snippet} + Orders | CMS
@@ -53,6 +80,17 @@ {#if order.customerDetails?.notes}

"{order.customerDetails.notes}"

{/if} + +
+ {@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)} + {@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)} +
+ {#if order.emailError} +

{order.emailError}

+ {/if} + {#if form?.orderId === order.id && form.message} +
{form.message}
+ {/if}
{/each} diff --git a/app-public/package-lock.json b/app-public/package-lock.json index d662fc4..ef8c7f5 100644 --- a/app-public/package-lock.json +++ b/app-public/package-lock.json @@ -12,6 +12,7 @@ "@sveltejs/adapter-node": "^5.5.4", "@tailwindcss/vite": "^4.3.0", "daisyui": "^5.5.19", + "nodemailer": "^10.0.12", "pocketbase": "^0.26.9", "stripe": "^22.3.2", "tailwindcss": "^4.3.0" @@ -20,6 +21,7 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", + "@types/nodemailer": "^8.0.2", "svelte": "^5.55.2", "svelte-check": "^4.4.6", "typescript": "^6.0.2", @@ -1168,6 +1170,16 @@ "undici-types": ">=7.24.0 <7.24.7" } }, + "node_modules/@types/nodemailer": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz", + "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/resolve": { "version": "1.20.2", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", @@ -1741,6 +1753,15 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/nodemailer": { + "version": "10.0.12", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.12.tgz", + "integrity": "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg==", + "license": "MIT-0", + "engines": { + "node": ">=20.0.0" + } + }, "node_modules/obug": { "version": "2.1.4", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", diff --git a/app-public/package.json b/app-public/package.json index 6de53b5..dbe812b 100644 --- a/app-public/package.json +++ b/app-public/package.json @@ -13,6 +13,7 @@ "@sveltejs/kit": "^2.57.0", "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^25.8.0", + "@types/nodemailer": "^8.0.2", "svelte": "^5.55.2", "svelte-check": "^4.4.6", "typescript": "^6.0.2", @@ -23,6 +24,7 @@ "@sveltejs/adapter-node": "^5.5.4", "@tailwindcss/vite": "^4.3.0", "daisyui": "^5.5.19", + "nodemailer": "^10.0.12", "pocketbase": "^0.26.9", "stripe": "^22.3.2", "tailwindcss": "^4.3.0" diff --git a/app-public/src/lib/server/email.ts b/app-public/src/lib/server/email.ts new file mode 100644 index 0000000..f8d7657 --- /dev/null +++ b/app-public/src/lib/server/email.ts @@ -0,0 +1 @@ +export * from '$shared/server/email'; diff --git a/app-public/src/routes/api/webhooks/stripe/+server.ts b/app-public/src/routes/api/webhooks/stripe/+server.ts index fec8e6c..fe47d9a 100644 --- a/app-public/src/routes/api/webhooks/stripe/+server.ts +++ b/app-public/src/routes/api/webhooks/stripe/+server.ts @@ -5,6 +5,7 @@ import { getStripe } from '$lib/stripe.server'; import { getAdminPb } from '$lib/server/pb-admin'; import { getFileUrl } from '$lib/pb'; import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket'; +import { sendOrderEmails } from '$lib/server/email'; import type PocketBase from 'pocketbase'; async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { @@ -14,7 +15,7 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { // Idempotency: if an order already exists for this intent, we're done. const existing = await pb .collection('orders') - .getFirstListItem(`stripePaymentIntentId = "${paymentIntent.id}"`) + .getFirstListItem(pb.filter('stripePaymentIntentId = {:id}', { id: paymentIntent.id })) .catch(() => null); if (existing) return; @@ -23,7 +24,7 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { const lines = await pb .collection('basket_lines') - .getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot' }); + .getFullList({ filter: pb.filter('basket = {:basketId}', { basketId }), expand: 'item,slot' }); // Create the order const order = await pb.collection('orders').create({ @@ -68,6 +69,11 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { await pb.collection('basket_lines').delete(line.id).catch(() => {}); } await pb.collection('baskets').update(basketId, { status: 'completed' }).catch(() => {}); + + // Confirmation to the customer + alert to the studio. Not awaited: SMTP can + // be slow and Stripe only needs the 2xx. sendOrderEmails never throws and + // records the outcome on the order, so failures can be resent from /orders. + void sendOrderEmails(pb, order.id); } async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) { diff --git a/backups/logo.png b/backups/logo.png new file mode 100644 index 0000000..0b09999 Binary files /dev/null and b/backups/logo.png differ diff --git a/docker-compose.yml b/docker-compose.yml index 40bfcae..416bbc3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,6 +27,15 @@ services: # Commerce (reservation & payment system) — set these in a root-level .env POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} + STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} # Internal only — served via the caddy reverse proxy expose: - "3001" @@ -51,6 +60,14 @@ services: STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} # Internal only — served via the caddy reverse proxy expose: - "3000" diff --git a/packages/shared/bun.lock b/packages/shared/bun.lock index 34d4a70..7132e83 100644 --- a/packages/shared/bun.lock +++ b/packages/shared/bun.lock @@ -6,13 +6,25 @@ "name": "@eva/shared", "dependencies": { "@stripe/stripe-js": "^9.12.1", + "nodemailer": "^10.0.12", "pocketbase": "^0.26.9", }, + "devDependencies": { + "@types/nodemailer": "^8.0.2", + }, }, }, "packages": { "@stripe/stripe-js": ["@stripe/stripe-js@9.13.0", "", {}, "sha512-/0c72BUgzzVkVTlsw5uBn8x3waTdVJ/PZGfQ6jY1eu6K7olUPf4d9lgDPA9/0sIdsR8j7o3QIG8fOCO6ItcL7A=="], + "@types/node": ["@types/node@26.6.3", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg=="], + + "@types/nodemailer": ["@types/nodemailer@8.0.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="], + + "nodemailer": ["nodemailer@10.0.12", "", {}, "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg=="], + "pocketbase": ["pocketbase@0.26.9", "", {}, "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ=="], + + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], } } diff --git a/packages/shared/package.json b/packages/shared/package.json index 1a20a58..700f658 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -12,10 +12,16 @@ "./basket.svelte": "./src/basket.svelte.ts", "./blocks/BlockRenderer.svelte": "./src/blocks/BlockRenderer.svelte", "./server/pb-admin": "./src/server/pb-admin.ts", - "./server/basket": "./src/server/basket.ts" + "./server/basket": "./src/server/basket.ts", + "./email": "./src/email/index.ts", + "./server/email": "./src/server/email/index.ts" }, "dependencies": { - "pocketbase": "^0.26.9", - "@stripe/stripe-js": "^9.12.1" + "@stripe/stripe-js": "^9.12.1", + "nodemailer": "^10.0.12", + "pocketbase": "^0.26.9" + }, + "devDependencies": { + "@types/nodemailer": "^8.0.2" } } diff --git a/packages/shared/src/email/defaults.ts b/packages/shared/src/email/defaults.ts new file mode 100644 index 0000000..c13a9e6 --- /dev/null +++ b/packages/shared/src/email/defaults.ts @@ -0,0 +1,86 @@ +import type { EmailBlock, EmailTemplate, EmailTemplateKey } from '../types'; + +export const emailTemplateKeys: EmailTemplateKey[] = ['customer_confirmation', 'client_alert']; + +export const emailTemplateMeta: Record = { + customer_confirmation: { + label: 'Booking confirmation', + description: 'Sent to the customer after a successful payment. Includes a calendar (.ics) attachment for booked time slots.' + }, + client_alert: { + label: 'New booking alert', + description: 'Sent to you after a successful payment. Replying goes straight to the customer.' + } +}; + +// Used whenever no email_templates record exists for a key, so booking emails +// work before anyone has opened the email editor. +export const defaultEmailTemplates: Record = { + customer_confirmation: { + key: 'customer_confirmation', + subject: 'Your booking is confirmed – {{service}}', + recipients: '', + enabled: true, + blocks: [ + { + id: 'default-cc-intro', + type: 'text', + data: { + content: + '

Thank you, {{customer_first_name}}!

Your booking is confirmed and paid. Here are the details:

' + } + }, + { id: 'default-cc-booking', type: 'booking_details', data: { title: 'Your booking' } }, + { + id: 'default-cc-outro', + type: 'text', + data: { + content: + '

A calendar file is attached — open it to add the appointment to your calendar.

If you need to change or cancel your booking, simply reply to this email.

Looking forward to seeing you,
{{business_name}}

' + } + }, + { id: 'default-cc-divider', type: 'divider', data: {} }, + { id: 'default-cc-contact', type: 'contact_info', data: { title: 'Where to find us' } } + ] satisfies EmailBlock[] + }, + client_alert: { + key: 'client_alert', + subject: 'New booking: {{service}} – {{customer_name}}', + recipients: '', + enabled: true, + blocks: [ + { + id: 'default-ca-intro', + type: 'text', + data: { + content: + '

New booking

{{customer_name}} just booked and paid {{order_total}}.

' + } + }, + { id: 'default-ca-booking', type: 'booking_details', data: { title: 'Booking' } }, + { id: 'default-ca-customer', type: 'customer_details', data: { title: 'Customer' } }, + { + id: 'default-ca-outro', + type: 'text', + data: { content: '

Reply to this email to contact {{customer_first_name}} directly.

' } + } + ] satisfies EmailBlock[] + } +}; + +export function isEmailTemplateKey(value: string): value is EmailTemplateKey { + return (emailTemplateKeys as string[]).includes(value); +} + +/** Merge a PocketBase record (or partial data) over the default for its key. */ +export function normalizeEmailTemplate(key: EmailTemplateKey, record?: Record | null): EmailTemplate { + const fallback = defaultEmailTemplates[key]; + if (!record) return structuredClone(fallback); + return { + key, + subject: typeof record.subject === 'string' && record.subject.trim() ? record.subject : fallback.subject, + blocks: Array.isArray(record.blocks) ? record.blocks : structuredClone(fallback.blocks), + recipients: typeof record.recipients === 'string' ? record.recipients : '', + enabled: typeof record.enabled === 'boolean' ? record.enabled : true + }; +} diff --git a/packages/shared/src/email/index.ts b/packages/shared/src/email/index.ts new file mode 100644 index 0000000..76b989f --- /dev/null +++ b/packages/shared/src/email/index.ts @@ -0,0 +1,2 @@ +export * from './render'; +export * from './defaults'; diff --git a/packages/shared/src/email/render.ts b/packages/shared/src/email/render.ts new file mode 100644 index 0000000..4a1086e --- /dev/null +++ b/packages/shared/src/email/render.ts @@ -0,0 +1,424 @@ +import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types'; + +// 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. +// +// Email clients (Gmail, Outlook, Apple Mail) strip