Compare commits

...

10 commits

Author SHA1 Message Date
Jakub Dorfman
fd1afc5f3a fixed image upload 2026-09-28 19:52:24 +02:00
Jakub Dorfman
96828994e1 added mailing through Brevo and node mailer, also a email editor, with
their custom blocks and renderers
2026-09-28 19:25:19 +02:00
Jakub Dorfman
43db707e34 added configurable modes to caddy http/https 2026-08-19 21:16:12 +02:00
Jakub Dorfman
c3989114b8 moved shared code to the shared package 2026-08-19 19:18:31 +02:00
Jakub Dorfman
478a5fd466 moved shared code to the shared package 2026-08-19 19:18:10 +02:00
Jakub Dorfman
1027da989e moved page rendering to a different service and access is now behind
admin.DOMAIN
www.DOMAIN
db.DOMAIN
2026-08-19 17:58:19 +02:00
Jakub Dorfman
c7f6b30b87 removed bare dev fallback routes, only support developmnet in
docker/podman
2026-08-19 13:22:51 +02:00
Jakub Dorfman
702d99b9ed Added shop and checkout to the CMS
Checkout is done with stripe
Added reservation system
2026-07-29 18:18:23 +02:00
Jakub Dorfman
09e54033dd fixed export of images 2026-06-05 16:23:24 +02:00
Jakub Dorfman
3e7a4f8983 fixed pocketbase volume
visual updates to Testimonials and UpcomingCalendar
2026-06-05 15:59:15 +02:00
144 changed files with 9667 additions and 1736 deletions

View file

@ -1,6 +1,10 @@
node_modules node_modules
app/node_modules app-admin/node_modules
app/.svelte-kit app-admin/.svelte-kit
app/build app-admin/build
app-public/node_modules
app-public/.svelte-kit
app-public/build
packages/shared/node_modules
.git .git
pocketbase/pb_data pocketbase/pb_data

View file

@ -1,2 +1,35 @@
PUBLIC_POCKETBASE_URL=http://localhost:8090 # Secrets read by docker-compose.yml via ${VAR:-} substitution.
POCKETBASE_INTERNAL_URL=http://localhost:8090 # Copy to .env at the project root and fill in.
# Stripe
STRIPE_SECRET_KEY=sk_test_...
PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_CURRENCY=eur
# PocketBase superuser credentials (used by server-side basket/checkout/webhook APIs)
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;
# also update ORIGIN/PUBLIC_* URLs to https://...)
CADDY_SCHEME=http

View file

@ -5,8 +5,8 @@ node_modules
.vercel .vercel
.netlify .netlify
.wrangler .wrangler
/.svelte-kit */.svelte-kit
/build */build
# OS # OS
.DS_Store .DS_Store
@ -21,3 +21,6 @@ Thumbs.db
# Vite # Vite
vite.config.js.timestamp-* vite.config.js.timestamp-*
vite.config.ts.timestamp-* vite.config.ts.timestamp-*
# Local project notes
status.md

153
AGENTS.md
View file

@ -5,36 +5,83 @@
- **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc.
- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. - **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage.
- **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site.
- **Docker Compose** — three services: `app` (SvelteKit), `pocketbase`, and `caddy` (reverse proxy). - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy).
## Project Structure ## Project Structure
``` ```
app/ # SvelteKit application packages/shared/src/ # Shared code (types, calendar utils, blocks, pb, basket, stripe)
app-admin/ # SvelteKit admin app (serves admin.<domain>)
├── src/ ├── src/
│ ├── lib/ │ ├── lib/
│ │ ├── admin/ # Admin UI components (BlockList, editors) │ │ ├── admin/ # Admin UI components (BlockList, editors)
│ │ ├── blocks/ # Public block renderers (one per BlockType) │ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared)
│ │ ├── components/ # Header.svelte, Footer.svelte │ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia
│ │ ├── pb.ts # PocketBase client factory + helpers │ │ ├── types.ts # Re-exports from $shared
│ │ └── types.ts # ContentBlock, PageRecord, HeaderGlobal, FooterGlobal │ │ ├── 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/ │ ├── routes/
│ │ ├── +layout.svelte # Root layout (admin vs public shell) │ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout)
│ │ ├── +page.svelte # Home page (slug=home) │ │ ├── login/ # Admin login
│ │ ├── [slug]/ # Dynamic CMS pages │ │ ├── pages/ # Page CRUD + block editor
│ │ ├── admin/ # Admin area (login, pages, globals) │ │ ├── calendar/ # Event CRUD
│ │ └── preview/ # Draft preview via sessionStorage │ │ ├── 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 │ └── app.css # Tailwind + DaisyUI + custom theme
├── static/ # Static assets ├── static/ # Static assets
├── build/ # Production build output ├── build/ # Production build output
├── svelte.config.js # Adapter-node, runes mode forced ├── svelte.config.js # Adapter-node, runes mode forced, $shared alias
├── vite.config.ts # Tailwind v4 + SvelteKit plugins ├── vite.config.ts # Tailwind v4 + SvelteKit plugins
└── package.json └── package.json
pocketbase/pb_data/ # PocketBase data (mounted volume-mounted) app-public/ # SvelteKit public app (serves *.<domain>)
docker-compose.yml # app + pocketbase services ├── src/
Dockerfile # Multi-stage Node 22 build │ ├── 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 ## Key Conventions
### Svelte 5 Runes Mode ### Svelte 5 Runes Mode
@ -47,20 +94,35 @@ All components use Svelte 5 runes syntax — **never** `export let`, `$:`, or `o
- `onclick={handler}` (not `on:click`) - `onclick={handler}` (not `on:click`)
### Block System ### Block System
Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Block types are defined in `$lib/types.ts`: 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 | image_text | timeline | testimonials | services | cta | spacer | horizontal_cards` `text | image_text | timeline | hero | button | spacer | testimonials | upcoming_calendar | shop | checkout`
- **Public renderers**: `$lib/blocks/<Type>Block.svelte` — one per type, receives `data` prop. Currently active: `TextBlock`, `ImageTextBlock`, `TimelineBlock`, `HeroBlock`. - **Renderers (shared)**: `packages/shared/src/blocks/<Type>Block.svelte` — one renderer per type, imported by both apps via `$shared/blocks/...`. The admin preview iframe uses the same shared renderers.
- **Admin editors**: `$lib/admin/editors/BlockEditor.svelte` — switches editor UI by type - **Admin editors**: `app-admin/src/lib/admin/editors/BlockEditor.svelte` — switches editor UI by type
- **Defaults**: `$lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults - **Defaults**: `app-admin/src/lib/admin/blockDefaults.ts` — `createBlock(type)` generates a new block with sensible defaults
- **Block list**: `$lib/admin/BlockList.svelte` — draggable reorder, select, delete - **Block list**: `app-admin/src/lib/admin/BlockList.svelte` — draggable reorder, select, delete
To add a new block type: add to `BlockType` union in `types.ts`, create renderer in `$lib/blocks/`, add editor case in `BlockEditor.svelte`, add default in `blockDefaults.ts`, add import in `BlockRenderer.svelte`. To add a new block type: add to `BlockType` union in `packages/shared/src/types.ts`, create renderer in `packages/shared/src/blocks/`, add editor case in `app-admin/src/lib/admin/editors/BlockEditor.svelte`, add default in `app-admin/src/lib/admin/blockDefaults.ts`, add import in `packages/shared/src/blocks/BlockRenderer.svelte`.
### 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 ### PocketBase Integration
- Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie - Client created in `hooks.server.ts` (`event.locals.pb`) — injected per-request with auth cookie
- `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` - `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()`
- Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt) - Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled)
- Server load functions use `locals.pb.collection('pages').getFirstListItem()` - Server load functions use `locals.pb.collection('pages').getFirstListItem()`
### Styling ### Styling
@ -69,38 +131,37 @@ To add a new block type: add to `BlockType` union in `types.ts`, create renderer
- **Prose**: `.prose-wellness` class for rich text content styling - **Prose**: `.prose-wellness` class for rich text content styling
### Routing ### Routing
- `+layout.server.ts` fetches header/footer globals for every public page - **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` - `+page.server.ts` for home fetches `slug = "home" && published = true`
- `[slug]/+page.server.ts` fetches by dynamic slug - `[slug]/+page.server.ts` fetches by dynamic slug
- Admin routes protected in `hooks.server.ts` — redirects to `/admin/login` if unauthenticated
## Build & Dev Commands ## Build & Dev Commands
```sh ```sh
# Development (from app/) # Full stack (single entry point on port 8080) — the only supported way to run/develop
cd app # Source changes require rebuilding; the container runs `node build`, not a dev server.
npm install DOMAIN=localhost docker compose up --build
npm run dev # http://localhost:5173 # Admin app: http://admin.localhost:8080
# Public app: http://www.localhost:8080
# PocketBase: http://db.localhost:8080/_/
# Production build # Type checking (can run on the host with node_modules present)
npm run build cd app-admin && npm run check
cd app-public && npm run check
# Type checking # Production build only (run by each app's Dockerfile)
npm run check cd app-admin && npm run build
cd app-public && npm run build
# Docker full stack (single entry point on port 8080)
docker compose up --build
# App + PocketBase via Caddy: http://localhost:8080
# PocketBase admin: http://localhost:8080/_/
# PocketBase only (for local dev outside Docker)
docker compose up pocketbase
# Direct access: http://localhost:8090/_/
``` ```
## Environment ## Environment
- `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL, now accessed through the Caddy reverse proxy (default `http://localhost:8080`) - `DOMAIN` — base domain for subdomain routing. Defaults to `localhost` for local dev. Set in `docker-compose.yml` or `.env`.
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`) - `PUBLIC_POCKETBASE_URL` — public-facing PocketBase URL (`http://db.${DOMAIN}:8080`). Set in `docker-compose.yml`.
- `ORIGIN` — SvelteKit origin for SSR (`http://localhost:8080`) - `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`.
- Copy `app/.env.example` → `app/.env` for local dev - `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`.

View file

@ -1,17 +1,26 @@
# Reverse proxy — single port for both the SvelteKit app and PocketBase # Reverse proxy — subdomain-based routing on port 8080
# Route: /api/* and /_/* → PocketBase # admin.{$DOMAIN} → app-admin (SvelteKit admin app)
# everything else → SvelteKit app # db.{$DOMAIN} → PocketBase (redirects / to /_/)
# *.{$DOMAIN} → app-public (SvelteKit public app)
#
# The scheme is controlled by the {$CADDY_SCHEME} env var (default: http).
# - http → plain HTTP (disables Caddy's automatic HTTPS). Matches the ORIGIN
# env vars in docker-compose.yml (http://admin.${DOMAIN}:8080 etc.)
# so SvelteKit's CSRF protection accepts form POSTs.
# - https → HTTPS. On a non-standard port (8080) Caddy will issue internal
# self-signed certificates unless you configure a real cert issuer.
# Remember to also update ORIGIN/PUBLIC_* URLs in docker-compose.yml.
:8080 { {$CADDY_SCHEME}://admin.{$DOMAIN}:8080 {
handle /api/* { reverse_proxy app-admin:3001
}
{$CADDY_SCHEME}://db.{$DOMAIN}:8080 {
# PocketBase admin UI lives at /_/ — redirect bare root there.
redir / /_/{path}
reverse_proxy pocketbase:80 reverse_proxy pocketbase:80
} }
handle /_/* { {$CADDY_SCHEME}://www.{$DOMAIN}:8080, {$CADDY_SCHEME}://*.{$DOMAIN}:8080 {
reverse_proxy pocketbase:80 reverse_proxy app-public:3000
}
handle {
reverse_proxy app:3000
}
} }

143
README.md
View file

@ -4,63 +4,70 @@ A full-stack SvelteKit CMS for a single-operator massage studio. PocketBase prov
## Stack ## Stack
- SvelteKit + SSR - SvelteKit + SSR (two apps: admin and public)
- PocketBase REST API via the `pocketbase` SDK - PocketBase REST API via the `pocketbase` SDK
- Tailwind CSS v4 + DaisyUI - Tailwind CSS v4 + DaisyUI
- Docker Compose with three services: `app`, `pocketbase`, and `caddy` (reverse proxy) - Docker Compose with four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy)
## Local development ## Architecture
1. Install Node.js `22.x` or another version accepted by SvelteKit's Vite plugin. The project is split into two independent SvelteKit apps, each serving its own subdomain:
2. Copy the app env file:
```sh
cp app/.env.example app/.env
```
3. Start PocketBase on port `8090`. With Docker:
```sh
docker compose up pocketbase
```
4. In another terminal:
```sh
cd app
npm install
npm run dev
```
5. Visit `http://localhost:5173`.
> **Note:** During local development (outside Docker), PocketBase is accessed directly at `http://localhost:8090`. When running the full Docker stack, everything goes through the Caddy reverse proxy on port `8080`. - **`app-admin`** — serves `admin.<domain>` (admin UI, page editor, CRUD)
- **`app-public`** — serves `*.<domain>` (public CMS pages, shop, checkout)
- **PocketBase** — serves `db.<domain>` (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 ## Docker Compose
Run the full stack: Run the full stack:
```sh ```sh
docker compose up --build DOMAIN=localhost docker compose up --build
``` ```
If dependency installation is slow on the first build, enable BuildKit explicitly: If dependency installation is slow on the first build, enable BuildKit explicitly:
```sh ```sh
DOCKER_BUILDKIT=1 docker compose build --progress=plain app DOCKER_BUILDKIT=1 docker compose build --progress=plain app-admin app-public
docker compose up docker compose up
``` ```
Subsequent builds reuse the npm cache declared in the `Dockerfile`. Subsequent builds reuse the npm cache declared in each app's `Dockerfile`.
- Single entry point (Caddy reverse proxy): **`http://localhost:8080`** - **Admin app**: `http://admin.localhost:8080` → `app-admin:3001`
- SvelteKit app: `http://localhost:8080/` (or any non-API path) - **Public app**: `http://www.localhost:8080` → `app-public:3000`
- PocketBase admin UI: `http://localhost:8080/_/` - **PocketBase admin UI**: `http://db.localhost:8080/_/` (redirects `/` to `/_/`)
- PocketBase REST API: `http://localhost:8080/api/` - **PocketBase REST API**: `http://db.localhost:8080/api/`
- PocketBase direct access (internal only, not exposed): `http://localhost:8090`
The app container uses two PocketBase URLs: The app containers use two PocketBase URLs:
- `POCKETBASE_INTERNAL_URL=http://pocketbase:80` for server-side SvelteKit calls from the app container when using the included `spectado/pocketbase` image. - `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://localhost:8080` for browser-side admin uploads and public file URLs. Since the Caddy reverse proxy routes `/api/*` to PocketBase, the public URL points to the proxy. - `PUBLIC_POCKETBASE_URL=http://db.${DOMAIN}:8080` for browser-side admin uploads and public file URLs. Points to the Caddy reverse proxy so browsers reach PocketBase via the `db` subdomain.
## PocketBase setup ## PocketBase setup
1. Open `http://localhost:8080/_/` (or `http://localhost:8090/_/` for direct access). 1. Open `http://db.localhost:8080/_/`.
2. Create the first PocketBase admin user when prompted. 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. 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: 4. Create starter records:
@ -86,23 +93,77 @@ If schema import fails because of a PocketBase version mismatch, create these co
- `file`: file, required, max select `1`, image mime types - `file`: file, required, max select `1`, image mime types
- `alt`: text - `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 ## Authentication
Admin routes live under `/admin`. Login accepts either: Admin routes live in the `app-admin` app. Login accepts either:
- a PocketBase admin account, or - a PocketBase admin account, or
- a record from a `users` auth collection if you create one. - a record from a `users` auth collection if you create one.
All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`. All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
## CMS routes ## CMS routes (admin app)
- `/admin/login` — sign in - `/login` — sign in
- `/admin/pages` — list/create pages - `/pages` — list/create pages
- `/admin/pages/[slug]` — block editor with draft preview - `/pages/[slug]` — block editor with draft preview
- `/admin/globals` — header/footer editor - `/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
## Public routes ## 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"` - `/` renders `pages.slug = "home"`
- `/[slug]` renders any other published page - `/[slug]` renders any other published page
@ -111,5 +172,5 @@ All `/admin` routes except `/admin/login` are guarded in `src/hooks.server.ts`.
## Notes ## Notes
- Admin image uploads create records in the `media` collection and store PocketBase file URLs in block JSON. - 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. - 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. - 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.

25
app-admin/Dockerfile Normal file
View file

@ -0,0 +1,25 @@
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS build
WORKDIR /app
ENV NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY app-admin/package*.json ./
COPY packages/shared/package.json ./packages/shared/package.json
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
COPY app-admin/ ./
COPY packages/shared/ ./packages/shared/
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production \
NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false
COPY --from=build /app/build ./build
COPY --from=build /app/package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev --ignore-scripts --no-audit --no-fund
EXPOSE 3001
CMD ["node", "build"]

File diff suppressed because it is too large Load diff

View file

@ -1,21 +1,19 @@
{ {
"name": "app", "name": "app-admin",
"private": true,
"version": "0.0.1", "version": "0.0.1",
"private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite dev",
"build": "vite build", "build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''", "prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch" "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
}, },
"devDependencies": { "devDependencies": {
"@sveltejs/adapter-auto": "^7.0.1",
"@sveltejs/kit": "^2.57.0", "@sveltejs/kit": "^2.57.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0", "@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/node": "^25.8.0", "@types/node": "^25.8.0",
"@types/nodemailer": "^8.0.2",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"svelte": "^5.55.2", "svelte": "^5.55.2",
"svelte-check": "^4.4.6", "svelte-check": "^4.4.6",
@ -26,6 +24,7 @@
"@dnd-kit/core": "^6.3.1", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
"@stripe/stripe-js": "^9.12.1",
"@sveltejs/adapter-node": "^5.5.4", "@sveltejs/adapter-node": "^5.5.4",
"@tailwindcss/vite": "^4.3.0", "@tailwindcss/vite": "^4.3.0",
"@tiptap/core": "^3.23.4", "@tiptap/core": "^3.23.4",
@ -33,6 +32,7 @@
"@tiptap/extension-placeholder": "^3.23.4", "@tiptap/extension-placeholder": "^3.23.4",
"@tiptap/starter-kit": "^3.23.4", "@tiptap/starter-kit": "^3.23.4",
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12",
"pocketbase": "^0.26.9", "pocketbase": "^0.26.9",
"svelte-tiptap": "^3.0.1", "svelte-tiptap": "^3.0.1",
"tailwindcss": "^4.3.0", "tailwindcss": "^4.3.0",

View file

@ -5,21 +5,20 @@ import { createPocketBase } from '$lib/pb';
export const handle: Handle = async ({ event, resolve }) => { export const handle: Handle = async ({ event, resolve }) => {
event.locals.pb = createPocketBase( event.locals.pb = createPocketBase(
event.request.headers.get('cookie') ?? '', event.request.headers.get('cookie') ?? '',
env.POCKETBASE_INTERNAL_URL || env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080' env.POCKETBASE_INTERNAL_URL
); );
event.locals.user = event.locals.pb.authStore.record; event.locals.user = event.locals.pb.authStore.record;
const path = event.url.pathname; const path = event.url.pathname;
const isAdminRoute = path.startsWith('/admin'); const isLoginRoute = path === '/login';
const isLoginRoute = path === '/admin/login';
const isAuthed = event.locals.pb.authStore.isValid; const isAuthed = event.locals.pb.authStore.isValid;
if (isAdminRoute && !isLoginRoute && !isAuthed) { if (!isLoginRoute && !isAuthed) {
throw redirect(303, '/admin/login'); throw redirect(303, '/login');
} }
if (isLoginRoute && isAuthed) { if (isLoginRoute && isAuthed) {
throw redirect(303, '/admin/pages'); throw redirect(303, '/pages');
} }
const response = await resolve(event); const response = await resolve(event);

View file

@ -1,9 +1,10 @@
<script lang="ts"> <script lang="ts">
import type { BlockType, ContentBlock } from '$lib/types'; import type { ContentBlock, EmailBlock } from '$lib/types';
import { blockLabels } from '$lib/admin/blockDefaults'; import { blockLabels } from '$lib/admin/blockDefaults';
let { blocks = [], selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{ let { blocks = [], labels = blockLabels, selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
blocks: ContentBlock[]; blocks: (ContentBlock | EmailBlock)[];
labels?: Record<string, string>;
selectedId?: string; selectedId?: string;
onSelect?: (id: string) => void; onSelect?: (id: string) => void;
onDelete?: (id: string) => void; onDelete?: (id: string) => void;
@ -17,7 +18,7 @@
function startHold(id: string) { function startHold(id: string) {
holdingId = id; holdingId = id;
holdTimer = setTimeout(() => { holdTimer = setTimeout(() => {
const idx = blocks.findIndex((b: ContentBlock) => b.id === id); const idx = blocks.findIndex((b: ContentBlock | EmailBlock) => b.id === id);
onDelete(id); onDelete(id);
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || ''); onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || '');
holdingId = ''; holdingId = '';
@ -44,7 +45,7 @@
> >
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span class="cursor-grab text-xl text-base-content/40">☰</span> <span class="cursor-grab text-xl text-base-content/40">☰</span>
<div class="flex-1 font-semibold">{blockLabels[block.type as BlockType]}</div> <div class="flex-1 font-semibold">{labels[block.type] ?? block.type}</div>
<button <button
class="btn btn-xs btn-error btn-outline relative overflow-hidden" class="btn btn-xs btn-error btn-outline relative overflow-hidden"
class:btn-disabled={holdingId && holdingId !== block.id} class:btn-disabled={holdingId && holdingId !== block.id}

View file

@ -9,7 +9,9 @@ export const blockLabels: Record<BlockType, string> = {
button: 'Button', button: 'Button',
spacer: 'Spacer', spacer: 'Spacer',
testimonials: 'Testimonials', testimonials: 'Testimonials',
upcoming_calendar: 'Upcoming Calendar' upcoming_calendar: 'Upcoming Calendar',
shop: 'Shop',
checkout: 'Checkout'
}; };
export const blockTypes = Object.keys(blockLabels) as BlockType[]; export const blockTypes = Object.keys(blockLabels) as BlockType[];
@ -63,6 +65,21 @@ export function createBlock(type: BlockType): ContentBlock {
categories: [] categories: []
}; };
break; break;
case 'shop':
base.data = {
title: 'Our Services',
itemTypeFilter: 'all',
itemIds: [],
layout: 'grid'
};
break;
case 'checkout':
base.data = {
title: 'Checkout',
heading: 'Complete your booking',
notesLabel: 'Notes or special requests'
};
break;
} }
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 }; base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
return base; return base;

View file

@ -4,10 +4,13 @@
import RichTextEditor from './RichTextEditor.svelte'; import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte'; import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte'; import SegmentedControl from './SegmentedControl.svelte';
import ShopBlockEditor from './ShopBlockEditor.svelte';
import CheckoutBlockEditor from './CheckoutBlockEditor.svelte';
let { block, eventCategories = [], onChange = (block: ContentBlock) => {} } = $props<{ let { block, eventCategories = [], items = [], onChange = (block: ContentBlock) => {} } = $props<{
block: ContentBlock | null; block: ContentBlock | null;
eventCategories?: string[]; eventCategories?: string[];
items?: { id: string; name: string; type: string }[];
onChange?: (block: ContentBlock) => void; onChange?: (block: ContentBlock) => void;
}>(); }>();
@ -200,6 +203,10 @@
{/if} {/if}
</div> </div>
</div> </div>
{:else if block.type === 'shop'}
<ShopBlockEditor {block} {items} {onChange} />
{:else if block.type === 'checkout'}
<CheckoutBlockEditor {block} {onChange} />
{/if} {/if}
<div class="rounded-box border border-base-300 p-4 mt-4"> <div class="rounded-box border border-base-300 p-4 mt-4">

View file

@ -0,0 +1,31 @@
<script lang="ts">
import type { ContentBlock, CheckoutBlockData } from '$lib/types';
let {
block,
onChange = (b: ContentBlock) => {}
} = $props<{
block: ContentBlock;
onChange?: (b: ContentBlock) => void;
}>();
function updateData(patch: Partial<CheckoutBlockData>) {
onChange({ ...block, data: { ...block.data, ...patch } });
}
</script>
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Heading</span></div>
<input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Notes label</span></div>
<input class="input input-bordered w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} />
</label>
<p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p>
</div>

View file

@ -0,0 +1,90 @@
<script lang="ts">
import type { EmailBlock, EmailBlockType } from '$lib/types';
import { emailBlockLabels } from '$lib/admin/emailBlockDefaults';
import RichTextEditor from './RichTextEditor.svelte';
import ImageUploader from './ImageUploader.svelte';
import SegmentedControl from './SegmentedControl.svelte';
let { block, primaryColor = '#8a9a7b', onChange = (block: EmailBlock) => {} } = $props<{
block: EmailBlock | null;
primaryColor?: string;
onChange?: (block: EmailBlock) => void;
}>();
function updateData(patch: Record<string, any>) {
if (!block) return;
block = { ...block, data: { ...block.data, ...patch } };
onChange(block);
}
function titleCase(value: string | number) {
const text = String(value);
return text.charAt(0).toUpperCase() + text.slice(1);
}
const autoFilled: Record<string, string> = {
booking_details: 'Filled in automatically with the booked services, date and time, prices and the total paid.',
customer_details: "Filled in automatically with the customer's name, email, phone and checkout notes.",
contact_info: 'Filled in automatically from the business name, address, phone and email in Globals → Footer.'
};
</script>
{#if !block}
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div>
{:else}
<div class="rounded-box bg-base-100 p-5 shadow">
<h2 class="mb-4 text-2xl font-bold">{emailBlockLabels[block.type as EmailBlockType]}</h2>
{#if block.type === 'text'}
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
<p class="mt-2 text-sm text-base-content/60">Use placeholders like <code>{'{{customer_first_name}}'}</code> — see the list above.</p>
{:else if block.type === 'image'}
<div class="space-y-4">
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
<SegmentedControl label="Width" options={[100, 75, 50, 25]} value={Number(block.data.width) || 100} onChange={(v) => updateData({ width: v })} formatLabel={(v) => `${v}%`} />
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} formatLabel={titleCase} />
<label class="form-control w-full">
<div class="label"><span class="label-text">Link (optional)</span></div>
<input class="input input-bordered w-full" placeholder="https://… or /page" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
</label>
<p class="text-sm text-base-content/60">Images load from the public media server, so they only appear in real inboxes once the site runs on a public domain.</p>
</div>
{:else if block.type === 'button'}
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Button label</span></div>
<input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">URL</span></div>
<input class="input input-bordered w-full" placeholder={'https://…, /page or {{site_url}}'} value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
</label>
<SegmentedControl label="Alignment" options={['left', 'center', 'right']} value={block.data.alignment || 'center'} onChange={(v) => updateData({ alignment: v })} formatLabel={titleCase} />
<div class="form-control">
<div class="flex items-center justify-between">
<span class="label-text w-24">Color</span>
<div class="flex flex-1 items-center gap-2">
<input class="input input-bordered h-10 w-10 cursor-pointer p-1" type="color" value={block.data.color || primaryColor} oninput={(e) => updateData({ color: e.currentTarget.value })} />
<input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
</div>
</div>
</div>
</div>
{:else if block.type === 'spacer'}
<label class="form-control w-full">
<div class="label"><span class="label-text">Height (px)</span></div>
<input type="number" min="0" class="input input-bordered w-full" value={block.data.height ?? 24} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 0 })} />
</label>
{:else if block.type === 'divider'}
<p class="text-base-content/60">A thin horizontal line. No settings.</p>
{:else}
<div class="space-y-3">
<label class="form-control w-full">
<div class="label"><span class="label-text">Section title</span></div>
<input class="input input-bordered w-full" placeholder="Leave empty for no title" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<p class="text-sm text-base-content/60">{autoFilled[block.type]}</p>
</div>
{/if}
</div>
{/if}

View file

@ -0,0 +1,79 @@
<script lang="ts">
import type { ContentBlock, ShopBlockData } from '$lib/types';
import SegmentedControl from './SegmentedControl.svelte';
let {
block,
items = [],
onChange = (b: ContentBlock) => {}
} = $props<{
block: ContentBlock;
items?: { id: string; name: string; type: string }[];
onChange?: (b: ContentBlock) => void;
}>();
function updateData(patch: Partial<ShopBlockData>) {
onChange({ ...block, data: { ...block.data, ...patch } });
}
function toggleItem(id: string) {
const current: string[] = block.data.itemIds || [];
updateData({
itemIds: current.includes(id)
? current.filter((itemId) => itemId !== id)
: [...current, id]
});
}
const typeFilterLabels: Record<string, string> = {
all: 'All',
item: 'Products',
item_with_time: 'Services'
};
</script>
<div class="space-y-4">
<label class="form-control w-full">
<div class="label"><span class="label-text">Title</span></div>
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
</label>
<SegmentedControl
label="Layout"
options={['grid', 'list']}
value={block.data.layout || 'grid'}
onChange={(v) => updateData({ layout: v as 'grid' | 'list' })}
formatLabel={(v) => String(v).charAt(0).toUpperCase() + String(v).slice(1)}
/>
<SegmentedControl
label="Item type"
options={['all', 'item', 'item_with_time']}
value={block.data.itemTypeFilter || 'all'}
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
/>
{#if items.length}
<div class="rounded-box border border-base-300 p-4">
<div class="mb-3">
<h3 class="font-semibold">Items</h3>
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
</div>
<div class="flex flex-wrap gap-2">
{#each items as item}
<button
type="button"
class="btn btn-xs"
class:btn-primary={(block.data.itemIds || []).includes(item.id)}
onclick={() => toggleItem(item.id)}
>
{item.name}
</button>
{/each}
</div>
</div>
{:else}
<p class="text-sm text-base-content/60">No items yet — create some under Items in the admin.</p>
{/if}
</div>

View file

@ -0,0 +1,43 @@
import { v4 as uuid } from 'uuid';
import type { EmailBlock, EmailBlockType } from '$lib/types';
export const emailBlockLabels: Record<EmailBlockType, string> = {
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: '<p>Hi {{customer_first_name}},</p><p>Add your message here.</p>' };
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;
}

View file

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Before After
Before After

View file

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

View file

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

View file

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

15
app-admin/src/lib/pb.ts Normal file
View file

@ -0,0 +1,15 @@
export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb';
// App-specific: admin uploads go through the admin upload endpoint.
export async function uploadMedia(file: File) {
const formData = new FormData();
formData.append('file', file);
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.message || `Upload failed (${res.status})`);
}
return res.json();
}

View file

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

View file

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

View file

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

View file

@ -0,0 +1 @@
export * from '$shared/stripe-client';

View file

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

View file

@ -0,0 +1,16 @@
import { defaultColors } from '$lib/types';
import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback;
} catch {
return fallback;
}
}
export const load: LayoutServerLoad = async ({ locals }) => {
const colors = await getGlobal(locals.pb, 'colors', defaultColors);
return { user: locals.user, colors };
};

View file

@ -1,11 +1,22 @@
<script lang="ts"> <script lang="ts">
let { children } = $props(); import '../app.css';
import favicon from '$lib/assets/favicon.svg';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { onMount } from 'svelte';
let { children, data } = $props();
let importStatus = $state<{ ok: boolean; message: string } | null>(null); let importStatus = $state<{ ok: boolean; message: string } | null>(null);
let importing = $state(false); let importing = $state(false);
// One basket store per layout instance — provided to all children
// (preview iframe block renderers). Never module-level state.
// Admin doesn't have a real basket; pass null so the store starts empty.
const basketStore = createBasketStore(null);
setBasketContext(basketStore);
async function handleExport() { async function handleExport() {
try { try {
const res = await fetch('/admin/api/export'); const res = await fetch('/api/export');
if (!res.ok) throw new Error(`Export failed (${res.status})`); if (!res.ok) throw new Error(`Export failed (${res.status})`);
const blob = await res.blob(); const blob = await res.blob();
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
@ -29,7 +40,7 @@
try { try {
const text = await file.text(); const text = await file.text();
const json = JSON.parse(text); const json = JSON.parse(text);
const res = await fetch('/admin/api/import', { const res = await fetch('/api/import', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(json) body: JSON.stringify(json)
@ -49,17 +60,39 @@
input.value = ''; input.value = '';
} }
} }
onMount(() => {
// Apply saved colors so the preview iframe matches the public site.
if (data.colors) {
const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading);
root.style.setProperty('--color-subheading', data.colors.subheading);
root.style.setProperty('--color-text', data.colors.text);
root.style.setProperty('--color-primary', data.colors.primary);
root.style.setProperty('--color-accent', data.colors.accent);
}
});
</script> </script>
<svelte:head>
<link rel="icon" href={favicon} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</svelte:head>
<div class="min-h-screen bg-base-200"> <div class="min-h-screen bg-base-200">
<div class="navbar bg-base-100 shadow-sm"> <div class="navbar bg-base-100 shadow-sm">
<div class="flex-1"> <div class="flex-1">
<a class="btn btn-ghost text-xl" href="/admin/pages">Massage CMS</a> <a class="btn btn-ghost text-xl" href="/pages">Massage CMS</a>
</div> </div>
<div class="flex-none gap-2"> <div class="flex-none gap-2">
<a class="btn btn-ghost" href="/admin/pages">Pages</a> <a class="btn btn-ghost" href="/pages">Pages</a>
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a> <a class="btn btn-ghost" href="/calendar">Calendar</a>
<a class="btn btn-ghost" href="/admin/globals">Globals</a> <a class="btn btn-ghost" href="/items">Items</a>
<a class="btn btn-ghost" href="/slots">Slots</a>
<a class="btn btn-ghost" href="/orders">Orders</a>
<a class="btn btn-ghost" href="/emails">Emails</a>
<a class="btn btn-ghost" href="/globals">Globals</a>
<div class="dropdown dropdown-end"> <div class="dropdown dropdown-end">
<button class="btn btn-ghost btn-sm" type="button" tabindex="0"> <button class="btn btn-ghost btn-sm" type="button" tabindex="0">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg> <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
@ -75,7 +108,7 @@
</ul> </ul>
</div> </div>
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} /> <input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
<form class="inline" method="POST" action="/admin/login?/logout"> <form class="inline" method="POST" action="/login?/logout">
<button class="btn btn-outline btn-sm" type="submit">Logout</button> <button class="btn btn-outline btn-sm" type="submit">Logout</button>
</form> </form>
</div> </div>

View file

@ -1,3 +1,4 @@
import { env } from '$env/dynamic/private';
import { json } from '@sveltejs/kit'; import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { import {
@ -26,12 +27,20 @@ export const GET: RequestHandler = async ({ locals }) => {
for (const url of extractImageUrls(g)) allUrls.add(url); for (const url of extractImageUrls(g)) allUrls.add(url);
} }
// Fetch each image as base64 // Fetch each image as base64. Stored image URLs may use any public host
// (e.g. http://localhost:8080 from before a domain migration, or
// http://db.localhost:8080 after). The app container can only reach
// PocketBase via the internal Docker network URL, so rewrite the host
// of every matched URL to the internal base.
const internalBase = env.POCKETBASE_INTERNAL_URL!;
const images: Record<string, string> = {}; const images: Record<string, string> = {};
for (const url of allUrls) { for (const url of allUrls) {
try { try {
// Replace the host (and optional port) with the internal base.
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
const key = urlToKey(url); const key = urlToKey(url);
images[key] = await fetchImageAsBase64(url); images[key] = await fetchImageAsBase64(fetchUrl);
} catch (e) { } catch (e) {
console.warn(`Could not fetch image: ${url}`, e); console.warn(`Could not fetch image: ${url}`, e);
} }

View file

@ -37,7 +37,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' ')); formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData); const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080'; const publicUrl = env.PUBLIC_POCKETBASE_URL;
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl); keyToUrl.set(key, newUrl);

View file

@ -17,11 +17,13 @@ export const POST: RequestHandler = async ({ request, locals }) => {
try { try {
const record = await locals.pb.collection('media').create(uploadForm); const record = await locals.pb.collection('media').create(uploadForm);
const publicUrl = env.PUBLIC_POCKETBASE_URL || 'http://localhost:8080'; const publicUrl = env.PUBLIC_POCKETBASE_URL;
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`; const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
return json({ record, url }); return json({ record, url });
} catch (e) { } catch (e) {
console.error('Media upload error:', e); console.error('Media upload error:', e);
throw error(500, 'Upload failed'); // Surface PocketBase's field validation message (e.g. file too large, wrong type)
const fieldError = (e as { response?: { data?: Record<string, { message?: string }> } })?.response?.data?.file?.message;
throw error(fieldError ? 400 : 500, fieldError ? `Upload failed: ${fieldError}` : 'Upload failed');
} }
}; };

View file

@ -0,0 +1,21 @@
import { emailTemplateKeys, emailTemplateMeta } from '$lib/email';
import { emailSender, isEmailConfigured, loadEmailSettings, loadEmailTemplate } from '$lib/server/email';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
const settings = await loadEmailSettings(locals.pb);
const templates = await Promise.all(
emailTemplateKeys.map(async (key) => {
const template = await loadEmailTemplate(locals.pb, key);
return {
key,
...emailTemplateMeta[key],
subject: template.subject,
enabled: template.enabled,
customised: Boolean(template.id),
recipients: key === 'customer_confirmation' ? 'The customer' : template.recipients || settings.business.email || ''
};
})
);
return { templates, smtpConfigured: isEmailConfigured(), sender: emailSender() };
};

View file

@ -0,0 +1,39 @@
<script lang="ts">
let { data } = $props();
</script>
<svelte:head><title>Emails | CMS</title></svelte:head>
<div class="space-y-6">
<div>
<h1 class="text-3xl font-bold">Emails</h1>
<p class="text-base-content/60">Automatic emails sent after a successful booking.</p>
</div>
{#if !data.smtpConfigured}
<div class="alert alert-warning">
<span>Email sending is not configured (<code>SMTP_HOST</code> is empty), so emails are only written to the server log. See the README for the Brevo setup.</span>
</div>
{:else}
<p class="text-sm text-base-content/60">Sending as <strong>{data.sender || 'EMAIL_FROM is not set!'}</strong></p>
{/if}
<div class="grid gap-4 md:grid-cols-2">
{#each data.templates as template}
<a class="rounded-box bg-base-100 p-5 shadow transition hover:shadow-md" href="/emails/{template.key}">
<div class="flex items-start justify-between gap-3">
<h2 class="text-xl font-bold">{template.label}</h2>
<div class="flex gap-2">
{#if !template.customised}<span class="badge badge-ghost">Default</span>{/if}
<span class="badge" class:badge-success={template.enabled} class:badge-error={!template.enabled}>{template.enabled ? 'On' : 'Off'}</span>
</div>
</div>
<p class="mt-2 text-sm text-base-content/60">{template.description}</p>
<dl class="mt-4 space-y-1 text-sm">
<div><dt class="inline font-semibold">To:</dt> <dd class="inline">{template.recipients || '— no recipient set —'}</dd></div>
<div><dt class="inline font-semibold">Subject:</dt> <dd class="inline">{template.subject}</dd></div>
</dl>
</a>
{/each}
</div>
</div>

View file

@ -0,0 +1,116 @@
import { error, fail, redirect } from '@sveltejs/kit';
import { emailTemplateMeta, isEmailTemplateKey } from '$lib/email';
import { isEmailConfigured, loadEmailSettings, loadEmailTemplate, sendTestEmail } from '$lib/server/email';
import type { EmailBlock } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
function parseBlocks(raw: FormDataEntryValue | null): EmailBlock[] | null {
try {
const blocks = JSON.parse(String(raw || '[]'));
return Array.isArray(blocks) ? blocks : null;
} catch {
return null;
}
}
/** A real bookable service for the sample booking in previews and test emails. */
async function findSampleService(pb: App.Locals['pb']) {
return pb
.collection('items')
.getFirstListItem("type = 'item_with_time' && active = true", { sort: 'name' })
.then((item) => ({ name: String(item.name), price: Number(item.price) || 0, duration: Number(item.duration) || null }))
.catch(() => undefined);
}
export const load: PageServerLoad = async ({ params, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const key = params.key;
const [template, settings, service] = await Promise.all([
loadEmailTemplate(locals.pb, key),
loadEmailSettings(locals.pb),
findSampleService(locals.pb)
]);
return {
key,
meta: emailTemplateMeta[key],
template: { subject: template.subject, blocks: template.blocks, recipients: template.recipients, enabled: template.enabled },
customised: Boolean(template.id),
settings,
service,
smtpConfigured: isEmailConfigured(),
userEmail: String(locals.user?.email || '')
};
};
export const actions: Actions = {
save: async ({ params, request, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const data = await request.formData();
const blocks = parseBlocks(data.get('blocks'));
if (!blocks) return fail(400, { action: 'save', ok: false, message: 'Invalid blocks data.' });
const subject = String(data.get('subject') || '').trim();
if (!subject) return fail(400, { action: 'save', ok: false, message: 'Subject is required.' });
const recipients = String(data.get('recipients') || '').trim();
const invalid = recipients
.split(',')
.map((address) => address.trim())
.filter((address) => address && !EMAIL_RE.test(address));
if (invalid.length) return fail(400, { action: 'save', ok: false, message: `Invalid recipient address: ${invalid.join(', ')}` });
const payload = { key: params.key, subject, blocks, recipients, enabled: data.get('enabled') === 'true' };
const existing = await loadEmailTemplate(locals.pb, params.key);
try {
if (existing.id) await locals.pb.collection('email_templates').update(existing.id, payload);
else await locals.pb.collection('email_templates').create(payload);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
return fail(500, {
action: 'save',
ok: false,
message: `Could not save: ${message}. Has the email_templates collection been imported from pb_schema.json?`
});
}
return { action: 'save', ok: true, message: 'Saved.' };
},
test: async ({ params, request, locals }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const data = await request.formData();
const to = String(data.get('to') || '').trim();
if (!EMAIL_RE.test(to)) return fail(400, { action: 'test', ok: false, message: 'Enter a valid email address.' });
const blocks = parseBlocks(data.get('blocks'));
if (!blocks) return fail(400, { action: 'test', ok: false, message: 'Invalid blocks data.' });
try {
const result = await sendTestEmail(
locals.pb,
{ key: params.key, subject: String(data.get('subject') || ''), blocks },
to,
await findSampleService(locals.pb)
);
return {
action: 'test',
ok: true,
message:
result.status === 'sent'
? `Test email sent to ${to}.`
: 'SMTP is not configured — the email was written to the app-admin log instead of being sent.'
};
} catch (e) {
return fail(502, { action: 'test', ok: false, message: `Sending failed: ${e instanceof Error ? e.message : String(e)}` });
}
},
reset: async ({ params, locals, url }) => {
if (!isEmailTemplateKey(params.key)) throw error(404, 'Unknown email template');
const existing = await loadEmailTemplate(locals.pb, params.key);
if (existing.id) await locals.pb.collection('email_templates').delete(existing.id);
throw redirect(303, url.pathname);
}
};

View file

@ -0,0 +1,232 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { beforeNavigate } from '$app/navigation';
import BlockList from '$lib/admin/BlockList.svelte';
import EmailBlockEditor from '$lib/admin/editors/EmailBlockEditor.svelte';
import { createEmailBlock, emailBlockLabels, emailBlockTypes } from '$lib/admin/emailBlockDefaults';
import { emailPlaceholders, renderEmail, sampleEmailContext } from '$lib/email';
import type { EmailBlock, EmailBlockType } from '$lib/types';
let { data, form } = $props();
let subject = $state(data.template.subject);
let recipients = $state(data.template.recipients);
let enabled = $state(data.template.enabled);
let blocks = $state<EmailBlock[]>(structuredClone(data.template.blocks));
let selectedId = $state(blocks[0]?.id || '');
let previewMode = $state<'desktop' | 'mobile'>('desktop');
let previewFormat = $state<'html' | 'text'>('html');
let testTo = $state(data.userEmail);
let saving = $state(false);
let testing = $state(false);
let copied = $state('');
const serialize = () => JSON.stringify({ subject, recipients, enabled, blocks });
let savedSnapshot = $state(serialize());
let dirty = $derived(serialize() !== savedSnapshot);
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
let context = $derived(sampleEmailContext({ ...data.settings, service: data.service }));
let rendered = $derived(renderEmail({ subject, blocks }, context));
let isAlert = $derived(data.key === 'client_alert');
beforeNavigate(({ cancel, type }) => {
if (dirty && type !== 'form' && !confirm('You have unsaved changes. Leave anyway?')) cancel();
});
function addBlock(type: EmailBlockType) {
const block = createEmailBlock(type);
blocks = [...blocks, block];
selectedId = block.id;
}
function updateBlock(updated: EmailBlock) {
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
}
function deleteBlock(id: string) {
blocks = blocks.filter((block) => block.id !== id);
if (selectedId === id) selectedId = blocks[0]?.id || '';
}
function moveBlock(from: number, to: number) {
const copy = [...blocks];
const [item] = copy.splice(from, 1);
copy.splice(to, 0, item);
blocks = copy;
}
async function copyPlaceholder(key: string) {
await navigator.clipboard?.writeText(`{{${key}}}`).catch(() => {});
copied = key;
setTimeout(() => (copied = ''), 1200);
}
</script>
<svelte:head><title>{data.meta.label} | Emails | CMS</title></svelte:head>
<div class="space-y-6">
<form
method="POST"
action="?/save"
class="space-y-6"
use:enhance={() => {
saving = true;
const snapshot = serialize();
return async ({ result, update }) => {
saving = false;
if (result.type === 'success') savedSnapshot = snapshot;
await update({ reset: false });
};
}}
>
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<input type="hidden" name="enabled" value={String(enabled)} />
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<a class="link link-hover text-sm text-base-content/60" href="/emails">← Emails</a>
<h1 class="text-3xl font-bold">{data.meta.label}</h1>
<p class="text-base-content/60">{data.meta.description}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
{#if dirty}<span class="badge badge-warning">Unsaved changes</span>{/if}
<button class="btn btn-primary" type="submit" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
</div>
</div>
{#if form?.action === 'save' && form.message}
<div class="alert" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if}
<div class="rounded-box space-y-4 bg-base-100 p-5 shadow">
<label class="label cursor-pointer justify-start gap-3">
<input type="checkbox" class="toggle toggle-primary" bind:checked={enabled} />
<span class="label-text">{enabled ? 'This email is sent automatically' : 'This email is turned off'}</span>
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Subject</span></div>
<input class="input input-bordered w-full" name="subject" bind:value={subject} />
</label>
{#if isAlert}
<label class="form-control w-full">
<div class="label"><span class="label-text">Send to (comma-separated)</span></div>
<input class="input input-bordered w-full" name="recipients" placeholder={data.settings.business.email || 'you@example.com'} bind:value={recipients} />
<div class="label">
<span class="label-text-alt text-base-content/60">
{#if data.settings.business.email}Leave empty to use the footer email ({data.settings.business.email}).{:else}No footer email is set — enter at least one address.{/if}
</span>
</div>
</label>
{:else}
<input type="hidden" name="recipients" value="" />
<p class="text-sm text-base-content/60">Sent to the email address the customer entered at checkout. Replies go to {data.settings.business.email || 'the footer email (not set yet)'}.</p>
{/if}
<details class="collapse collapse-arrow border border-base-300">
<summary class="collapse-title font-semibold">Placeholders</summary>
<div class="collapse-content">
<p class="mb-3 text-sm text-base-content/60">Type these into the subject or any text block; they're replaced with the booking's details. Click one to copy it.</p>
<div class="grid gap-2 sm:grid-cols-2">
{#each emailPlaceholders as placeholder}
<button type="button" class="btn btn-ghost btn-sm justify-start font-normal" onclick={() => copyPlaceholder(placeholder.key)}>
<code class="text-primary">{`{{${placeholder.key}}}`}</code>
<span class="text-base-content/60">{copied === placeholder.key ? 'Copied!' : placeholder.description}</span>
</button>
{/each}
</div>
</div>
</details>
</div>
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
<aside class="space-y-4">
<div class="rounded-box bg-base-100 p-4 shadow">
<div class="dropdown w-full">
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
{#each emailBlockTypes as type}
<li><button type="button" onclick={() => addBlock(type)}>{emailBlockLabels[type]}</button></li>
{/each}
</ul>
</div>
</div>
<BlockList {blocks} labels={emailBlockLabels} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside>
<EmailBlockEditor block={selectedBlock} primaryColor={data.settings.colors.primary} onChange={updateBlock} />
</div>
</form>
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-3 flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div>
<h2 class="text-xl font-bold">Preview</h2>
<p class="text-sm text-base-content/60">With a sample booking. <strong>Subject:</strong> {rendered.subject}</p>
</div>
<div class="flex gap-2">
<div class="join">
<button type="button" class="btn btn-sm join-item" class:btn-active={previewFormat === 'html'} onclick={() => (previewFormat = 'html')}>Formatted</button>
<button type="button" class="btn btn-sm join-item" class:btn-active={previewFormat === 'text'} onclick={() => (previewFormat = 'text')}>Plain text</button>
</div>
<div class="join">
<button type="button" class="btn btn-sm join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button>
<button type="button" class="btn btn-sm join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button>
</div>
</div>
</div>
{#if previewFormat === 'html'}
<iframe
class="mx-auto block h-[48rem] rounded-box border border-base-300 bg-white"
class:w-full={previewMode === 'desktop'}
style={previewMode === 'mobile' ? 'width: 390px;' : ''}
sandbox=""
srcdoc={rendered.html}
title="Email preview"
></iframe>
{:else}
<pre class="max-h-[48rem] overflow-auto whitespace-pre-wrap rounded-box border border-base-300 bg-base-200 p-4 text-sm">{rendered.text}</pre>
{/if}
</div>
<form
method="POST"
action="?/test"
class="rounded-box space-y-3 bg-base-100 p-5 shadow"
use:enhance={() => {
testing = true;
return async ({ update }) => {
testing = false;
await update({ reset: false, invalidateAll: false });
};
}}
>
<h2 class="text-xl font-bold">Send a test email</h2>
<p class="text-sm text-base-content/60">Sends the current (unsaved) version with the sample booking{data.key === 'customer_confirmation' ? ', including the calendar attachment' : ''}.</p>
{#if !data.smtpConfigured}
<div class="alert alert-warning text-sm">SMTP is not configured, so the test email will only be written to the server log.</div>
{/if}
<input type="hidden" name="subject" value={subject} />
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
<div class="flex flex-col gap-2 sm:flex-row">
<input class="input input-bordered flex-1" type="email" name="to" placeholder="you@example.com" bind:value={testTo} required />
<button class="btn" type="submit" disabled={testing}>{testing ? 'Sending…' : 'Send test'}</button>
</div>
{#if form?.action === 'test' && form.message}
<div class="alert text-sm" class:alert-success={form.ok} class:alert-error={!form.ok}>{form.message}</div>
{/if}
</form>
{#if data.customised}
<form
method="POST"
action="?/reset"
class="text-right"
onsubmit={(e) => {
if (!confirm('Replace this email with the built-in default? Your changes will be lost.')) e.preventDefault();
}}
>
<button class="btn btn-ghost btn-sm text-error" type="submit">Reset to default</button>
</form>
{/if}
</div>

View file

@ -0,0 +1,74 @@
import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb';
import type { ItemRecord, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
function itemPayload(data: FormData) {
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
return {
name: String(data.get('name') || '').trim(),
description: String(data.get('description') || '').trim(),
price: parseFloat(String(data.get('price') || '')),
image: String(data.get('image') || '').trim(),
type,
stock: Number.isNaN(stock) ? null : stock,
duration: Number.isNaN(duration) ? null : duration,
active: String(data.get('active')) === 'true'
};
}
function normalizeItem(record: Record<string, any>): ItemRecord {
const media = record.expand?.image;
return {
id: record.id,
name: String(record.name || ''),
description: String(record.description || ''),
price: Number(record.price) || 0,
image: String(record.image || ''),
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type === 'item_with_time' ? 'item_with_time' : 'item',
stock: record.stock ?? null,
duration: record.duration ?? null,
active: record.active !== false
};
}
export const load: PageServerLoad = async ({ locals }) => {
const records = await locals.pb
.collection('items')
.getFullList({ sort: 'name', expand: 'image' })
.catch(() => []);
const items = records.map((record) => normalizeItem(record));
return { items };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const payload = itemPayload(data);
if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
await locals.pb.collection('items').create(payload);
return { ok: true };
},
update: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' });
if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
await locals.pb.collection('items').update(id, payload);
return { ok: true };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' });
await locals.pb.collection('items').delete(id);
return { ok: true };
}
};

View file

@ -0,0 +1,199 @@
<script lang="ts">
import type { ItemRecord, ItemType } from '$lib/types';
let { data, form } = $props();
let items = $derived(data.items || []);
let showEditor = $state(false);
let uploading = $state(false);
type ItemDraft = {
id: string;
name: string;
description: string;
price: number;
image: string;
imageUrl: string;
type: ItemType;
stock: string;
duration: string;
active: boolean;
};
let draft = $state<ItemDraft>(emptyDraft());
let action = $derived(draft.id ? '?/update' : '?/create');
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true };
}
function createItem() {
draft = emptyDraft();
showEditor = true;
}
function editItem(item: ItemRecord) {
draft = {
id: item.id,
name: item.name,
description: item.description,
price: item.price,
image: item.image,
imageUrl: item.imageUrl,
type: item.type,
stock: item.stock == null ? '' : String(item.stock),
duration: item.duration == null ? '' : String(item.duration),
active: item.active
};
showEditor = true;
}
async function onImageSelected(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
uploading = true;
try {
const formData = new FormData();
formData.append('file', file);
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
const result = await res.json();
draft = { ...draft, image: result.record.id, imageUrl: result.url };
} catch (err) {
console.error(err);
} finally {
uploading = false;
input.value = '';
}
}
</script>
<svelte:head><title>Items | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Items</h1>
<p class="text-base-content/60">Manage services and products shown in Shop blocks.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Create item</button>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each items as item}
<tr>
<td>
<div class="flex items-center gap-3">
{#if item.imageUrl}
<img class="h-10 w-10 rounded-box object-cover" src={item.imageUrl} alt="" />
{/if}
<span class="font-semibold">{item.name}</span>
</div>
</td>
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{eur.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '—') : '—'}</td>
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td>
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div>
{#if showEditor}
<div class="fixed inset-0 z-50 bg-black/50 p-4">
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-2xl font-bold">{draft.id ? 'Edit item' : 'Create item'}</h2>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<form method="POST" action={action} class="space-y-4">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
<label class="form-control w-full">
<div class="label"><span class="label-text">Name</span></div>
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Description</span></div>
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
</label>
<div class="grid gap-4 md:grid-cols-2">
<label class="form-control w-full">
<div class="label"><span class="label-text">Price</span></div>
<input class="input input-bordered w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Type</span></div>
<select class="select select-bordered w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service</option>
</select>
</label>
</div>
{#if draft.type === 'item'}
<label class="form-control w-full">
<div class="label"><span class="label-text">Stock</span></div>
<input class="input input-bordered w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
{:else}
<label class="form-control w-full">
<div class="label"><span class="label-text">Duration minutes</span></div>
<input class="input input-bordered w-full" type="number" min="0" step="1" name="duration" placeholder="60" bind:value={draft.duration} />
</label>
{/if}
<div class="form-control w-full">
<div class="label"><span class="label-text">Image</span></div>
<div class="flex items-start gap-3">
{#if draft.imageUrl}
<img class="h-16 w-16 rounded-box object-cover" src={draft.imageUrl} alt="" />
{/if}
<div class="flex-1 space-y-2">
<input class="input input-bordered w-full" name="image" placeholder="Media record id" bind:value={draft.image} />
<input class="file-input file-input-bordered file-input-sm w-full" type="file" accept="image/*" disabled={uploading} onchange={onImageSelected} />
<p class="text-xs text-base-content/60">
{uploading ? 'Uploading…' : 'Upload a file or paste a media record id. A media picker will replace this in a later iteration.'}
</p>
</div>
</div>
</div>
<label class="label cursor-pointer justify-start gap-3">
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} />
<span class="label-text">Active</span>
</label>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save item</button>
</div>
</div>
</form>
</div>
</div>
{/if}

View file

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

View file

@ -0,0 +1,61 @@
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
// autodate fields. PocketBase ids are time-sortable ULIDs.
const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []);
const orders = [];
for (const record of records) {
const lineRecords = await locals.pb
.collection('order_lines')
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) })
.catch(() => []);
orders.push({
id: record.id,
email: String(record.email || ''),
customerDetails: record.customerDetails || {},
total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
lines: lineRecords.map((line) => ({
id: line.id,
name: String(line.name || ''),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : ''
}))
});
}
return { orders };
};
const OUTCOME_MESSAGES: Record<string, string> = {
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]}.` };
}
};

View file

@ -0,0 +1,96 @@
<script lang="ts">
import { enhance } from '$app/forms';
let { data, form } = $props();
let orders = $derived(data.orders || []);
let resending = $state('');
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
</script>
{#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)}
<form
method="POST"
action="?/resend"
class="flex items-center gap-2"
use:enhance={() => {
resending = `${order.id}-${kind}`;
return async ({ update }) => {
resending = '';
await update();
};
}}
>
<input type="hidden" name="orderId" value={order.id} />
<input type="hidden" name="kind" value={kind} />
<span class="badge badge-sm" class:badge-success={sentAt} class:badge-ghost={!sentAt} title={sentAt ? new Date(sentAt).toLocaleString() : 'Not sent'}>
{label}: {sentAt ? 'sent' : 'not sent'}
</span>
<button class="btn btn-ghost btn-xs" type="submit" disabled={resending !== ''}>
{resending === `${order.id}-${kind}` ? 'Sending…' : sentAt ? 'Resend' : 'Send'}
</button>
</form>
{/snippet}
<svelte:head><title>Orders | CMS</title></svelte:head>
<div class="space-y-6">
<div>
<h1 class="text-3xl font-bold">Orders</h1>
<p class="text-base-content/60">Confirmed bookings and purchases.</p>
</div>
{#if orders.length === 0}
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">No orders yet.</div>
{/if}
{#each orders as order}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div>
<h2 class="text-xl font-bold">{order.customerDetails?.name || order.email || 'Order'}</h2>
<p class="text-sm text-base-content/60">
{order.email}
{#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if}
{#if order.created} · {new Date(order.created).toLocaleString()}{/if}
</p>
</div>
<div class="flex items-center gap-3">
<span
class="badge capitalize"
class:badge-success={order.status === 'paid'}
class:badge-warning={order.status === 'pending'}
class:badge-error={order.status === 'refunded'}
>{order.status}</span>
<span class="text-lg font-bold">{eur.format(order.total)}</span>
</div>
</div>
<ul class="mt-4 space-y-1 border-t border-base-300 pt-4">
{#each order.lines as line}
<li>
{line.quantity}× {line.name} — {eur.format(line.price)}
{#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{new Date(line.start).toLocaleString()}</span>
{/if}
</li>
{/each}
</ul>
{#if order.customerDetails?.notes}
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
{/if}
<div class="mt-4 flex flex-wrap gap-x-6 gap-y-2 border-t border-base-300 pt-3">
{@render emailStatus(order, 'customer', 'Confirmation', order.customerEmailSentAt)}
{@render emailStatus(order, 'client', 'Alert', order.clientEmailSentAt)}
</div>
{#if order.emailError}
<p class="mt-2 whitespace-pre-line text-sm text-error">{order.emailError}</p>
{/if}
{#if form?.orderId === order.id && form.message}
<div class="alert mt-2 py-2 text-sm" class:alert-success={form.ok} class:alert-warning={!form.ok}>{form.message}</div>
{/if}
</div>
{/each}
</div>

View file

@ -14,7 +14,7 @@ export const actions: Actions = {
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false }); await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
throw redirect(303, `/admin/pages/${slug}`); throw redirect(303, `/pages/${slug}`);
}, },
toggle: async ({ request, locals }) => { toggle: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();

View file

@ -28,8 +28,8 @@
<td>{page.title}</td> <td>{page.title}</td>
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td> <td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
<td class="flex justify-end gap-2"> <td class="flex justify-end gap-2">
<a class="btn btn-sm" href={`/admin/pages/${page.slug}`}>Edit</a> <a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
<a class="btn btn-sm" href={page.slug === 'home' ? '/' : `/${page.slug}`} target="_blank">Preview</a> <a class="btn btn-sm" href={`${import.meta.env.VITE_PUBLIC_SITE_URL}/${page.slug === 'home' ? '' : page.slug}`} target="_blank">Preview</a>
<form method="POST" action="?/toggle"> <form method="POST" action="?/toggle">
<input type="hidden" name="id" value={page.id} /> <input type="hidden" name="id" value={page.id} />
<input type="hidden" name="published" value={page.published} /> <input type="hidden" name="published" value={page.published} />

View file

@ -6,7 +6,12 @@ export const load: PageServerLoad = async ({ params, locals }) => {
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`); const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event))); const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
return { page, eventCategories }; const items = await locals.pb
.collection('items')
.getFullList({ sort: 'name' })
.then((records) => records.map(({ id, name, type }) => ({ id, name, type })))
.catch(() => []);
return { page, eventCategories, items };
}; };
export const actions: Actions = { export const actions: Actions = {
@ -20,6 +25,6 @@ export const actions: Actions = {
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) }); await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
throw redirect(303, `/admin/pages/${slug}`); throw redirect(303, `/pages/${slug}`);
} }
}; };

View file

@ -87,7 +87,7 @@
</div> </div>
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} /> <BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
</aside> </aside>
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} onChange={updateBlock} /> <BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} />
</div> </div>
</form> </form>

View file

@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte'; import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
import type { ContentBlock } from '$lib/types'; import type { ContentBlock } from '$lib/types';
let blocks = $state<ContentBlock[]>([]); let blocks = $state<ContentBlock[]>([]);

View file

@ -0,0 +1,96 @@
import { fail } from '@sveltejs/kit';
import type { createPocketBase } from '$lib/pb';
import type { SlotStatus } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>;
type SlotPayload =
| { payload: { item: string; start: string; end: string; status: string; notes: string } }
| { error: string };
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const itemId = String(data.get('item') || '').trim();
const startValue = String(data.get('start') || '').trim();
const status = String(data.get('status') || 'available').trim();
const notes = String(data.get('notes') || '').trim();
if (!itemId || !startValue) return { error: 'Service and start are required.' };
const start = new Date(startValue);
if (Number.isNaN(start.getTime())) return { error: 'Invalid start time.' };
let item: Record<string, any>;
try {
item = await pb.collection('items').getOne(itemId);
} catch {
return { error: 'Selected service was not found.' };
}
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' };
const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000);
return {
payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), status, notes }
};
}
export const load: PageServerLoad = async ({ locals }) => {
const itemRecords = await locals.pb
.collection('items')
.getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' })
.catch(() => []);
const items = itemRecords.map((record) => ({
id: record.id,
name: String(record.name || ''),
duration: record.duration ?? 0
}));
const slotRecords = await locals.pb
.collection('slots')
.getFullList({ sort: '-start', expand: 'item' })
.catch(() => []);
const slots = slotRecords.map((record) => ({
id: record.id,
item: String(record.item || ''),
itemName: String(record.expand?.item?.name || 'Unknown service'),
itemDuration: record.expand?.item?.duration ?? null,
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
status: String(record.status || 'available') as SlotStatus,
heldUntil: record.heldUntil ? String(record.heldUntil) : '',
order: record.order ? String(record.order) : '',
notes: String(record.notes || '')
}));
return { items, slots };
};
export const actions: Actions = {
create: async ({ request, locals }) => {
const data = await request.formData();
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
await locals.pb.collection('slots').create(result.payload);
return { ok: true };
},
update: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' });
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
await locals.pb.collection('slots').update(id, result.payload);
return { ok: true };
},
delete: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' });
const record = await locals.pb.collection('slots').getOne(id).catch(() => null);
if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted' });
await locals.pb.collection('slots').delete(id);
return { ok: true };
}
};

View file

@ -0,0 +1,161 @@
<script lang="ts">
import { toDatetimeInput } from '$lib/calendar';
let { data, form } = $props();
let items = $derived(data.items || []);
let slots = $derived(
[...(data.slots || [])].sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
);
let showEditor = $state(false);
type SlotDraft = {
id: string;
item: string;
start: string;
status: string;
heldUntil: string;
notes: string;
};
let draft = $state<SlotDraft>(emptyDraft());
let action = $derived(draft.id ? '?/update' : '?/create');
let isHeld = $derived(draft.status === 'held');
let selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => {
if (!selectedItem || !draft.start) return '';
const start = new Date(draft.start);
if (Number.isNaN(start.getTime())) return '';
const end = new Date(start.getTime() + (Number(selectedItem.duration) || 0) * 60_000);
return `Ends at ${end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
});
function emptyDraft(): SlotDraft {
return { id: '', item: '', start: toDatetimeInput(new Date().toISOString()), status: 'available', heldUntil: '', notes: '' };
}
function createSlot() {
draft = emptyDraft();
showEditor = true;
}
function editSlot(slot: (typeof slots)[number]) {
draft = {
id: slot.id,
item: slot.item,
start: toDatetimeInput(slot.start),
status: slot.status,
heldUntil: slot.heldUntil,
notes: slot.notes
};
showEditor = true;
}
</script>
<svelte:head><title>Slots | CMS</title></svelte:head>
<div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
<div>
<h1 class="text-3xl font-bold">Slots</h1>
<p class="text-base-content/60">Create bookable time slots for your services.</p>
</div>
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
</div>
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
<tbody>
{#each slots as slot}
<tr>
<td><span class="font-semibold">{slot.itemName}</span></td>
<td>{new Date(slot.start).toLocaleString()}</td>
<td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td>
<td>
<span
class="badge capitalize"
class:badge-success={slot.status === 'available'}
class:badge-warning={slot.status === 'held'}
class:badge-info={slot.status === 'booked'}
>{slot.status}</span>
</td>
<td class="text-right">
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} onclick={() => editSlot(slot)}>Edit</button>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
</div>
{#if showEditor}
<div class="fixed inset-0 z-50 bg-black/50 p-4">
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
<div class="mb-4 flex items-center justify-between gap-3">
<h2 class="text-2xl font-bold">{draft.id ? 'Edit slot' : 'Create slot'}</h2>
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
</div>
<form method="POST" action={action} class="space-y-4">
<input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="status" value={draft.status} />
{#if isHeld}
<input type="hidden" name="item" value={draft.item} />
<input type="hidden" name="start" value={draft.start} />
{/if}
{#if isHeld}
<div class="alert alert-warning">
This slot is currently held by a basket{draft.heldUntil ? ` (until ${new Date(draft.heldUntil).toLocaleString()})` : ''} — editing start/end is disabled.
</div>
{/if}
<label class="form-control w-full">
<div class="label"><span class="label-text">Service</span></div>
<select class="select select-bordered w-full" name="item" required disabled={isHeld} bind:value={draft.item}>
<option value="" disabled>Select a service…</option>
{#each items as item}
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
{/each}
</select>
</label>
<label class="form-control w-full">
<div class="label"><span class="label-text">Start</span></div>
<input
class="input input-bordered w-full"
type="datetime-local"
name="start"
required
disabled={isHeld}
value={draft.start}
oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })}
/>
</label>
{#if endLabel}<p class="text-sm text-base-content/60">{endLabel}</p>{/if}
<label class="form-control w-full">
<div class="label"><span class="label-text">Notes</span></div>
<textarea class="textarea textarea-bordered" name="notes" bind:value={draft.notes}></textarea>
</label>
<div class="flex justify-between gap-2 pt-2">
{#if draft.id}
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
{:else}
<span></span>
{/if}
<div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save slot</button>
</div>
</div>
</form>
</div>
</div>
{/if}

View file

@ -7,7 +7,10 @@ const config = {
runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true) runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true)
}, },
kit: { kit: {
adapter: adapter() adapter: adapter(),
alias: {
$shared: '../packages/shared/src'
}
} }
}; };

14
app-admin/tsconfig.json Normal file
View file

@ -0,0 +1,14 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}

1
app-public/.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

View file

@ -5,9 +5,11 @@ WORKDIR /app
ENV NPM_CONFIG_AUDIT=false \ ENV NPM_CONFIG_AUDIT=false \
NPM_CONFIG_FUND=false \ NPM_CONFIG_FUND=false \
NPM_CONFIG_PROGRESS=false NPM_CONFIG_PROGRESS=false
COPY app/package*.json ./ COPY app-public/package*.json ./
COPY packages/shared/package.json ./packages/shared/package.json
RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund RUN --mount=type=cache,target=/root/.npm npm ci --ignore-scripts --no-audit --no-fund
COPY app/ ./ COPY app-public/ ./
COPY packages/shared/ ./packages/shared/
RUN npm run build RUN npm run build
FROM node:22-alpine FROM node:22-alpine

2497
app-public/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

32
app-public/package.json Normal file
View file

@ -0,0 +1,32 @@
{
"name": "app-public",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@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",
"vite": "^8.0.7"
},
"dependencies": {
"@stripe/stripe-js": "^9.12.1",
"@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"
}
}

140
app-public/src/app.css Normal file
View file

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

18
app-public/src/app.d.ts vendored Normal file
View file

@ -0,0 +1,18 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
import type PocketBase from 'pocketbase';
declare global {
namespace App {
// interface Error {}
interface Locals {
pb: PocketBase;
user: import('pocketbase').AuthRecord | null;
}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
app-public/src/app.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="text-scale" content="scale" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View file

@ -0,0 +1,15 @@
import type { Handle } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { createPocketBase } from '$lib/pb';
export const handle: Handle = async ({ event, resolve }) => {
event.locals.pb = createPocketBase(
event.request.headers.get('cookie') ?? '',
env.POCKETBASE_INTERNAL_URL
);
event.locals.user = event.locals.pb.authStore.record;
const response = await resolve(event);
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
return response;
};

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

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

View file

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

View file

@ -0,0 +1,51 @@
<script lang="ts">
import type { HeaderGlobal } from '$lib/types';
import { getBasketContext } from '$lib/basket.svelte';
let { header } = $props<{ header: HeaderGlobal }>();
const basket = getBasketContext();
let hasItems = $derived(basket.count > 0);
function formatTotal(amount: number) {
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
}
</script>
<header class="sticky top-0 z-40 border-b border-charcoal/5 bg-warm/90 backdrop-blur">
<div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-6 py-4">
<a class="flex items-center gap-3" href="/" aria-label="Home">
{#if header.logo?.url}
<img class="h-12 w-12 rounded-full object-cover" src={header.logo.url} alt={header.logo.alt || ''} />
{:else}
<span class="grid h-12 w-12 place-items-center rounded-full bg-sage text-lg font-bold text-white">ES</span>
{/if}
<span class="font-serif text-xl font-bold">Eva Shafik</span>
</a>
<nav class="hidden items-center gap-7 md:flex" aria-label="Main navigation">
{#each header.navLinks || [] as link}
<a class="text-sm font-semibold text-charcoal/75 transition hover:text-sage-dark" href={link.href}>{link.label}</a>
{/each}
</nav>
<div class="flex items-center gap-3">
{#if hasItems}
<a
class="relative flex items-center gap-2 rounded-full border border-charcoal/10 px-4 py-2 text-sm font-semibold text-charcoal/80 transition hover:border-sage hover:text-sage-dark"
href="/book"
aria-label="View your basket"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007Z" />
</svg>
<span class="badge badge-sm rounded-full border-0 bg-sage text-white">{basket.count}</span>
<span class="hidden sm:inline">{formatTotal(basket.total)}</span>
</a>
{/if}
{#if header.ctaButton?.label}
<a class="btn rounded-full border-0 px-6 text-white hover:opacity-90" style="background-color: var(--color-primary, #8a9a7b);" href={header.ctaButton.href}>{header.ctaButton.label}</a>
{/if}
</div>
</div>
</header>

1
app-public/src/lib/pb.ts Normal file
View file

@ -0,0 +1 @@
export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb';

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1 @@
export * from '$shared/stripe-client';

View file

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

View file

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

View file

@ -0,0 +1,79 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord, SlotRecord } from '$lib/types';
import { getFileUrl } from '$lib/pb';
import { getAdminPb } from '$lib/server/pb-admin';
import { BASKET_COOKIE, loadBasket, sweepExpiredHolds } from '$lib/server/basket';
import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try {
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
return record.data || fallback;
} catch {
return fallback;
}
}
export const load: LayoutServerLoad = async ({ locals, cookies }) => {
const [header, footer, colors] = await Promise.all([
getGlobal(locals.pb, 'header', defaultHeader),
getGlobal(locals.pb, 'footer', defaultFooter),
getGlobal(locals.pb, 'colors', defaultColors)
]);
if (!header.homePage) header.homePage = defaultHeader.homePage;
// Commerce data for the public site.
let basket = null;
let items: ItemRecord[] = [];
let slots: SlotRecord[] = [];
try {
const pb = await getAdminPb();
await sweepExpiredHolds(pb);
const basketId = cookies.get(BASKET_COOKIE);
if (basketId) basket = await loadBasket(pb, basketId);
const itemRecords = await pb
.collection('items')
.getFullList({ filter: 'active = true', sort: 'name', expand: 'image' })
.catch(() => []);
items = itemRecords.map((record) => {
const media = record.expand?.image;
return {
id: record.id,
name: record.name,
description: record.description || '',
price: record.price,
image: record.image || '',
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type,
stock: record.stock ?? null,
duration: record.duration ?? null,
active: record.active
};
});
const nowIso = new Date().toISOString();
const slotRecords = await pb
.collection('slots')
.getFullList({ filter: `status = 'available' && start >= "${nowIso}"`, sort: 'start' })
.catch(() => []);
slots = slotRecords.map((record) => ({
id: record.id,
item: record.item,
start: record.start,
end: record.end || '',
status: record.status,
heldUntil: record.heldUntil || null,
order: record.order || null,
notes: record.notes || ''
}));
} catch (e) {
// Admin PB not configured (e.g. fresh dev env) — commerce features off.
console.warn('Commerce data unavailable:', e instanceof Error ? e.message : e);
}
return { header, footer, colors, user: locals.user, basket, items, slots };
};

View file

@ -3,13 +3,22 @@
import favicon from '$lib/assets/favicon.svg'; import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte'; import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte'; import Footer from '$lib/components/Footer.svelte';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
let { children, data } = $props(); let { children, data } = $props();
let isAdmin = $derived(data.url?.pathname?.startsWith('/admin'));
// One basket store per public layout instance — provided to all children
// (Header indicator, ShopBlock, CheckoutBlock). Never module-level state.
const basketStore = createBasketStore(data.basket ?? null);
setBasketContext(basketStore);
// Keep the store in sync when layout data refreshes (e.g. after checkout
// clears the cookie and data.basket becomes null).
$effect(() => basketStore.syncFrom(data.basket ?? null));
onMount(() => { onMount(() => {
if (data.colors && !isAdmin) { if (data.colors) {
const root = document.documentElement; const root = document.documentElement;
root.style.setProperty('--color-bg', data.colors.background); root.style.setProperty('--color-bg', data.colors.background);
root.style.setProperty('--color-heading', data.colors.heading); root.style.setProperty('--color-heading', data.colors.heading);
@ -26,10 +35,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
</svelte:head> </svelte:head>
{#if isAdmin}
{@render children()}
{:else}
<Header header={data.header} /> <Header header={data.header} />
<main>{@render children()}</main> <main>{@render children()}</main>
<Footer footer={data.footer} /> <Footer footer={data.footer} />
{/if}

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte'; import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
let { data } = $props(); let { data } = $props();
</script> </script>
@ -8,4 +8,4 @@
<title>{data.page.title}</title> <title>{data.page.title}</title>
</svelte:head> </svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} /> <BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />

View file

@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte'; import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
let { data } = $props(); let { data } = $props();
</script> </script>
@ -7,4 +7,4 @@
<title>{data.page.title}</title> <title>{data.page.title}</title>
</svelte:head> </svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} /> <BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,72 @@
<script lang="ts">
import { onMount } from 'svelte';
let { data } = $props();
function formatSlotDate(iso?: string | null) {
if (!iso) return '';
return new Date(iso).toLocaleString(undefined, {
weekday: 'long',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
function formatPrice(amount: number) {
return new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(amount);
}
</script>
<svelte:head>
<title>Booking confirmation</title>
</svelte:head>
<section class="mx-auto max-w-2xl px-6 py-16 text-center">
{#if data.state === 'paid' && data.order}
<div class="mb-6 inline-grid h-16 w-16 place-items-center rounded-full bg-sage text-3xl text-white">✓</div>
<h1 class="font-serif text-4xl">Thank you, {data.order.customerDetails?.name || 'friend'}!</h1>
<p class="mt-3 text-charcoal/70">
Your booking is confirmed. A receipt was sent to <strong>{data.order.email}</strong>.
</p>
<div class="mt-8 rounded-box border border-charcoal/10 bg-white/60 p-6 text-left">
<h2 class="font-serif text-xl">Your order</h2>
<ul class="mt-4 space-y-3">
{#each data.order.lines ?? [] as line}
<li class="flex items-baseline justify-between gap-4">
<div>
<span class="font-semibold">{line.quantity}× {line.name}</span>
{#if line.start}
<div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div>
{/if}
</div>
<span>{formatPrice(line.price * line.quantity)}</span>
</li>
{/each}
</ul>
<div class="mt-4 flex justify-between border-t border-charcoal/10 pt-4 font-bold">
<span>Total</span><span>{formatPrice(data.order.total)}</span>
</div>
</div>
<a class="btn mt-8 rounded-full border-0 px-8 text-white" style="background-color: var(--color-primary, #8a9a7b);" href="/">Book another</a>
{:else if data.state === 'processing'}
<h1 class="font-serif text-4xl">Processing your payment…</h1>
<p class="mt-3 text-charcoal/70">
Your payment went through — we're just finalizing your booking. This page refreshes automatically.
</p>
<span class="loading loading-spinner loading-lg mt-6 text-sage"></span>
<!-- Auto-reload until the webhook has created the order -->
<meta http-equiv="refresh" content="4" />
{:else if data.state === 'canceled' || data.state === 'failed'}
<h1 class="font-serif text-4xl">Payment not completed</h1>
<p class="mt-3 text-charcoal/70">Your payment didn't go through — no money was captured. Please try again.</p>
<a class="btn mt-8 rounded-full border-0 px-8 text-white" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a>
{:else}
<h1 class="font-serif text-4xl">Nothing to see here</h1>
<p class="mt-3 text-charcoal/70">This link is missing a payment reference.</p>
<a class="btn mt-8 rounded-full border-0 px-8 text-white" style="background-color: var(--color-primary, #8a9a7b);" href="/">Back to the shop</a>
{/if}
</section>

View file

@ -0,0 +1,3 @@
# allow crawling everything by default
User-agent: *
Disallow:

View file

@ -0,0 +1,17 @@
import adapter from '@sveltejs/adapter-node';
/** @type {import('@sveltejs/kit').Config} */
const config = {
compilerOptions: {
// Force runes mode for the project, except for libraries. Can be removed in svelte 6.
runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true)
},
kit: {
adapter: adapter(),
alias: {
$shared: '../packages/shared/src'
}
}
};
export default config;

14
app-public/tsconfig.json Normal file
View file

@ -0,0 +1,14 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}

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