added mailing through Brevo and node mailer, also a email editor, with
their custom blocks and renderers
This commit is contained in:
parent
43db707e34
commit
96828994e1
34 changed files with 2035 additions and 323 deletions
17
.env.example
17
.env.example
|
|
@ -11,6 +11,23 @@ STRIPE_CURRENCY=eur
|
||||||
POCKETBASE_ADMIN_EMAIL=admin@example.com
|
POCKETBASE_ADMIN_EMAIL=admin@example.com
|
||||||
POCKETBASE_ADMIN_PASSWORD=changeme
|
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.
|
# Caddy scheme for the reverse proxy on port 8080.
|
||||||
# http (default) — plain HTTP; matches the ORIGIN vars in docker-compose.yml
|
# http (default) — plain HTTP; matches the ORIGIN vars in docker-compose.yml
|
||||||
# https — HTTPS on :8080 (self-signed unless you add a cert issuer;
|
# https — HTTPS on :8080 (self-signed unless you add a cert issuer;
|
||||||
|
|
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -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
|
||||||
|
|
|
||||||
16
AGENTS.md
16
AGENTS.md
|
|
@ -30,7 +30,8 @@ app-admin/ # SvelteKit admin app (serves admin.<domain>)
|
||||||
│ │ ├── calendar/ # Event CRUD
|
│ │ ├── calendar/ # Event CRUD
|
||||||
│ │ ├── items/ # Service/product CRUD
|
│ │ ├── items/ # Service/product CRUD
|
||||||
│ │ ├── slots/ # Bookable time slot CRUD
|
│ │ ├── slots/ # Bookable time slot CRUD
|
||||||
│ │ ├── orders/ # Read-only order list
|
│ │ ├── orders/ # Order list + booking-email status/resend
|
||||||
|
│ │ ├── emails/ # Block-based booking email editor (live preview, test send)
|
||||||
│ │ ├── globals/ # Header/footer/colors editor
|
│ │ ├── globals/ # Header/footer/colors editor
|
||||||
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
|
│ │ ├── preview/ # Draft preview via sessionStorage (same-origin)
|
||||||
│ │ └── api/ # upload, export, import endpoints
|
│ │ └── api/ # upload, export, import endpoints
|
||||||
|
|
@ -103,6 +104,15 @@ Pages are composed of `ContentBlock[]`. Each block has `{ id, type, data }`. Blo
|
||||||
|
|
||||||
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`.
|
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
|
### Shared Code
|
||||||
- `packages/shared/src/types.ts` — all type definitions
|
- `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)
|
- `packages/shared/src/calendar.ts` — calendar utilities (used by admin calendar editor and public upcoming calendar block)
|
||||||
|
|
@ -112,7 +122,7 @@ To add a new block type: add to `BlockType` union in `packages/shared/src/types.
|
||||||
### 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
|
||||||
|
|
@ -152,4 +162,6 @@ cd app-public && npm run build
|
||||||
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`.
|
- `POCKETBASE_INTERNAL_URL` — internal Docker network URL (`http://pocketbase:80`). Set in `docker-compose.yml`.
|
||||||
- `ORIGIN` — SvelteKit origin for SSR. Differs per app: `http://admin.${DOMAIN}:8080` (admin), `http://www.${DOMAIN}:8080` (public).
|
- `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`).
|
- `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`.
|
- Stripe + PocketBase admin secrets are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
|
||||||
|
|
|
||||||
27
README.md
27
README.md
|
|
@ -99,8 +99,9 @@ Commerce collections (see the Stripe section above for context):
|
||||||
- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text
|
- `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
|
- `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`
|
- `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
|
- `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)
|
- `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.
|
> **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.
|
||||||
|
|
||||||
|
|
@ -121,7 +122,8 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
|
||||||
- `/calendar` — events shown by Upcoming Calendar blocks
|
- `/calendar` — events shown by Upcoming Calendar blocks
|
||||||
- `/items` — services and products shown in Shop blocks
|
- `/items` — services and products shown in Shop blocks
|
||||||
- `/slots` — manually created bookable time slots for services
|
- `/slots` — manually created bookable time slots for services
|
||||||
- `/orders` — read-only list of confirmed bookings and purchases
|
- `/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
|
- `/globals` — header/footer/colors editor
|
||||||
|
|
||||||
## Reservations & payments (Stripe)
|
## Reservations & payments (Stripe)
|
||||||
|
|
@ -140,6 +142,27 @@ Setup:
|
||||||
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.
|
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.
|
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)
|
## Public routes (public app)
|
||||||
|
|
||||||
- `/` renders `pages.slug = "home"`
|
- `/` renders `pages.slug = "home"`
|
||||||
|
|
|
||||||
21
app-admin/package-lock.json
generated
21
app-admin/package-lock.json
generated
|
|
@ -19,6 +19,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",
|
||||||
|
|
@ -28,6 +29,7 @@
|
||||||
"@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",
|
||||||
|
|
@ -1683,6 +1685,16 @@
|
||||||
"undici-types": ">=7.24.0 <7.24.7"
|
"undici-types": ">=7.24.0 <7.24.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/nodemailer": {
|
||||||
|
"version": "8.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz",
|
||||||
|
"integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/resolve": {
|
"node_modules/@types/resolve": {
|
||||||
"version": "1.20.2",
|
"version": "1.20.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
|
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
|
||||||
|
|
@ -2269,6 +2281,15 @@
|
||||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/nodemailer": {
|
||||||
|
"version": "10.0.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.12.tgz",
|
||||||
|
"integrity": "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg==",
|
||||||
|
"license": "MIT-0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/obug": {
|
"node_modules/obug": {
|
||||||
"version": "2.1.4",
|
"version": "2.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
"@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",
|
||||||
|
|
@ -23,14 +24,15 @@
|
||||||
"@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",
|
||||||
"@sveltejs/adapter-node": "^5.5.4",
|
|
||||||
"@stripe/stripe-js": "^9.12.1",
|
"@stripe/stripe-js": "^9.12.1",
|
||||||
|
"@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",
|
||||||
"@tiptap/extension-link": "^3.23.4",
|
"@tiptap/extension-link": "^3.23.4",
|
||||||
"@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",
|
||||||
|
|
|
||||||
|
|
@ -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}
|
||||||
|
|
|
||||||
90
app-admin/src/lib/admin/editors/EmailBlockEditor.svelte
Normal file
90
app-admin/src/lib/admin/editors/EmailBlockEditor.svelte
Normal 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}
|
||||||
43
app-admin/src/lib/admin/emailBlockDefaults.ts
Normal file
43
app-admin/src/lib/admin/emailBlockDefaults.ts
Normal 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;
|
||||||
|
}
|
||||||
1
app-admin/src/lib/email.ts
Normal file
1
app-admin/src/lib/email.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export * from '$shared/email';
|
||||||
1
app-admin/src/lib/server/email.ts
Normal file
1
app-admin/src/lib/server/email.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export * from '$shared/server/email';
|
||||||
|
|
@ -91,6 +91,7 @@
|
||||||
<a class="btn btn-ghost" href="/items">Items</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="/slots">Slots</a>
|
||||||
<a class="btn btn-ghost" href="/orders">Orders</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>
|
<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">
|
||||||
|
|
|
||||||
21
app-admin/src/routes/emails/+page.server.ts
Normal file
21
app-admin/src/routes/emails/+page.server.ts
Normal 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() };
|
||||||
|
};
|
||||||
39
app-admin/src/routes/emails/+page.svelte
Normal file
39
app-admin/src/routes/emails/+page.svelte
Normal 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>
|
||||||
116
app-admin/src/routes/emails/[key]/+page.server.ts
Normal file
116
app-admin/src/routes/emails/[key]/+page.server.ts
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
||||||
232
app-admin/src/routes/emails/[key]/+page.svelte
Normal file
232
app-admin/src/routes/emails/[key]/+page.svelte
Normal 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>
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
import type { PageServerLoad } from './$types';
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import { sendOrderEmails, type EmailKind } from '$lib/server/email';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ locals }) => {
|
export const load: PageServerLoad = async ({ locals }) => {
|
||||||
// Sort by id, not 'created' — commerce collections were imported without
|
// Sort by id, not 'created' — commerce collections were imported without
|
||||||
|
|
@ -9,7 +11,7 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
const lineRecords = await locals.pb
|
const lineRecords = await locals.pb
|
||||||
.collection('order_lines')
|
.collection('order_lines')
|
||||||
.getFullList({ filter: `order = "${record.id}"` })
|
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) })
|
||||||
.catch(() => []);
|
.catch(() => []);
|
||||||
|
|
||||||
orders.push({
|
orders.push({
|
||||||
|
|
@ -19,6 +21,9 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
total: Number(record.total) || 0,
|
total: Number(record.total) || 0,
|
||||||
status: String(record.status || 'pending'),
|
status: String(record.status || 'pending'),
|
||||||
created: String(record.created || ''),
|
created: String(record.created || ''),
|
||||||
|
customerEmailSentAt: String(record.customerEmailSentAt || ''),
|
||||||
|
clientEmailSentAt: String(record.clientEmailSentAt || ''),
|
||||||
|
emailError: String(record.emailError || ''),
|
||||||
lines: lineRecords.map((line) => ({
|
lines: lineRecords.map((line) => ({
|
||||||
id: line.id,
|
id: line.id,
|
||||||
name: String(line.name || ''),
|
name: String(line.name || ''),
|
||||||
|
|
@ -32,3 +37,25 @@ export const load: PageServerLoad = async ({ locals }) => {
|
||||||
|
|
||||||
return { orders };
|
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]}.` };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,37 @@
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
let { data } = $props();
|
import { enhance } from '$app/forms';
|
||||||
|
|
||||||
|
let { data, form } = $props();
|
||||||
let orders = $derived(data.orders || []);
|
let orders = $derived(data.orders || []);
|
||||||
|
let resending = $state('');
|
||||||
|
|
||||||
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
{#snippet emailStatus(order: (typeof orders)[number], kind: 'customer' | 'client', label: string, sentAt: string)}
|
||||||
|
<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>
|
<svelte:head><title>Orders | CMS</title></svelte:head>
|
||||||
|
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
|
|
@ -53,6 +80,17 @@
|
||||||
{#if order.customerDetails?.notes}
|
{#if order.customerDetails?.notes}
|
||||||
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
||||||
{/if}
|
{/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>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
21
app-public/package-lock.json
generated
21
app-public/package-lock.json
generated
|
|
@ -12,6 +12,7 @@
|
||||||
"@sveltejs/adapter-node": "^5.5.4",
|
"@sveltejs/adapter-node": "^5.5.4",
|
||||||
"@tailwindcss/vite": "^4.3.0",
|
"@tailwindcss/vite": "^4.3.0",
|
||||||
"daisyui": "^5.5.19",
|
"daisyui": "^5.5.19",
|
||||||
|
"nodemailer": "^10.0.12",
|
||||||
"pocketbase": "^0.26.9",
|
"pocketbase": "^0.26.9",
|
||||||
"stripe": "^22.3.2",
|
"stripe": "^22.3.2",
|
||||||
"tailwindcss": "^4.3.0"
|
"tailwindcss": "^4.3.0"
|
||||||
|
|
@ -20,6 +21,7 @@
|
||||||
"@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",
|
||||||
"svelte": "^5.55.2",
|
"svelte": "^5.55.2",
|
||||||
"svelte-check": "^4.4.6",
|
"svelte-check": "^4.4.6",
|
||||||
"typescript": "^6.0.2",
|
"typescript": "^6.0.2",
|
||||||
|
|
@ -1168,6 +1170,16 @@
|
||||||
"undici-types": ">=7.24.0 <7.24.7"
|
"undici-types": ">=7.24.0 <7.24.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/nodemailer": {
|
||||||
|
"version": "8.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz",
|
||||||
|
"integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/node": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/resolve": {
|
"node_modules/@types/resolve": {
|
||||||
"version": "1.20.2",
|
"version": "1.20.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
|
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
|
||||||
|
|
@ -1741,6 +1753,15 @@
|
||||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/nodemailer": {
|
||||||
|
"version": "10.0.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.12.tgz",
|
||||||
|
"integrity": "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg==",
|
||||||
|
"license": "MIT-0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/obug": {
|
"node_modules/obug": {
|
||||||
"version": "2.1.4",
|
"version": "2.1.4",
|
||||||
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz",
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
"@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",
|
||||||
"svelte": "^5.55.2",
|
"svelte": "^5.55.2",
|
||||||
"svelte-check": "^4.4.6",
|
"svelte-check": "^4.4.6",
|
||||||
"typescript": "^6.0.2",
|
"typescript": "^6.0.2",
|
||||||
|
|
@ -23,6 +24,7 @@
|
||||||
"@sveltejs/adapter-node": "^5.5.4",
|
"@sveltejs/adapter-node": "^5.5.4",
|
||||||
"@tailwindcss/vite": "^4.3.0",
|
"@tailwindcss/vite": "^4.3.0",
|
||||||
"daisyui": "^5.5.19",
|
"daisyui": "^5.5.19",
|
||||||
|
"nodemailer": "^10.0.12",
|
||||||
"pocketbase": "^0.26.9",
|
"pocketbase": "^0.26.9",
|
||||||
"stripe": "^22.3.2",
|
"stripe": "^22.3.2",
|
||||||
"tailwindcss": "^4.3.0"
|
"tailwindcss": "^4.3.0"
|
||||||
|
|
|
||||||
1
app-public/src/lib/server/email.ts
Normal file
1
app-public/src/lib/server/email.ts
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
export * from '$shared/server/email';
|
||||||
|
|
@ -5,6 +5,7 @@ import { getStripe } from '$lib/stripe.server';
|
||||||
import { getAdminPb } from '$lib/server/pb-admin';
|
import { getAdminPb } from '$lib/server/pb-admin';
|
||||||
import { getFileUrl } from '$lib/pb';
|
import { getFileUrl } from '$lib/pb';
|
||||||
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
|
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
|
||||||
|
import { sendOrderEmails } from '$lib/server/email';
|
||||||
import type PocketBase from 'pocketbase';
|
import type PocketBase from 'pocketbase';
|
||||||
|
|
||||||
async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
|
async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
|
||||||
|
|
@ -14,7 +15,7 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
|
||||||
// Idempotency: if an order already exists for this intent, we're done.
|
// Idempotency: if an order already exists for this intent, we're done.
|
||||||
const existing = await pb
|
const existing = await pb
|
||||||
.collection('orders')
|
.collection('orders')
|
||||||
.getFirstListItem(`stripePaymentIntentId = "${paymentIntent.id}"`)
|
.getFirstListItem(pb.filter('stripePaymentIntentId = {:id}', { id: paymentIntent.id }))
|
||||||
.catch(() => null);
|
.catch(() => null);
|
||||||
if (existing) return;
|
if (existing) return;
|
||||||
|
|
||||||
|
|
@ -23,7 +24,7 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
|
||||||
|
|
||||||
const lines = await pb
|
const lines = await pb
|
||||||
.collection('basket_lines')
|
.collection('basket_lines')
|
||||||
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot' });
|
.getFullList({ filter: pb.filter('basket = {:basketId}', { basketId }), expand: 'item,slot' });
|
||||||
|
|
||||||
// Create the order
|
// Create the order
|
||||||
const order = await pb.collection('orders').create({
|
const order = await pb.collection('orders').create({
|
||||||
|
|
@ -68,6 +69,11 @@ async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
|
||||||
await pb.collection('basket_lines').delete(line.id).catch(() => {});
|
await pb.collection('basket_lines').delete(line.id).catch(() => {});
|
||||||
}
|
}
|
||||||
await pb.collection('baskets').update(basketId, { status: 'completed' }).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) {
|
async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) {
|
||||||
|
|
|
||||||
BIN
backups/logo.png
Normal file
BIN
backups/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 416 KiB |
|
|
@ -27,6 +27,15 @@ services:
|
||||||
# Commerce (reservation & payment system) — set these in a root-level .env
|
# Commerce (reservation & payment system) — set these in a root-level .env
|
||||||
POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
|
POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-}
|
||||||
POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
|
POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-}
|
||||||
|
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
|
||||||
|
# Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends
|
||||||
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
|
SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
|
SMTP_PASS: ${SMTP_PASS:-}
|
||||||
|
EMAIL_FROM: ${EMAIL_FROM:-}
|
||||||
|
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
|
||||||
|
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
|
||||||
# Internal only — served via the caddy reverse proxy
|
# Internal only — served via the caddy reverse proxy
|
||||||
expose:
|
expose:
|
||||||
- "3001"
|
- "3001"
|
||||||
|
|
@ -51,6 +60,14 @@ services:
|
||||||
STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
|
STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
|
||||||
PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-}
|
PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-}
|
||||||
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
|
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
|
||||||
|
# Booking emails (Brevo SMTP relay) — sent from the Stripe webhook
|
||||||
|
SMTP_HOST: ${SMTP_HOST:-}
|
||||||
|
SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
|
SMTP_USER: ${SMTP_USER:-}
|
||||||
|
SMTP_PASS: ${SMTP_PASS:-}
|
||||||
|
EMAIL_FROM: ${EMAIL_FROM:-}
|
||||||
|
EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-}
|
||||||
|
SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo}
|
||||||
# Internal only — served via the caddy reverse proxy
|
# Internal only — served via the caddy reverse proxy
|
||||||
expose:
|
expose:
|
||||||
- "3000"
|
- "3000"
|
||||||
|
|
|
||||||
|
|
@ -6,13 +6,25 @@
|
||||||
"name": "@eva/shared",
|
"name": "@eva/shared",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@stripe/stripe-js": "^9.12.1",
|
"@stripe/stripe-js": "^9.12.1",
|
||||||
|
"nodemailer": "^10.0.12",
|
||||||
"pocketbase": "^0.26.9",
|
"pocketbase": "^0.26.9",
|
||||||
},
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/nodemailer": "^8.0.2",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"packages": {
|
"packages": {
|
||||||
"@stripe/stripe-js": ["@stripe/stripe-js@9.13.0", "", {}, "sha512-/0c72BUgzzVkVTlsw5uBn8x3waTdVJ/PZGfQ6jY1eu6K7olUPf4d9lgDPA9/0sIdsR8j7o3QIG8fOCO6ItcL7A=="],
|
"@stripe/stripe-js": ["@stripe/stripe-js@9.13.0", "", {}, "sha512-/0c72BUgzzVkVTlsw5uBn8x3waTdVJ/PZGfQ6jY1eu6K7olUPf4d9lgDPA9/0sIdsR8j7o3QIG8fOCO6ItcL7A=="],
|
||||||
|
|
||||||
|
"@types/node": ["@types/node@26.6.3", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg=="],
|
||||||
|
|
||||||
|
"@types/nodemailer": ["@types/nodemailer@8.0.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA=="],
|
||||||
|
|
||||||
|
"nodemailer": ["nodemailer@10.0.12", "", {}, "sha512-PQ46oNbNMuH/Sno7B5IWIU9etytwrO0xdTFvWXpIQFRXhBAXtzD48243AS+BCbQQTPD8y3fqUrgLn0tSo77gvg=="],
|
||||||
|
|
||||||
"pocketbase": ["pocketbase@0.26.9", "", {}, "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ=="],
|
"pocketbase": ["pocketbase@0.26.9", "", {}, "sha512-Tiv1/hNuUzRdvT0d8hF03dfzuefQ1WdSRp1A1q3wzFC/WYhQcbU/Qlaubl/3ZDo6xvFXBS8JAgBS/L+ms7nkVQ=="],
|
||||||
|
|
||||||
|
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,10 +12,16 @@
|
||||||
"./basket.svelte": "./src/basket.svelte.ts",
|
"./basket.svelte": "./src/basket.svelte.ts",
|
||||||
"./blocks/BlockRenderer.svelte": "./src/blocks/BlockRenderer.svelte",
|
"./blocks/BlockRenderer.svelte": "./src/blocks/BlockRenderer.svelte",
|
||||||
"./server/pb-admin": "./src/server/pb-admin.ts",
|
"./server/pb-admin": "./src/server/pb-admin.ts",
|
||||||
"./server/basket": "./src/server/basket.ts"
|
"./server/basket": "./src/server/basket.ts",
|
||||||
|
"./email": "./src/email/index.ts",
|
||||||
|
"./server/email": "./src/server/email/index.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"pocketbase": "^0.26.9",
|
"@stripe/stripe-js": "^9.12.1",
|
||||||
"@stripe/stripe-js": "^9.12.1"
|
"nodemailer": "^10.0.12",
|
||||||
|
"pocketbase": "^0.26.9"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/nodemailer": "^8.0.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
86
packages/shared/src/email/defaults.ts
Normal file
86
packages/shared/src/email/defaults.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
import type { EmailBlock, EmailTemplate, EmailTemplateKey } from '../types';
|
||||||
|
|
||||||
|
export const emailTemplateKeys: EmailTemplateKey[] = ['customer_confirmation', 'client_alert'];
|
||||||
|
|
||||||
|
export const emailTemplateMeta: Record<EmailTemplateKey, { label: string; description: string }> = {
|
||||||
|
customer_confirmation: {
|
||||||
|
label: 'Booking confirmation',
|
||||||
|
description: 'Sent to the customer after a successful payment. Includes a calendar (.ics) attachment for booked time slots.'
|
||||||
|
},
|
||||||
|
client_alert: {
|
||||||
|
label: 'New booking alert',
|
||||||
|
description: 'Sent to you after a successful payment. Replying goes straight to the customer.'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Used whenever no email_templates record exists for a key, so booking emails
|
||||||
|
// work before anyone has opened the email editor.
|
||||||
|
export const defaultEmailTemplates: Record<EmailTemplateKey, EmailTemplate> = {
|
||||||
|
customer_confirmation: {
|
||||||
|
key: 'customer_confirmation',
|
||||||
|
subject: 'Your booking is confirmed – {{service}}',
|
||||||
|
recipients: '',
|
||||||
|
enabled: true,
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
id: 'default-cc-intro',
|
||||||
|
type: 'text',
|
||||||
|
data: {
|
||||||
|
content:
|
||||||
|
'<h2>Thank you, {{customer_first_name}}!</h2><p>Your booking is confirmed and paid. Here are the details:</p>'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ id: 'default-cc-booking', type: 'booking_details', data: { title: 'Your booking' } },
|
||||||
|
{
|
||||||
|
id: 'default-cc-outro',
|
||||||
|
type: 'text',
|
||||||
|
data: {
|
||||||
|
content:
|
||||||
|
'<p>A calendar file is attached — open it to add the appointment to your calendar.</p><p>If you need to change or cancel your booking, simply reply to this email.</p><p>Looking forward to seeing you,<br>{{business_name}}</p>'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ id: 'default-cc-divider', type: 'divider', data: {} },
|
||||||
|
{ id: 'default-cc-contact', type: 'contact_info', data: { title: 'Where to find us' } }
|
||||||
|
] satisfies EmailBlock[]
|
||||||
|
},
|
||||||
|
client_alert: {
|
||||||
|
key: 'client_alert',
|
||||||
|
subject: 'New booking: {{service}} – {{customer_name}}',
|
||||||
|
recipients: '',
|
||||||
|
enabled: true,
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
id: 'default-ca-intro',
|
||||||
|
type: 'text',
|
||||||
|
data: {
|
||||||
|
content:
|
||||||
|
'<h2>New booking</h2><p>{{customer_name}} just booked and paid {{order_total}}.</p>'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ id: 'default-ca-booking', type: 'booking_details', data: { title: 'Booking' } },
|
||||||
|
{ id: 'default-ca-customer', type: 'customer_details', data: { title: 'Customer' } },
|
||||||
|
{
|
||||||
|
id: 'default-ca-outro',
|
||||||
|
type: 'text',
|
||||||
|
data: { content: '<p>Reply to this email to contact {{customer_first_name}} directly.</p>' }
|
||||||
|
}
|
||||||
|
] satisfies EmailBlock[]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function isEmailTemplateKey(value: string): value is EmailTemplateKey {
|
||||||
|
return (emailTemplateKeys as string[]).includes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Merge a PocketBase record (or partial data) over the default for its key. */
|
||||||
|
export function normalizeEmailTemplate(key: EmailTemplateKey, record?: Record<string, any> | null): EmailTemplate {
|
||||||
|
const fallback = defaultEmailTemplates[key];
|
||||||
|
if (!record) return structuredClone(fallback);
|
||||||
|
return {
|
||||||
|
key,
|
||||||
|
subject: typeof record.subject === 'string' && record.subject.trim() ? record.subject : fallback.subject,
|
||||||
|
blocks: Array.isArray(record.blocks) ? record.blocks : structuredClone(fallback.blocks),
|
||||||
|
recipients: typeof record.recipients === 'string' ? record.recipients : '',
|
||||||
|
enabled: typeof record.enabled === 'boolean' ? record.enabled : true
|
||||||
|
};
|
||||||
|
}
|
||||||
2
packages/shared/src/email/index.ts
Normal file
2
packages/shared/src/email/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
export * from './render';
|
||||||
|
export * from './defaults';
|
||||||
424
packages/shared/src/email/render.ts
Normal file
424
packages/shared/src/email/render.ts
Normal file
|
|
@ -0,0 +1,424 @@
|
||||||
|
import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types';
|
||||||
|
|
||||||
|
// Pure email rendering — no server or browser APIs, so the admin editor can
|
||||||
|
// render its live preview client-side with exactly the code that sends.
|
||||||
|
//
|
||||||
|
// Email clients (Gmail, Outlook, Apple Mail) strip <style> tags and ignore
|
||||||
|
// most modern CSS, so everything here is table-based with inline styles.
|
||||||
|
|
||||||
|
export type EmailLine = {
|
||||||
|
name: string;
|
||||||
|
price: number;
|
||||||
|
quantity: number;
|
||||||
|
start: string | null;
|
||||||
|
end: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EmailContext = {
|
||||||
|
orderId: string;
|
||||||
|
total: number;
|
||||||
|
currency: string;
|
||||||
|
customer: CustomerDetails;
|
||||||
|
lines: EmailLine[];
|
||||||
|
business: FooterGlobal;
|
||||||
|
colors: ColorsGlobal;
|
||||||
|
siteUrl: string;
|
||||||
|
timezone: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RenderedEmail = { subject: string; html: string; text: string };
|
||||||
|
|
||||||
|
export const emailPlaceholders: { key: string; description: string }[] = [
|
||||||
|
{ key: 'customer_name', description: 'Customer full name' },
|
||||||
|
{ key: 'customer_first_name', description: 'Customer first name' },
|
||||||
|
{ key: 'customer_email', description: 'Customer email' },
|
||||||
|
{ key: 'customer_phone', description: 'Customer phone' },
|
||||||
|
{ key: 'customer_notes', description: 'Notes left at checkout' },
|
||||||
|
{ key: 'service', description: 'Booked service(s)' },
|
||||||
|
{ key: 'booking_date', description: 'Date and time of the first booking' },
|
||||||
|
{ key: 'order_total', description: 'Total paid' },
|
||||||
|
{ key: 'order_id', description: 'Order reference' },
|
||||||
|
{ key: 'business_name', description: 'Business name (footer settings)' },
|
||||||
|
{ key: 'business_email', description: 'Business email (footer settings)' },
|
||||||
|
{ key: 'business_phone', description: 'Business phone (footer settings)' },
|
||||||
|
{ key: 'site_url', description: 'Website address' }
|
||||||
|
];
|
||||||
|
|
||||||
|
const CONTENT_WIDTH = 536; // 600px card minus 2×32px padding
|
||||||
|
const FONT_BODY = "'DM Sans', Helvetica, Arial, sans-serif";
|
||||||
|
const FONT_HEADING = "'Playfair Display', Georgia, 'Times New Roman', serif";
|
||||||
|
const BORDER = '#e7e1d8';
|
||||||
|
|
||||||
|
// ── Formatting ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function escapeHtml(value: unknown): string {
|
||||||
|
return String(value ?? '')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatMoney(amount: number, currency: string): string {
|
||||||
|
try {
|
||||||
|
return new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency.toUpperCase() }).format(amount);
|
||||||
|
} catch {
|
||||||
|
return `${amount.toFixed(2)} ${currency.toUpperCase()}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeTimeZone(timezone: string): string {
|
||||||
|
try {
|
||||||
|
new Intl.DateTimeFormat('en-GB', { timeZone: timezone });
|
||||||
|
return timezone;
|
||||||
|
} catch {
|
||||||
|
return 'UTC';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatDateTime(iso: string, timezone: string): string {
|
||||||
|
return new Intl.DateTimeFormat('en-GB', {
|
||||||
|
timeZone: safeTimeZone(timezone),
|
||||||
|
weekday: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
}).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(iso: string, timezone: string): string {
|
||||||
|
return new Intl.DateTimeFormat('en-GB', {
|
||||||
|
timeZone: safeTimeZone(timezone),
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
}).format(new Date(iso));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */
|
||||||
|
export function formatLineWhen(line: EmailLine, timezone: string): string {
|
||||||
|
if (!line.start) return '';
|
||||||
|
const start = formatDateTime(line.start, timezone);
|
||||||
|
return line.end ? `${start} – ${formatTime(line.end, timezone)}` : start;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function absoluteUrl(url: string, siteUrl: string): string {
|
||||||
|
if (url.startsWith('/') && !url.startsWith('//')) return siteUrl.replace(/\/$/, '') + url;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Placeholders ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function placeholderValues(ctx: EmailContext): Record<string, string> {
|
||||||
|
const firstBooking = ctx.lines.find((line) => line.start);
|
||||||
|
return {
|
||||||
|
customer_name: ctx.customer.name,
|
||||||
|
customer_first_name: (ctx.customer.name || '').trim().split(/\s+/)[0] || '',
|
||||||
|
customer_email: ctx.customer.email,
|
||||||
|
customer_phone: ctx.customer.phone,
|
||||||
|
customer_notes: ctx.customer.notes,
|
||||||
|
service: ctx.lines.map((line) => line.name).join(', '),
|
||||||
|
booking_date: firstBooking ? formatLineWhen(firstBooking, ctx.timezone) : '',
|
||||||
|
order_total: formatMoney(ctx.total, ctx.currency),
|
||||||
|
order_id: ctx.orderId,
|
||||||
|
business_name: ctx.business.businessName,
|
||||||
|
business_email: ctx.business.email,
|
||||||
|
business_phone: ctx.business.phone,
|
||||||
|
site_url: ctx.siteUrl
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replace {{key}} tokens; unknown keys are left untouched so typos stay visible. */
|
||||||
|
export function fillPlaceholders(input: string, values: Record<string, string>, escape: boolean): string {
|
||||||
|
return String(input ?? '').replace(/\{\{\s*([a-z_]+)\s*\}\}/g, (match, key: string) =>
|
||||||
|
key in values ? (escape ? escapeHtml(values[key]) : values[key]) : match
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Rich text → inline-styled HTML ────────────────────────────────────
|
||||||
|
|
||||||
|
function richTextStyles(colors: ColorsGlobal): Record<string, string> {
|
||||||
|
const heading = `font-family:${FONT_HEADING};color:${colors.heading};font-weight:600;line-height:1.3;`;
|
||||||
|
const body = `font-family:${FONT_BODY};color:${colors.text};font-size:16px;line-height:1.6;`;
|
||||||
|
return {
|
||||||
|
h1: `${heading}font-size:28px;margin:0 0 16px;`,
|
||||||
|
h2: `${heading}font-size:24px;margin:0 0 14px;`,
|
||||||
|
h3: `${heading}font-size:19px;margin:0 0 10px;color:${colors.subheading};`,
|
||||||
|
p: `${body}margin:0 0 14px;`,
|
||||||
|
ul: `${body}margin:0 0 14px;padding-left:24px;`,
|
||||||
|
ol: `${body}margin:0 0 14px;padding-left:24px;`,
|
||||||
|
li: `${body}margin:0 0 4px;`,
|
||||||
|
blockquote: `${body}margin:0 0 14px;padding-left:14px;border-left:3px solid ${colors.primary};color:${colors.subheading};font-style:italic;`,
|
||||||
|
a: `color:${colors.accent};text-decoration:underline;`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function styleRichText(html: string, ctx: EmailContext): string {
|
||||||
|
const styles = richTextStyles(ctx.colors);
|
||||||
|
return html
|
||||||
|
.replace(/<(h1|h2|h3|p|ul|ol|li|blockquote|a)(\s[^>]*)?>/gi, (_match, rawTag: string, rawAttrs = '') => {
|
||||||
|
const tag = rawTag.toLowerCase();
|
||||||
|
let attrs = String(rawAttrs);
|
||||||
|
const existing = attrs.match(/\sstyle\s*=\s*"([^"]*)"/i);
|
||||||
|
if (existing) {
|
||||||
|
attrs = attrs.replace(existing[0], ` style="${styles[tag]}${existing[1]}"`);
|
||||||
|
} else {
|
||||||
|
attrs += ` style="${styles[tag]}"`;
|
||||||
|
}
|
||||||
|
return `<${tag}${attrs}>`;
|
||||||
|
})
|
||||||
|
.replace(/\shref\s*=\s*"(\/[^"]*)"/gi, (_m, href: string) => ` href="${escapeHtml(absoluteUrl(href, ctx.siteUrl))}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeEntities(text: string): string {
|
||||||
|
return text
|
||||||
|
.replace(/ /g, ' ')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/&/g, '&');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function htmlToText(html: string, siteUrl = ''): string {
|
||||||
|
return decodeEntities(
|
||||||
|
html
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')
|
||||||
|
.replace(/<li[^>]*>/gi, '- ')
|
||||||
|
.replace(/<\/(p|h1|h2|h3|ul|ol|blockquote|div)>/gi, '\n\n')
|
||||||
|
.replace(/<\/li>/gi, '\n')
|
||||||
|
.replace(/<a\s[^>]*href\s*=\s*"([^"]*)"[^>]*>(.*?)<\/a>/gi, (_m, href: string, label: string) => {
|
||||||
|
const url = absoluteUrl(href, siteUrl);
|
||||||
|
const text = label.replace(/<[^>]+>/g, '');
|
||||||
|
return text && text !== url ? `${text} (${url})` : url;
|
||||||
|
})
|
||||||
|
.replace(/<[^>]+>/g, '')
|
||||||
|
)
|
||||||
|
.replace(/[ \t]+\n/g, '\n')
|
||||||
|
.replace(/\n{3,}/g, '\n\n')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Blocks ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function row(content: string, padding = '8px 32px', align = 'left'): string {
|
||||||
|
return `<tr><td align="${align}" style="padding:${padding};text-align:${align};">${content}</td></tr>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sectionTitle(title: string, ctx: EmailContext): string {
|
||||||
|
if (!title) return '';
|
||||||
|
return `<h3 style="font-family:${FONT_HEADING};color:${ctx.colors.heading};font-size:19px;font-weight:600;line-height:1.3;margin:0 0 12px;">${escapeHtml(title)}</h3>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function detailTable(rows: [string, string][], ctx: EmailContext): string {
|
||||||
|
const cells = rows
|
||||||
|
.map(
|
||||||
|
([label, value]) =>
|
||||||
|
`<tr><td valign="top" style="padding:6px 12px 6px 0;font-family:${FONT_BODY};font-size:14px;line-height:1.5;color:${ctx.colors.subheading};white-space:nowrap;">${escapeHtml(label)}</td><td valign="top" style="padding:6px 0;font-family:${FONT_BODY};font-size:15px;line-height:1.5;color:${ctx.colors.text};">${value}</td></tr>`
|
||||||
|
)
|
||||||
|
.join('');
|
||||||
|
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${cells}</table>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function boxed(inner: string, ctx: EmailContext): string {
|
||||||
|
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:${ctx.colors.background};border:1px solid ${BORDER};border-radius:8px;"><tr><td style="padding:20px 22px;">${inner}</td></tr></table>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBookingDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||||
|
const cell = `font-family:${FONT_BODY};color:${ctx.colors.text};`;
|
||||||
|
const lines = ctx.lines
|
||||||
|
.map((line) => {
|
||||||
|
const when = formatLineWhen(line, ctx.timezone);
|
||||||
|
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||||
|
return `<tr>
|
||||||
|
<td valign="top" style="${cell}padding:10px 12px 10px 0;border-bottom:1px solid ${BORDER};">
|
||||||
|
<div style="font-size:16px;font-weight:600;line-height:1.4;">${escapeHtml(qty + line.name)}</div>
|
||||||
|
${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">${escapeHtml(when)}</div>` : ''}
|
||||||
|
</td>
|
||||||
|
<td valign="top" align="right" style="${cell}padding:10px 0;border-bottom:1px solid ${BORDER};font-size:15px;white-space:nowrap;">${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))}</td>
|
||||||
|
</tr>`;
|
||||||
|
})
|
||||||
|
.join('');
|
||||||
|
const total = `<tr><td style="${cell}padding:12px 12px 0 0;font-size:16px;font-weight:700;">Total paid</td><td align="right" style="${cell}padding:12px 0 0;font-size:16px;font-weight:700;white-space:nowrap;">${escapeHtml(formatMoney(ctx.total, ctx.currency))}</td></tr>`;
|
||||||
|
const table = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${lines}${total}</table>`;
|
||||||
|
return boxed(sectionTitle(block.data.title ?? '', ctx) + table, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||||
|
const link = `color:${ctx.colors.accent};text-decoration:underline;`;
|
||||||
|
const { name, email, phone, notes } = ctx.customer;
|
||||||
|
const rows: [string, string][] = [['Name', escapeHtml(name)]];
|
||||||
|
if (email) rows.push(['Email', `<a href="mailto:${escapeHtml(email)}" style="${link}">${escapeHtml(email)}</a>`]);
|
||||||
|
if (phone) rows.push(['Phone', `<a href="tel:${escapeHtml(phone.replace(/\s+/g, ''))}" style="${link}">${escapeHtml(phone)}</a>`]);
|
||||||
|
if (notes) rows.push(['Notes', escapeHtml(notes).replace(/\n/g, '<br>')]);
|
||||||
|
return boxed(sectionTitle(block.data.title ?? '', ctx) + detailTable(rows, ctx), ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderContactInfo(block: EmailBlock, ctx: EmailContext): string {
|
||||||
|
const link = `color:${ctx.colors.accent};text-decoration:underline;`;
|
||||||
|
const { businessName, address, phone, email } = ctx.business;
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (businessName) parts.push(`<strong>${escapeHtml(businessName)}</strong>`);
|
||||||
|
if (address) parts.push(escapeHtml(address).replace(/\n/g, '<br>'));
|
||||||
|
if (phone) parts.push(`<a href="tel:${escapeHtml(phone.replace(/\s+/g, ''))}" style="${link}">${escapeHtml(phone)}</a>`);
|
||||||
|
if (email) parts.push(`<a href="mailto:${escapeHtml(email)}" style="${link}">${escapeHtml(email)}</a>`);
|
||||||
|
if (ctx.siteUrl) parts.push(`<a href="${escapeHtml(ctx.siteUrl)}" style="${link}">${escapeHtml(ctx.siteUrl.replace(/^https?:\/\//, ''))}</a>`);
|
||||||
|
const body = `<p style="font-family:${FONT_BODY};color:${ctx.colors.text};font-size:15px;line-height:1.7;margin:0;">${parts.join('<br>')}</p>`;
|
||||||
|
return sectionTitle(block.data.title ?? '', ctx) + body;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlockHtml(block: EmailBlock, ctx: EmailContext, values: Record<string, string>): string {
|
||||||
|
const data = block.data || {};
|
||||||
|
switch (block.type) {
|
||||||
|
case 'text':
|
||||||
|
return row(styleRichText(fillPlaceholders(data.content || '', values, true), ctx));
|
||||||
|
case 'image': {
|
||||||
|
if (!data.url) return '';
|
||||||
|
const width = Math.round((CONTENT_WIDTH * (Number(data.width) || 100)) / 100);
|
||||||
|
const align = data.alignment || 'center';
|
||||||
|
const img = `<img src="${escapeHtml(absoluteUrl(data.url, ctx.siteUrl))}" alt="${escapeHtml(data.alt || '')}" width="${width}" style="display:inline-block;width:100%;max-width:${width}px;height:auto;border:0;border-radius:6px;">`;
|
||||||
|
const href = fillPlaceholders(data.href || '', values, false);
|
||||||
|
return row(href ? `<a href="${escapeHtml(absoluteUrl(href, ctx.siteUrl))}">${img}</a>` : img, '8px 32px', align);
|
||||||
|
}
|
||||||
|
case 'button': {
|
||||||
|
const color = data.color || ctx.colors.primary;
|
||||||
|
const href = escapeHtml(absoluteUrl(fillPlaceholders(data.href || '', values, false), ctx.siteUrl));
|
||||||
|
const label = fillPlaceholders(data.label || '', values, true);
|
||||||
|
const button = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="display:inline-table;"><tr><td bgcolor="${escapeHtml(color)}" style="background:${escapeHtml(color)};border-radius:6px;"><a href="${href}" style="display:inline-block;padding:13px 28px;font-family:${FONT_BODY};font-size:16px;font-weight:600;line-height:1.2;color:#ffffff;text-decoration:none;border-radius:6px;">${label}</a></td></tr></table>`;
|
||||||
|
return row(button, '12px 32px', data.alignment || 'center');
|
||||||
|
}
|
||||||
|
case 'spacer': {
|
||||||
|
const height = Math.max(0, Number(data.height) || 24);
|
||||||
|
return `<tr><td style="height:${height}px;line-height:${height}px;font-size:0;"> </td></tr>`;
|
||||||
|
}
|
||||||
|
case 'divider':
|
||||||
|
return row(`<div style="border-top:1px solid ${BORDER};font-size:0;line-height:0;"> </div>`, '16px 32px');
|
||||||
|
case 'booking_details':
|
||||||
|
return row(renderBookingDetails(block, ctx), '12px 32px');
|
||||||
|
case 'customer_details':
|
||||||
|
return row(renderCustomerDetails(block, ctx), '12px 32px');
|
||||||
|
case 'contact_info':
|
||||||
|
return row(renderContactInfo(block, ctx), '12px 32px');
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderBlockText(block: EmailBlock, ctx: EmailContext, values: Record<string, string>): string {
|
||||||
|
const data = block.data || {};
|
||||||
|
const title = data.title ? `${String(data.title).toUpperCase()}\n` : '';
|
||||||
|
switch (block.type) {
|
||||||
|
case 'text':
|
||||||
|
// Escape so values survive tag stripping; htmlToText decodes them again.
|
||||||
|
return htmlToText(fillPlaceholders(data.content || '', values, true), ctx.siteUrl);
|
||||||
|
case 'button': {
|
||||||
|
const href = absoluteUrl(fillPlaceholders(data.href || '', values, false), ctx.siteUrl);
|
||||||
|
return `${fillPlaceholders(data.label || '', values, false)}: ${href}`;
|
||||||
|
}
|
||||||
|
case 'divider':
|
||||||
|
return '----------------------------------------';
|
||||||
|
case 'booking_details': {
|
||||||
|
const lines = ctx.lines.map((line) => {
|
||||||
|
const when = formatLineWhen(line, ctx.timezone);
|
||||||
|
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||||
|
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}`;
|
||||||
|
});
|
||||||
|
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}`;
|
||||||
|
}
|
||||||
|
case 'customer_details': {
|
||||||
|
const { name, email, phone, notes } = ctx.customer;
|
||||||
|
return [
|
||||||
|
`${title}Name: ${name}`,
|
||||||
|
email && `Email: ${email}`,
|
||||||
|
phone && `Phone: ${phone}`,
|
||||||
|
notes && `Notes: ${notes}`
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
case 'contact_info': {
|
||||||
|
const { businessName, address, phone, email } = ctx.business;
|
||||||
|
return title + [businessName, address, phone, email, ctx.siteUrl].filter(Boolean).join('\n');
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Document ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function renderEmail(template: Pick<EmailTemplate, 'subject' | 'blocks'>, ctx: EmailContext): RenderedEmail {
|
||||||
|
const values = placeholderValues(ctx);
|
||||||
|
const subject = fillPlaceholders(template.subject, values, false).replace(/\s+/g, ' ').trim();
|
||||||
|
const blocks = template.blocks || [];
|
||||||
|
|
||||||
|
const body = blocks.map((block) => renderBlockHtml(block, ctx, values)).join('\n');
|
||||||
|
const footerParts = [ctx.business.businessName, (ctx.business.address || '').replace(/\n/g, ', ')].filter(Boolean);
|
||||||
|
const footer = footerParts.length
|
||||||
|
? `<p style="font-family:${FONT_BODY};font-size:12px;line-height:1.6;color:${ctx.colors.subheading};margin:16px 0 0;">${footerParts.map(escapeHtml).join(' · ')}</p>`
|
||||||
|
: '';
|
||||||
|
|
||||||
|
const html = `<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<meta name="supported-color-schemes" content="light">
|
||||||
|
<title>${escapeHtml(subject)}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:0;background:${ctx.colors.background};">
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background:${ctx.colors.background};">
|
||||||
|
<tr><td align="center" style="padding:32px 12px;">
|
||||||
|
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600" style="width:100%;max-width:600px;background:#ffffff;border:1px solid ${BORDER};border-radius:10px;">
|
||||||
|
<tr><td style="height:24px;line-height:24px;font-size:0;"> </td></tr>
|
||||||
|
${body}
|
||||||
|
<tr><td style="height:24px;line-height:24px;font-size:0;"> </td></tr>
|
||||||
|
</table>
|
||||||
|
${footer}
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
|
||||||
|
const text = blocks
|
||||||
|
.map((block) => renderBlockText(block, ctx, values))
|
||||||
|
.filter((part) => part.trim())
|
||||||
|
.join('\n\n');
|
||||||
|
|
||||||
|
return { subject, html, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Realistic fake data for the admin preview and "send test email". */
|
||||||
|
export function sampleEmailContext(options: {
|
||||||
|
business: FooterGlobal;
|
||||||
|
colors: ColorsGlobal;
|
||||||
|
siteUrl: string;
|
||||||
|
timezone: string;
|
||||||
|
currency: string;
|
||||||
|
service?: { name: string; price: number; duration: number | null };
|
||||||
|
}): EmailContext {
|
||||||
|
const service = options.service ?? { name: 'Relaxing full-body massage', price: 90, duration: 60 };
|
||||||
|
const start = new Date();
|
||||||
|
start.setUTCDate(start.getUTCDate() + 3);
|
||||||
|
start.setUTCHours(9, 0, 0, 0);
|
||||||
|
const end = new Date(start.getTime() + (service.duration || 60) * 60_000);
|
||||||
|
return {
|
||||||
|
orderId: 'SAMPLE123',
|
||||||
|
total: service.price,
|
||||||
|
currency: options.currency,
|
||||||
|
customer: {
|
||||||
|
name: 'Jane Example',
|
||||||
|
email: 'jane@example.com',
|
||||||
|
phone: '+47 400 00 000',
|
||||||
|
notes: 'First visit — slight lower back tension.'
|
||||||
|
},
|
||||||
|
lines: [{ name: service.name, price: service.price, quantity: 1, start: start.toISOString(), end: end.toISOString() }],
|
||||||
|
business: options.business,
|
||||||
|
colors: options.colors,
|
||||||
|
siteUrl: options.siteUrl,
|
||||||
|
timezone: options.timezone
|
||||||
|
};
|
||||||
|
}
|
||||||
69
packages/shared/src/server/email/ics.ts
Normal file
69
packages/shared/src/server/email/ics.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
// Minimal RFC 5545 calendar file for booking confirmations.
|
||||||
|
// METHOD:PUBLISH (not REQUEST) so mail clients offer "Add to calendar"
|
||||||
|
// rather than treating it as a meeting invite that expects an RSVP.
|
||||||
|
|
||||||
|
export type IcsEvent = {
|
||||||
|
uid: string;
|
||||||
|
start: string; // ISO
|
||||||
|
end: string; // ISO
|
||||||
|
summary: string;
|
||||||
|
description?: string;
|
||||||
|
location?: string;
|
||||||
|
url?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function formatUtc(iso: string): string {
|
||||||
|
return new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeText(value: string): string {
|
||||||
|
return value.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,').replace(/\r?\n/g, '\\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fold lines to 75 octets as the spec requires (continuations start with a space). */
|
||||||
|
function fold(line: string): string {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const parts: string[] = [];
|
||||||
|
let current = '';
|
||||||
|
let bytes = 0;
|
||||||
|
for (const char of line) {
|
||||||
|
const size = encoder.encode(char).length;
|
||||||
|
const limit = parts.length === 0 ? 75 : 74;
|
||||||
|
if (bytes + size > limit) {
|
||||||
|
parts.push(current);
|
||||||
|
current = '';
|
||||||
|
bytes = 0;
|
||||||
|
}
|
||||||
|
current += char;
|
||||||
|
bytes += size;
|
||||||
|
}
|
||||||
|
parts.push(current);
|
||||||
|
return parts.join('\r\n ');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildIcs(events: IcsEvent[], productName: string): string {
|
||||||
|
const stamp = formatUtc(new Date().toISOString());
|
||||||
|
const lines = [
|
||||||
|
'BEGIN:VCALENDAR',
|
||||||
|
'VERSION:2.0',
|
||||||
|
`PRODID:-//${escapeText(productName)}//Booking//EN`,
|
||||||
|
'CALSCALE:GREGORIAN',
|
||||||
|
'METHOD:PUBLISH'
|
||||||
|
];
|
||||||
|
for (const event of events) {
|
||||||
|
lines.push(
|
||||||
|
'BEGIN:VEVENT',
|
||||||
|
`UID:${event.uid}`,
|
||||||
|
`DTSTAMP:${stamp}`,
|
||||||
|
`DTSTART:${formatUtc(event.start)}`,
|
||||||
|
`DTEND:${formatUtc(event.end)}`,
|
||||||
|
`SUMMARY:${escapeText(event.summary)}`
|
||||||
|
);
|
||||||
|
if (event.description) lines.push(`DESCRIPTION:${escapeText(event.description)}`);
|
||||||
|
if (event.location) lines.push(`LOCATION:${escapeText(event.location)}`);
|
||||||
|
if (event.url) lines.push(`URL:${event.url}`);
|
||||||
|
lines.push('STATUS:CONFIRMED', 'END:VEVENT');
|
||||||
|
}
|
||||||
|
lines.push('END:VCALENDAR');
|
||||||
|
return lines.map(fold).join('\r\n') + '\r\n';
|
||||||
|
}
|
||||||
236
packages/shared/src/server/email/index.ts
Normal file
236
packages/shared/src/server/email/index.ts
Normal file
|
|
@ -0,0 +1,236 @@
|
||||||
|
import type PocketBase from 'pocketbase';
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
|
import { env as publicEnv } from '$env/dynamic/public';
|
||||||
|
import {
|
||||||
|
defaultColors,
|
||||||
|
defaultFooter,
|
||||||
|
type ColorsGlobal,
|
||||||
|
type CustomerDetails,
|
||||||
|
type EmailTemplate,
|
||||||
|
type EmailTemplateKey,
|
||||||
|
type FooterGlobal
|
||||||
|
} from '../../types';
|
||||||
|
import { normalizeEmailTemplate } from '../../email/defaults';
|
||||||
|
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine } from '../../email/render';
|
||||||
|
import { buildIcs } from './ics';
|
||||||
|
import { sendEmail, type SendResult } from './transport';
|
||||||
|
|
||||||
|
export { sendEmail, isEmailConfigured, emailSender, type SendResult, type OutgoingEmail } from './transport';
|
||||||
|
export { buildIcs, type IcsEvent } from './ics';
|
||||||
|
|
||||||
|
export type EmailKind = 'customer' | 'client';
|
||||||
|
|
||||||
|
const TEMPLATE_KEY: Record<EmailKind, EmailTemplateKey> = {
|
||||||
|
customer: 'customer_confirmation',
|
||||||
|
client: 'client_alert'
|
||||||
|
};
|
||||||
|
|
||||||
|
const SENT_AT_FIELD: Record<EmailKind, string> = {
|
||||||
|
customer: 'customerEmailSentAt',
|
||||||
|
client: 'clientEmailSentAt'
|
||||||
|
};
|
||||||
|
|
||||||
|
// Prefixes for per-kind lines in orders.emailError, so resending one email
|
||||||
|
// only replaces that email's error line.
|
||||||
|
const ERROR_PREFIX: Record<EmailKind, string> = {
|
||||||
|
customer: 'Customer email',
|
||||||
|
client: 'Alert email'
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EmailOutcome = 'sent' | 'logged' | 'disabled' | 'failed';
|
||||||
|
|
||||||
|
export type EmailSettings = {
|
||||||
|
business: FooterGlobal;
|
||||||
|
colors: ColorsGlobal;
|
||||||
|
siteUrl: string;
|
||||||
|
timezone: string;
|
||||||
|
currency: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function getGlobalData<T extends object>(pb: PocketBase, key: string, fallback: T): Promise<T> {
|
||||||
|
try {
|
||||||
|
const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
|
||||||
|
return { ...fallback, ...(record.data || {}) };
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Public site URL — the admin app's ORIGIN is the admin subdomain, so prefer PUBLIC_SITE_URL. */
|
||||||
|
export function emailSiteUrl(): string {
|
||||||
|
return (publicEnv.PUBLIC_SITE_URL || env.ORIGIN || '').replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> {
|
||||||
|
const [business, colors] = await Promise.all([
|
||||||
|
getGlobalData(pb, 'footer', defaultFooter),
|
||||||
|
getGlobalData(pb, 'colors', defaultColors)
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
business,
|
||||||
|
colors,
|
||||||
|
siteUrl: emailSiteUrl(),
|
||||||
|
timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
|
||||||
|
currency: env.STRIPE_CURRENCY || 'eur'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The saved template for `key`, or the built-in default if none was saved (or the collection is missing). */
|
||||||
|
export async function loadEmailTemplate(pb: PocketBase, key: EmailTemplateKey): Promise<EmailTemplate & { id?: string }> {
|
||||||
|
const record = await pb
|
||||||
|
.collection('email_templates')
|
||||||
|
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
||||||
|
.catch(() => null);
|
||||||
|
return { ...normalizeEmailTemplate(key, record), id: record?.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSettings): string | null {
|
||||||
|
const host = settings.siteUrl.replace(/^https?:\/\//, '').replace(/[:/].*$/, '') || 'localhost';
|
||||||
|
const events = ctx.lines.flatMap((line, i) =>
|
||||||
|
line.start
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
uid: `${ctx.orderId}-${lineIds[i] ?? i}@${host}`,
|
||||||
|
start: line.start,
|
||||||
|
end: line.end || new Date(new Date(line.start).getTime() + 60 * 60_000).toISOString(),
|
||||||
|
summary: `${line.name} – ${settings.business.businessName}`.replace(/ – $/, ''),
|
||||||
|
description: `Booking reference: ${ctx.orderId}`,
|
||||||
|
location: (settings.business.address || '').replace(/\n/g, ', '),
|
||||||
|
url: settings.siteUrl || undefined
|
||||||
|
}
|
||||||
|
]
|
||||||
|
: []
|
||||||
|
);
|
||||||
|
return events.length ? buildIcs(events, settings.business.businessName || 'Booking') : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOrderContext(pb: PocketBase, orderId: string, settings: EmailSettings) {
|
||||||
|
const order = await pb.collection('orders').getOne(orderId);
|
||||||
|
const lineRecords = await pb
|
||||||
|
.collection('order_lines')
|
||||||
|
.getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' });
|
||||||
|
|
||||||
|
const lines: EmailLine[] = lineRecords.map((line) => {
|
||||||
|
const start = line.start ? new Date(line.start).toISOString() : null;
|
||||||
|
const slotEnd = line.expand?.slot?.end;
|
||||||
|
const duration = Number(line.expand?.item?.duration) || 0;
|
||||||
|
const end = slotEnd
|
||||||
|
? new Date(slotEnd).toISOString()
|
||||||
|
: start && duration
|
||||||
|
? new Date(new Date(start).getTime() + duration * 60_000).toISOString()
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
name: String(line.name || 'Item'),
|
||||||
|
price: Number(line.price) || 0,
|
||||||
|
quantity: Number(line.quantity) || 1,
|
||||||
|
start,
|
||||||
|
end
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const details = (order.customerDetails || {}) as Partial<CustomerDetails>;
|
||||||
|
const customer: CustomerDetails = {
|
||||||
|
name: String(details.name || ''),
|
||||||
|
email: String(details.email || order.email || ''),
|
||||||
|
phone: String(details.phone || ''),
|
||||||
|
notes: String(details.notes || '')
|
||||||
|
};
|
||||||
|
|
||||||
|
const ctx: EmailContext = {
|
||||||
|
orderId: order.id,
|
||||||
|
total: Number(order.total) || 0,
|
||||||
|
customer,
|
||||||
|
lines,
|
||||||
|
...settings
|
||||||
|
};
|
||||||
|
return { order, ctx, lineIds: lineRecords.map((line) => line.id) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render and send the booking emails for a paid order, then record the
|
||||||
|
* outcome on the order (customerEmailSentAt / clientEmailSentAt / emailError).
|
||||||
|
* Never throws — a failed email must not fail the Stripe webhook; the admin
|
||||||
|
* can resend from /orders.
|
||||||
|
*/
|
||||||
|
export async function sendOrderEmails(
|
||||||
|
pb: PocketBase,
|
||||||
|
orderId: string,
|
||||||
|
kinds: EmailKind[] = ['customer', 'client']
|
||||||
|
): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
|
||||||
|
const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {};
|
||||||
|
try {
|
||||||
|
const settings = await loadEmailSettings(pb);
|
||||||
|
const { order, ctx, lineIds } = await loadOrderContext(pb, orderId, settings);
|
||||||
|
|
||||||
|
const patch: Record<string, string> = {};
|
||||||
|
const errorLines = String(order.emailError || '')
|
||||||
|
.split('\n')
|
||||||
|
.filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind])));
|
||||||
|
|
||||||
|
for (const kind of kinds) {
|
||||||
|
const template = await loadEmailTemplate(pb, TEMPLATE_KEY[kind]);
|
||||||
|
if (!template.enabled) {
|
||||||
|
outcomes[kind] = 'disabled';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const rendered = renderEmail(template, ctx);
|
||||||
|
const to = kind === 'customer' ? ctx.customer.email : template.recipients.trim() || settings.business.email;
|
||||||
|
if (!to) {
|
||||||
|
throw new Error(
|
||||||
|
kind === 'customer'
|
||||||
|
? 'the order has no customer email'
|
||||||
|
: 'no recipient — set one on the email template or add an email to the footer settings'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const ics = kind === 'customer' ? bookingIcs(ctx, lineIds, settings) : null;
|
||||||
|
const result = await sendEmail({
|
||||||
|
to,
|
||||||
|
...rendered,
|
||||||
|
replyTo: kind === 'customer' ? settings.business.email || undefined : ctx.customer.email || undefined,
|
||||||
|
attachments: ics ? [{ filename: 'booking.ics', content: ics, contentType: 'text/calendar; charset=utf-8; method=PUBLISH' }] : undefined
|
||||||
|
});
|
||||||
|
outcomes[kind] = result.status;
|
||||||
|
if (result.status === 'sent') {
|
||||||
|
patch[SENT_AT_FIELD[kind]] = new Date().toISOString();
|
||||||
|
} else {
|
||||||
|
errorLines.push(`${ERROR_PREFIX[kind]}: not sent — SMTP is not configured (written to the server log instead)`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
outcomes[kind] = 'failed';
|
||||||
|
const message = e instanceof Error ? e.message : String(e);
|
||||||
|
errorLines.push(`${ERROR_PREFIX[kind]}: ${message}`);
|
||||||
|
console.error(`[email] ${kind} email for order ${orderId} failed:`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
patch.emailError = errorLines.join('\n').slice(0, 2000);
|
||||||
|
await pb
|
||||||
|
.collection('orders')
|
||||||
|
.update(orderId, patch)
|
||||||
|
.catch((e) => console.error(`[email] could not record email status on order ${orderId}:`, e));
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[email] could not prepare emails for order ${orderId}:`, e);
|
||||||
|
for (const kind of kinds) outcomes[kind] ??= 'failed';
|
||||||
|
}
|
||||||
|
return outcomes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render `template` with sample booking data and send it to `to` (admin "Send test email"). */
|
||||||
|
export async function sendTestEmail(
|
||||||
|
pb: PocketBase,
|
||||||
|
template: Pick<EmailTemplate, 'key' | 'subject' | 'blocks'>,
|
||||||
|
to: string,
|
||||||
|
service?: { name: string; price: number; duration: number | null }
|
||||||
|
): Promise<SendResult> {
|
||||||
|
const settings = await loadEmailSettings(pb);
|
||||||
|
const ctx = sampleEmailContext({ ...settings, service });
|
||||||
|
const rendered = renderEmail(template, ctx);
|
||||||
|
const ics = template.key === 'customer_confirmation' ? bookingIcs(ctx, ['test'], settings) : null;
|
||||||
|
return sendEmail({
|
||||||
|
to,
|
||||||
|
...rendered,
|
||||||
|
subject: `[Test] ${rendered.subject}`,
|
||||||
|
attachments: ics ? [{ filename: 'booking.ics', content: ics, contentType: 'text/calendar; charset=utf-8; method=PUBLISH' }] : undefined
|
||||||
|
});
|
||||||
|
}
|
||||||
70
packages/shared/src/server/email/transport.ts
Normal file
70
packages/shared/src/server/email/transport.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
import nodemailer, { type Transporter } from 'nodemailer';
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
|
|
||||||
|
export type OutgoingEmail = {
|
||||||
|
to: string;
|
||||||
|
subject: string;
|
||||||
|
html: string;
|
||||||
|
text: string;
|
||||||
|
replyTo?: string;
|
||||||
|
attachments?: { filename: string; content: string; contentType: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// 'logged' = SMTP isn't configured (local dev), so the email was printed to
|
||||||
|
// the server log instead of being sent.
|
||||||
|
export type SendResult = { status: 'sent'; messageId: string } | { status: 'logged' };
|
||||||
|
|
||||||
|
let transporter: Transporter | null = null;
|
||||||
|
|
||||||
|
export function isEmailConfigured(): boolean {
|
||||||
|
return Boolean(env.SMTP_HOST);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emailSender(): string {
|
||||||
|
return env.EMAIL_FROM ? `${env.EMAIL_FROM_NAME || ''} <${env.EMAIL_FROM}>`.trim() : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTransporter(): Transporter {
|
||||||
|
if (!transporter) {
|
||||||
|
const port = Number(env.SMTP_PORT) || 587;
|
||||||
|
transporter = nodemailer.createTransport({
|
||||||
|
host: env.SMTP_HOST,
|
||||||
|
port,
|
||||||
|
// 465 is implicit TLS; 587/2525 upgrade via STARTTLS.
|
||||||
|
secure: port === 465,
|
||||||
|
auth: env.SMTP_USER ? { user: env.SMTP_USER, pass: env.SMTP_PASS || '' } : undefined,
|
||||||
|
// Fail fast — nodemailer's defaults wait up to two minutes.
|
||||||
|
connectionTimeout: 10_000,
|
||||||
|
greetingTimeout: 10_000,
|
||||||
|
socketTimeout: 30_000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return transporter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send one email through the configured SMTP relay (Brevo in production).
|
||||||
|
* Throws on SMTP errors; callers decide how to record the failure.
|
||||||
|
*/
|
||||||
|
export async function sendEmail(email: OutgoingEmail): Promise<SendResult> {
|
||||||
|
if (!isEmailConfigured()) {
|
||||||
|
console.info(
|
||||||
|
`[email] SMTP_HOST is not set — logging instead of sending.\n` +
|
||||||
|
` To: ${email.to}\n Reply-To: ${email.replyTo || '-'}\n Subject: ${email.subject}\n` +
|
||||||
|
` Attachments: ${email.attachments?.map((a) => a.filename).join(', ') || '-'}\n\n${email.text}\n`
|
||||||
|
);
|
||||||
|
return { status: 'logged' };
|
||||||
|
}
|
||||||
|
if (!env.EMAIL_FROM) throw new Error('EMAIL_FROM is not set');
|
||||||
|
|
||||||
|
const info = await getTransporter().sendMail({
|
||||||
|
from: { name: env.EMAIL_FROM_NAME || '', address: env.EMAIL_FROM },
|
||||||
|
to: email.to,
|
||||||
|
replyTo: email.replyTo || undefined,
|
||||||
|
subject: email.subject,
|
||||||
|
html: email.html,
|
||||||
|
text: email.text,
|
||||||
|
attachments: email.attachments
|
||||||
|
});
|
||||||
|
return { status: 'sent', messageId: info.messageId };
|
||||||
|
}
|
||||||
|
|
@ -170,6 +170,9 @@ export type OrderRecord = {
|
||||||
stripePaymentIntentId: string;
|
stripePaymentIntentId: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
lines?: OrderLine[];
|
lines?: OrderLine[];
|
||||||
|
customerEmailSentAt?: string;
|
||||||
|
clientEmailSentAt?: string;
|
||||||
|
emailError?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type OrderLine = {
|
export type OrderLine = {
|
||||||
|
|
@ -199,6 +202,38 @@ export type CheckoutBlockData = {
|
||||||
notesLabel?: string;
|
notesLabel?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ── Email types ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Email blocks are a separate, smaller set than page blocks: email clients
|
||||||
|
// only render table layouts with inline styles, so each type has its own
|
||||||
|
// renderer in $shared/email/render.
|
||||||
|
export type EmailBlockType =
|
||||||
|
| 'text'
|
||||||
|
| 'image'
|
||||||
|
| 'button'
|
||||||
|
| 'spacer'
|
||||||
|
| 'divider'
|
||||||
|
| 'booking_details'
|
||||||
|
| 'customer_details'
|
||||||
|
| 'contact_info';
|
||||||
|
|
||||||
|
export type EmailBlock = {
|
||||||
|
id: string;
|
||||||
|
type: EmailBlockType;
|
||||||
|
data: Record<string, any>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type EmailTemplateKey = 'customer_confirmation' | 'client_alert';
|
||||||
|
|
||||||
|
export type EmailTemplate = {
|
||||||
|
key: EmailTemplateKey;
|
||||||
|
subject: string;
|
||||||
|
blocks: EmailBlock[];
|
||||||
|
// Comma-separated addresses; only used by client_alert (falls back to the footer email).
|
||||||
|
recipients: string;
|
||||||
|
enabled: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
export type ColorsGlobal = {
|
export type ColorsGlobal = {
|
||||||
background: string;
|
background: string;
|
||||||
heading: string;
|
heading: string;
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{
|
{
|
||||||
"id": "text_slug00001",
|
"id": "text_slug00001",
|
||||||
"name": "slug",
|
"name": "slug",
|
||||||
|
|
@ -75,6 +76,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{
|
{
|
||||||
"id": "text_key000001",
|
"id": "text_key000001",
|
||||||
"name": "key",
|
"name": "key",
|
||||||
|
|
@ -116,6 +118,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{
|
{
|
||||||
"id": "file_file00001",
|
"id": "file_file00001",
|
||||||
"name": "file",
|
"name": "file",
|
||||||
|
|
@ -170,6 +173,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{
|
{
|
||||||
"id": "text_eventname",
|
"id": "text_eventname",
|
||||||
"name": "name",
|
"name": "name",
|
||||||
|
|
@ -302,6 +306,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "text_itemname01", "name": "name", "type": "text", "system": false, "required": true, "presentable": true, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
|
{ "id": "text_itemname01", "name": "name", "type": "text", "system": false, "required": true, "presentable": true, "unique": false, "options": { "min": null, "max": 180, "pattern": "" } },
|
||||||
{ "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
{ "id": "text_itemdesc01", "name": "description", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } },
|
||||||
{ "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "id": "num_itemprice01", "name": "price", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||||
|
|
@ -326,6 +331,7 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "rel_slotitem001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_slotitem001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "date_slotstart0", "name": "start", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_slotstart0", "name": "start", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
{ "id": "date_slotend000", "name": "end", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_slotend000", "name": "end", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
|
|
@ -352,6 +358,7 @@
|
||||||
"updateRule": "",
|
"updateRule": "",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "sel_basketstat0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["active", "completed", "abandoned"] },
|
{ "id": "sel_basketstat0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["active", "completed", "abandoned"] },
|
||||||
{ "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
{ "id": "date_basketexp0", "name": "expiresAt", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
{ "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
|
{ "id": "text_basketemai", "name": "email", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
|
||||||
|
|
@ -375,6 +382,7 @@
|
||||||
"updateRule": "",
|
"updateRule": "",
|
||||||
"deleteRule": "",
|
"deleteRule": "",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_blbasket0001", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_blitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
|
|
@ -399,12 +407,16 @@
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@request.auth.id != ''",
|
"deleteRule": "@request.auth.id != ''",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_orderbasket0", "name": "basket", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_baskets0001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
|
{ "id": "text_orderemail0", "name": "email", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 254, "pattern": "" } },
|
||||||
{ "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } },
|
{ "id": "json_ordercustde", "name": "customerDetails", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 100000 } },
|
||||||
{ "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
{ "id": "num_ordertotal01", "name": "total", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 0, "max": null } },
|
||||||
{ "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] },
|
{ "id": "sel_orderstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["pending", "paid", "refunded"] },
|
||||||
{ "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } }
|
{ "id": "text_orderstripe0", "name": "stripePaymentIntentId", "type": "text", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": null, "max": 200, "pattern": "" } },
|
||||||
|
{ "id": "date_ordcustmail", "name": "customerEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
|
{ "id": "date_ordclntmail", "name": "clientEmailSentAt", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
|
||||||
|
{ "id": "text_ordmailerr0", "name": "emailError", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 2000, "pattern": "" } }
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
"CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)"
|
"CREATE INDEX `idx_orders_basket` ON `orders` (`basket`)"
|
||||||
|
|
@ -423,6 +435,7 @@
|
||||||
"updateRule": "",
|
"updateRule": "",
|
||||||
"deleteRule": "",
|
"deleteRule": "",
|
||||||
"fields": [
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
{ "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_olorder00001", "name": "order", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "rel_olitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_olitem000001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
{ "id": "rel_olslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
{ "id": "rel_olslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null },
|
||||||
|
|
@ -437,5 +450,29 @@
|
||||||
],
|
],
|
||||||
"autodate": true,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "pbc_emailtpl0001",
|
||||||
|
"name": "email_templates",
|
||||||
|
"type": "base",
|
||||||
|
"system": false,
|
||||||
|
"listRule": "@request.auth.id != ''",
|
||||||
|
"viewRule": "@request.auth.id != ''",
|
||||||
|
"createRule": "@request.auth.id != ''",
|
||||||
|
"updateRule": "@request.auth.id != ''",
|
||||||
|
"deleteRule": "@request.auth.id != ''",
|
||||||
|
"fields": [
|
||||||
|
{ "id": "text3208210256", "name": "id", "type": "text", "system": true, "required": true, "presentable": false, "hidden": false, "primaryKey": true, "autogeneratePattern": "[a-z0-9]{15}", "min": 15, "max": 15, "pattern": "^[a-z0-9]+$" },
|
||||||
|
{ "id": "text_etplkey0001", "name": "key", "type": "text", "system": false, "required": true, "presentable": true, "unique": true, "options": { "min": null, "max": 80, "pattern": "" } },
|
||||||
|
{ "id": "text_etplsubject", "name": "subject", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 300, "pattern": "" } },
|
||||||
|
{ "id": "json_etplblocks0", "name": "blocks", "type": "json", "system": false, "required": false, "presentable": false, "unique": false, "options": { "maxSize": 2000000 } },
|
||||||
|
{ "id": "text_etplrecips0", "name": "recipients", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } },
|
||||||
|
{ "id": "bool_etplenabled", "name": "enabled", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }
|
||||||
|
],
|
||||||
|
"indexes": [
|
||||||
|
"CREATE UNIQUE INDEX `idx_email_templates_key` ON `email_templates` (`key`)"
|
||||||
|
],
|
||||||
|
"autodate": true,
|
||||||
|
"options": {}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue