diff --git a/.env.example b/.env.example index d131456..9211223 100644 --- a/.env.example +++ b/.env.example @@ -1,17 +1,15 @@ # Secrets read by docker-compose.yml via ${VAR:-} substitution. # Copy to .env at the project root and fill in. -# Stripe. The secret key and webhook secret go to PocketBase only (the shop -# API in pocketbase/pb_hooks); the public app gets just the publishable key. +# Stripe STRIPE_SECRET_KEY=sk_test_... PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_CURRENCY=eur -# Shared by PocketBase and the public app so the public app can record -# booking-email status on orders (its only write). Generate a long random -# value, e.g.: openssl rand -hex 32 -INTERNAL_API_SECRET= +# PocketBase superuser credentials (used by server-side basket/checkout/webhook APIs) +POCKETBASE_ADMIN_EMAIL=admin@example.com +POCKETBASE_ADMIN_PASSWORD=changeme # Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP). # Leave SMTP_HOST empty in development: emails are then written to the diff --git a/AGENTS.md b/AGENTS.md index 60af89e..d34dda3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Stack - **SvelteKit 2** (SSR, Svelte 5 runes mode) — all `.svelte` files use `$state`, `$derived`, `$props()` etc. -- **PocketBase** — server pinned to **0.23.12** (`docker-compose.yml`), REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. Bump the server version deliberately (changelog, backup, test migrations). +- **PocketBase** — REST API via the `pocketbase` SDK (v0.26). Auth, DB, and image storage. - **Tailwind CSS v4** + **DaisyUI 5** — utility-first CSS with DaisyUI components for admin; custom theme for the public site. - **Docker Compose** — four services: `app-admin`, `app-public`, `pocketbase`, and `caddy` (reverse proxy). @@ -14,7 +14,7 @@ packages/shared/src/ # Shared code (types, calendar utils, blocks, pb, app-admin/ # SvelteKit admin app (serves admin.) ├── src/ │ ├── lib/ -│ │ ├── admin/ # Admin UI components (BlockList, Modal, editors, confirm/unsaved helpers) +│ │ ├── admin/ # Admin UI components (BlockList, editors) │ │ ├── blocks/ # Re-exports from $shared/blocks (block renderers live in shared) │ │ ├── pb.ts # Re-exports from $shared/pb + app-specific uploadMedia │ │ ├── types.ts # Re-exports from $shared @@ -22,18 +22,17 @@ app-admin/ # SvelteKit admin app (serves admin.) │ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared -│ │ └── server/ # Re-exports from $shared/server + admin helpers (actions.ts, pages.ts) +│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket) │ ├── routes/ -│ │ ├── +layout.svelte # Root layout (admin shell: grouped sidebar; bare on /login and /preview) +│ │ ├── +layout.svelte # Root layout (admin shell: navbar, export/import, logout) │ │ ├── login/ # Admin login │ │ ├── pages/ # Page CRUD + block editor -│ │ ├── calendar/ # Event CRUD (menu label: Events) -│ │ ├── items/ # Service/product CRUD (menu label: Services & products) +│ │ ├── calendar/ # Event CRUD +│ │ ├── items/ # Service/product CRUD │ │ ├── slots/ # Bookable time slot CRUD │ │ ├── orders/ # Order list + booking-email status/resend │ │ ├── emails/ # Block-based booking email editor (live preview, test send) -│ │ ├── globals/ # Header/footer/colors editor (menu label: Site design) -│ │ ├── backup/ # Export/import UI (calls api/export, api/import) +│ │ ├── globals/ # Header/footer/colors editor │ │ ├── preview/ # Draft preview via sessionStorage (same-origin) │ │ └── api/ # upload, export, import endpoints │ ├── hooks.server.ts # Auth guard — all routes except /login @@ -54,7 +53,7 @@ app-public/ # SvelteKit public app (serves *.) │ │ ├── scrollReveal.ts # Re-exports from $shared │ │ ├── stripe-client.ts # Re-exports from $shared │ │ ├── basket.svelte.ts # Re-exports from $shared -│ │ └── server/ # shop.ts (client for PocketBase's /api/shop routes, basket cookie) + $shared/server re-exports +│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket); stripe.server.ts is public-only │ ├── routes/ │ │ ├── +layout.svelte # Root layout (always renders Header/Footer) │ │ ├── +page.svelte # Home page (slug=home) @@ -68,8 +67,7 @@ app-public/ # SvelteKit public app (serves *.) ├── svelte.config.js # Adapter-node, runes mode forced, $shared alias ├── vite.config.ts # Tailwind v4 + SvelteKit plugins └── package.json -pocketbase/pb_migrations/ # JS migrations, mounted at /pb_migrations; applied on PocketBase start -pocketbase/pb_hooks/ # JS hooks, mounted at /pb_hooks: the shop API (/api/shop/*) + hold-sweeping cron +pocketbase/pb_data/ # PocketBase data (volume-mounted) docker-compose.yml # app-admin + app-public + pocketbase + caddy services Caddyfile # Subdomain-based routing ``` @@ -126,25 +124,14 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type - `$lib/pb.ts` exports `createPocketBase()`, `getFileUrl()`, `uploadMedia()` - Collections: `pages` (slug, title, blocks[], published), `globals` (key, data), `media` (file, alt), `email_templates` (key, subject, blocks[], recipients, enabled) - Server load functions use `locals.pb.collection('pages').getFirstListItem()` -- **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them). -- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting. -- **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules. -- **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only). ### Styling - **Public site**: Custom theme via `@theme` in `app.css` — colors: `warm`, `charcoal`, `sage`, `sage-dark`, `terracotta`. Fonts: `DM Sans` (body), `Playfair Display` (headings). -- **Admin area**: DaisyUI **5** (no `form-control` / `label-text` / `*-bordered` — those are v4). Colours come from Site design via `$shared/theme`, rendered as a ` + + +
+
+ + {#if header.logo?.url} + {header.logo.alt + {:else} + ES + {/if} + Eva Shafik + + + + +
+ {#if hasItems} + + + + + {basket.count} + + + {/if} + {#if header.ctaButton?.label} + {header.ctaButton.label} + {/if} +
+
+
diff --git a/app-public/src/lib/server/basket.ts b/app-public/src/lib/server/basket.ts new file mode 100644 index 0000000..74bac8c --- /dev/null +++ b/app-public/src/lib/server/basket.ts @@ -0,0 +1 @@ +export * from '$shared/server/basket'; diff --git a/app-public/src/lib/server/pb-admin.ts b/app-public/src/lib/server/pb-admin.ts new file mode 100644 index 0000000..e9a7a46 --- /dev/null +++ b/app-public/src/lib/server/pb-admin.ts @@ -0,0 +1 @@ +export * from '$shared/server/pb-admin'; diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts deleted file mode 100644 index 2388562..0000000 --- a/app-public/src/lib/server/shop.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { error, isHttpError, json, type RequestHandler } from '@sveltejs/kit'; -import { env } from '$env/dynamic/private'; -import { getFileUrl } from '$lib/pb'; -import type { Basket, BasketLine, OrderRecord } from '$lib/types'; -import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email'; - -// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All -// basket, payment and order writes happen there; this app holds no -// PocketBase or Stripe secrets — it keeps the basket cookie and forwards. - -export const BASKET_COOKIE = 'basket_id'; -/** Cookie lifetime; PocketBase keeps the basket alive for 24h after its last change. */ -export const BASKET_COOKIE_MAX_AGE = 24 * 60 * 60; - -function shopUrl(path: string) { - return `${env.POCKETBASE_INTERNAL_URL}/api/shop${path}`; -} - -/** Call the shop API; PocketBase errors become SvelteKit errors with the same status and message. */ -export async function shopFetch(path: string, init: RequestInit = {}): Promise { - let res: Response; - try { - res = await fetch(shopUrl(path), init); - } catch (e) { - console.error('[shop] PocketBase unreachable:', e); - throw error(503, 'The shop is temporarily unavailable — please try again'); - } - if (res.status === 204) return undefined as T; - const body = await res.json().catch(() => ({})); - if (!res.ok) throw error(res.status, body?.message || `Shop request failed (${res.status})`); - return body as T; -} - -/** Wrap an API route so shop errors always reach the browser as JSON `{ message }` (never an HTML error page). */ -export function jsonErrors[0]>(handler: (event: E) => Promise) { - return async (event: E) => { - try { - return await handler(event); - } catch (e) { - if (isHttpError(e)) return json({ message: e.body.message }, { status: e.status }); - throw e; - } - }; -} - -export function postJson(path: string, data: unknown): Promise { - return shopFetch(path, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data) - }); -} - -type BasketPayload = { record: Record; lines: Record[] } | null; - -/** Map the API's raw basket records to the `Basket` type used by the UI. */ -export function mapBasket(payload: BasketPayload): Basket | null { - if (!payload) return null; - const { record, lines } = payload; - const mappedLines: BasketLine[] = lines.map((line) => { - const item = line.expand?.item; - const slot = line.expand?.slot; - const media = item?.expand?.image; - return { - id: line.id, - basket: line.basket, - item: line.item, - slot: line.slot || null, - quantity: line.quantity, - lineType: line.lineType, - itemName: item?.name, - itemPrice: item?.price, - itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, - slotStart: slot?.start, - slotEnd: slot?.end - }; - }); - return { - id: record.id, - status: record.status, - expiresAt: record.expiresAt, - email: record.email || null, - customerDetails: record.customerDetails || null, - stripePaymentIntentId: record.stripePaymentIntentId || null, - lines: mappedLines - }; -} - -/** The basket for a cookie value, or null (expired, completed, unknown). */ -export async function getBasket(basketId: string | undefined): Promise { - // Ids are PocketBase record ids; anything else can't be a basket. - if (!basketId || !/^[a-z0-9]{1,32}$/i.test(basketId)) return null; - const { basket } = await shopFetch<{ basket: BasketPayload }>(`/basket/${basketId}`); - return mapBasket(basket); -} - -export function mapOrder(order: Record, lines: Record[]): OrderRecord { - return { - id: order.id, - basket: order.basket, - email: order.email, - customerDetails: order.customerDetails, - total: order.total, - status: order.status, - stripePaymentIntentId: order.stripePaymentIntentId, - createdAt: order.created, - lines: lines.map((l) => ({ - id: l.id, - order: l.order, - item: l.item, - slot: l.slot || null, - quantity: l.quantity, - lineType: l.lineType, - name: l.name, - price: l.price, - start: l.start || null - })) - }; -} - -/** - * Send the booking emails for a new order (data supplied by PocketBase's - * webhook handler), then report the outcome back so /orders shows it. - * Never throws; runs after Stripe has had its response. - */ -export async function sendAndRecordOrderEmails(data: OrderEmailData) { - const { patch } = await sendOrderEmailsFromData(data); - const secret = env.INTERNAL_API_SECRET; - if (!secret) { - console.warn(`[email] INTERNAL_API_SECRET is not set — email status for order ${data.order.id} was not recorded`); - return; - } - await shopFetch('/order-email-status', { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-Internal-Secret': secret }, - body: JSON.stringify({ orderId: data.order.id, patch }) - }).catch((e) => console.error(`[email] could not record email status on order ${data.order.id}:`, e)); -} diff --git a/app-public/src/lib/stripe.server.ts b/app-public/src/lib/stripe.server.ts new file mode 100644 index 0000000..daf707a --- /dev/null +++ b/app-public/src/lib/stripe.server.ts @@ -0,0 +1,17 @@ +import Stripe from 'stripe'; +import { env } from '$env/dynamic/private'; + +let stripe: Stripe | null = null; + +export function getStripe(): Stripe { + if (!stripe) { + const key = env.STRIPE_SECRET_KEY; + if (!key) throw new Error('STRIPE_SECRET_KEY is not set'); + stripe = new Stripe(key); + } + return stripe; +} + +export function getCurrency(): string { + return env.STRIPE_CURRENCY || 'eur'; +} diff --git a/app-public/src/routes/+layout.server.ts b/app-public/src/routes/+layout.server.ts index bbe2ecc..f4a9947 100644 --- a/app-public/src/routes/+layout.server.ts +++ b/app-public/src/routes/+layout.server.ts @@ -1,12 +1,13 @@ import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import type { ItemRecord, SlotRecord } from '$lib/types'; -import { BASKET_COOKIE, getBasket } from '$lib/server/shop'; -import { loadShopData } from '$shared/server/shop'; +import { getFileUrl } from '$lib/pb'; +import { getAdminPb } from '$lib/server/pb-admin'; +import { BASKET_COOKIE, loadBasket, sweepExpiredHolds } from '$lib/server/basket'; import type { LayoutServerLoad } from './$types'; async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { try { - const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key })); + const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`); return record.data || fallback; } catch { return fallback; @@ -22,18 +23,57 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => { if (!header.homePage) header.homePage = defaultHeader.homePage; - // Commerce data for the public site. The listing is public data (API - // rules allow active items / available slots); the basket comes from the - // shop API in PocketBase. Failures leave the shop empty, never break a page. - const [shop, basket] = await Promise.all([ - loadShopData(locals.pb).catch((e) => { - console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e); - return null; - }), - getBasket(cookies.get(BASKET_COOKIE)).catch(() => null) - ]); - const items: ItemRecord[] = shop?.items ?? []; - const slots: SlotRecord[] = shop?.slots ?? []; + // Commerce data for the public site. + let basket = null; + let items: ItemRecord[] = []; + let slots: SlotRecord[] = []; + + try { + const pb = await getAdminPb(); + await sweepExpiredHolds(pb); + + const basketId = cookies.get(BASKET_COOKIE); + if (basketId) basket = await loadBasket(pb, basketId); + + const itemRecords = await pb + .collection('items') + .getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }) + .catch(() => []); + items = itemRecords.map((record) => { + const media = record.expand?.image; + return { + id: record.id, + name: record.name, + description: record.description || '', + price: record.price, + image: record.image || '', + imageUrl: media ? getFileUrl('media', media.id, media.file) : '', + type: record.type, + stock: record.stock ?? null, + duration: record.duration ?? null, + active: record.active + }; + }); + + const nowIso = new Date().toISOString(); + const slotRecords = await pb + .collection('slots') + .getFullList({ filter: `status = 'available' && start >= "${nowIso}"`, sort: 'start' }) + .catch(() => []); + slots = slotRecords.map((record) => ({ + id: record.id, + item: record.item, + start: record.start, + end: record.end || '', + status: record.status, + heldUntil: record.heldUntil || null, + order: record.order || null, + notes: record.notes || '' + })); + } catch (e) { + // Admin PB not configured (e.g. fresh dev env) — commerce features off. + console.warn('Commerce data unavailable:', e instanceof Error ? e.message : e); + } return { header, footer, colors, user: locals.user, basket, items, slots }; }; diff --git a/app-public/src/routes/+layout.svelte b/app-public/src/routes/+layout.svelte index 087f78d..7538aee 100644 --- a/app-public/src/routes/+layout.svelte +++ b/app-public/src/routes/+layout.svelte @@ -4,7 +4,7 @@ import Header from '$lib/components/Header.svelte'; import Footer from '$lib/components/Footer.svelte'; import { createBasketStore, setBasketContext } from '$lib/basket.svelte'; - import { rootStyleTag, siteThemeVars } from '$shared/theme'; + import { onMount } from 'svelte'; let { children, data } = $props(); @@ -16,14 +16,23 @@ // Keep the store in sync when layout data refreshes (e.g. after checkout // clears the cookie and data.basket becomes null). $effect(() => basketStore.syncFrom(data.basket ?? null)); + + onMount(() => { + if (data.colors) { + const root = document.documentElement; + root.style.setProperty('--color-bg', data.colors.background); + root.style.setProperty('--color-heading', data.colors.heading); + root.style.setProperty('--color-subheading', data.colors.subheading); + root.style.setProperty('--color-text', data.colors.text); + root.style.setProperty('--color-primary', data.colors.primary); + root.style.setProperty('--color-accent', data.colors.accent); + } + }); - - {@html rootStyleTag(siteThemeVars(data.colors))}
diff --git a/app-public/src/routes/+page.server.ts b/app-public/src/routes/+page.server.ts index eb226c7..6153b9d 100644 --- a/app-public/src/routes/+page.server.ts +++ b/app-public/src/routes/+page.server.ts @@ -16,7 +16,7 @@ export const load: PageServerLoad = async ({ locals }) => { try { const page = await locals.pb .collection('pages') - .getFirstListItem(locals.pb.filter('slug = {:slug} && published = true', { slug: homeSlug })); + .getFirstListItem(`slug = "${homeSlug}" && published = true`); let calendarEvents: CalendarEventRecord[] = []; if (hasUpcomingCalendarBlock(page.blocks || [])) { const range = getUpcomingCalendarRange(); diff --git a/app-public/src/routes/[slug]/+page.server.ts b/app-public/src/routes/[slug]/+page.server.ts index 4d6c301..5e88b53 100644 --- a/app-public/src/routes/[slug]/+page.server.ts +++ b/app-public/src/routes/[slug]/+page.server.ts @@ -7,7 +7,7 @@ export const load: PageServerLoad = async ({ params, locals }) => { try { const page = await locals.pb .collection('pages') - .getFirstListItem(locals.pb.filter('slug = {:slug} && published = true', { slug: params.slug })); + .getFirstListItem(`slug = "${params.slug}" && published = true`); let calendarEvents: CalendarEventRecord[] = []; if (hasUpcomingCalendarBlock(page.blocks || [])) { const range = getUpcomingCalendarRange(); diff --git a/app-public/src/routes/api/basket/+server.ts b/app-public/src/routes/api/basket/+server.ts index 29a1d15..1b13b3d 100644 --- a/app-public/src/routes/api/basket/+server.ts +++ b/app-public/src/routes/api/basket/+server.ts @@ -1,15 +1,54 @@ -import { json, error } from '@sveltejs/kit'; +import { json, error, type Cookies } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; -import { BASKET_COOKIE, BASKET_COOKIE_MAX_AGE, getBasket, jsonErrors, mapBasket, postJson } from '$lib/server/shop'; +import { getAdminPb } from '$lib/server/pb-admin'; +import { + BASKET_COOKIE, + BASKET_TTL_MS, + SLOT_HOLD_MS, + sweepExpiredHolds, + loadBasket, + createBasket, + touchBasket, + releaseLineHold +} from '$lib/server/basket'; +import type PocketBase from 'pocketbase'; -// Basket API for the browser. The logic (stock, slot holds, expiry) is in -// PocketBase — pocketbase/pb_hooks/shop; this route only adds the cookie. +function setBasketCookie(cookies: Cookies, basketId: string) { + cookies.set(BASKET_COOKIE, basketId, { + path: '/', + httpOnly: true, + sameSite: 'lax', + maxAge: BASKET_TTL_MS / 1000 + }); +} -export const GET: RequestHandler = jsonErrors(async ({ cookies }) => { - return json({ basket: await getBasket(cookies.get(BASKET_COOKIE)) }); -}); +/** + * Resolve the current basket from the cookie. When `create` is true and no + * valid basket exists, a new one is created (and the cookie is set). + */ +async function resolveBasket(pb: PocketBase, cookies: Cookies, create: boolean) { + const id = cookies.get(BASKET_COOKIE); + if (id) { + const basket = await loadBasket(pb, id); + if (basket) return { basket, isNew: false }; + } + if (!create) return { basket: null, isNew: false }; + const basket = await createBasket(pb); + setBasketCookie(cookies, basket.id); + return { basket, isNew: true }; +} + +export const GET: RequestHandler = async ({ cookies }) => { + const pb = await getAdminPb(); + await sweepExpiredHolds(pb); + const { basket } = await resolveBasket(pb, cookies, false); + return json({ basket }); +}; + +export const POST: RequestHandler = async ({ request, cookies }) => { + const pb = await getAdminPb(); + await sweepExpiredHolds(pb); -export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { let body: Record; try { body = await request.json(); @@ -17,17 +56,112 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { throw error(400, 'Invalid JSON body'); } - const { basket } = await postJson<{ basket: Parameters[0] }>('/basket', { - action: body.action, - itemId: body.itemId, - slotId: body.slotId, - lineId: body.lineId, - quantity: body.quantity, - basketId: cookies.get(BASKET_COOKIE) || '' - }); + const action = String(body.action || ''); - const mapped = mapBasket(basket); - // A basket is created on the first add; (re)set the cookie to keep it alive. - if (mapped) cookies.set(BASKET_COOKIE, mapped.id, { path: '/', httpOnly: true, sameSite: 'lax', maxAge: BASKET_COOKIE_MAX_AGE }); - return json({ basket: mapped }); -}); + // All mutations need a basket — lazily created on first add. + const { basket } = await resolveBasket(pb, cookies, action === 'add_item' || action === 'add_slot'); + if (!basket) throw error(400, 'No active basket — add an item first'); + + switch (action) { + case 'add_item': { + const itemId = String(body.itemId || ''); + const quantity = Math.max(1, Number(body.quantity) || 1); + if (!itemId) throw error(400, 'itemId is required'); + + const item = await pb.collection('items').getOne(itemId).catch(() => null); + if (!item || !item.active) throw error(404, 'Item not found'); + if (item.type !== 'item') throw error(400, 'Use add_slot for bookable services'); + + const existing = basket.lines.find((l) => l.lineType === 'item' && l.item === itemId); + const newQty = (existing?.quantity ?? 0) + quantity; + if (item.stock != null && newQty > item.stock) { + throw error(409, `Only ${item.stock} in stock`); + } + + if (existing) { + await pb.collection('basket_lines').update(existing.id, { quantity: newQty }); + } else { + await pb.collection('basket_lines').create({ + basket: basket.id, + item: itemId, + quantity, + lineType: 'item' + }); + } + break; + } + + case 'add_slot': { + const slotId = String(body.slotId || ''); + if (!slotId) throw error(400, 'slotId is required'); + + if (basket.lines.some((l) => l.slot === slotId)) { + throw error(409, 'Slot already in your basket'); + } + + const slot = await pb.collection('slots').getOne(slotId).catch(() => null); + if (!slot) throw error(404, 'Slot not found'); + if (slot.status !== 'available') throw error(409, 'Slot is no longer available'); + + // Atomic guard: basket_lines.slot has a partial UNIQUE index, so two + // concurrent requests cannot both create a line for the same slot. + // The line is created first; whoever loses the race gets a 409. + let line; + try { + line = await pb.collection('basket_lines').create({ + basket: basket.id, + item: slot.item, + slot: slotId, + quantity: 1, + lineType: 'slot' + }); + } catch { + throw error(409, 'Slot was just reserved by someone else'); + } + + try { + await pb.collection('slots').update(slotId, { + status: 'held', + heldUntil: new Date(Date.now() + SLOT_HOLD_MS).toISOString() + }); + } catch (e) { + // Roll back the line if the hold update failed + await pb.collection('basket_lines').delete(line.id).catch(() => {}); + throw error(500, 'Could not reserve the slot — please try again'); + } + break; + } + + case 'update_quantity': { + const lineId = String(body.lineId || ''); + const quantity = Number(body.quantity); + const line = basket.lines.find((l) => l.id === lineId); + if (!line) throw error(404, 'Line not found in your basket'); + if (line.lineType === 'slot') throw error(400, 'Slot lines have fixed quantity 1'); + if (!Number.isInteger(quantity) || quantity < 1) throw error(400, 'Quantity must be a positive integer'); + + const item = await pb.collection('items').getOne(line.item).catch(() => null); + if (item?.stock != null && quantity > item.stock) { + throw error(409, `Only ${item.stock} in stock`); + } + await pb.collection('basket_lines').update(lineId, { quantity }); + break; + } + + case 'remove_line': { + const lineId = String(body.lineId || ''); + const line = basket.lines.find((l) => l.id === lineId); + if (!line) throw error(404, 'Line not found in your basket'); + await pb.collection('basket_lines').delete(lineId); + await releaseLineHold(pb, line); + break; + } + + default: + throw error(400, `Unknown action: ${action}`); + } + + await touchBasket(pb, basket.id); + const updated = await loadBasket(pb, basket.id); + return json({ basket: updated }); +}; diff --git a/app-public/src/routes/api/checkout/create-intent/+server.ts b/app-public/src/routes/api/checkout/create-intent/+server.ts index 9172923..c56ad63 100644 --- a/app-public/src/routes/api/checkout/create-intent/+server.ts +++ b/app-public/src/routes/api/checkout/create-intent/+server.ts @@ -1,10 +1,26 @@ import { json, error } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; -import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop'; +import { getAdminPb } from '$lib/server/pb-admin'; +import { BASKET_COOKIE, SLOT_CHECKOUT_HOLD_MS, sweepExpiredHolds, loadBasket, extendBasketHolds } from '$lib/server/basket'; +import { getStripe, getCurrency } from '$lib/stripe.server'; +import type { CustomerDetails } from '$lib/types'; + +export const POST: RequestHandler = async ({ request, cookies }) => { + const pb = await getAdminPb(); + + const basketId = cookies.get(BASKET_COOKIE); + // Payment is starting — extend any held slots to the checkout hold (30 min) + // so a booked service survives the customer entering card details or + // retrying a declined card. Extend BEFORE sweeping so a slot whose hold + // just lapsed is rescued rather than released at the moment they try to pay. + if (basketId) await extendBasketHolds(pb, basketId, SLOT_CHECKOUT_HOLD_MS); + await sweepExpiredHolds(pb); + + if (!basketId) throw error(400, 'No active basket'); + const basket = await loadBasket(pb, basketId); + if (!basket) throw error(400, 'Your session has expired — please re-select your items'); + if (!basket.lines.length) throw error(400, 'Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.'); -// Starts payment: PocketBase re-validates the basket, extends slot holds and -// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). -export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { let body: Record; try { body = await request.json(); @@ -12,12 +28,75 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => { throw error(400, 'Invalid JSON body'); } - const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', { - basketId: cookies.get(BASKET_COOKIE) || '', - name: body.name, - email: body.email, - phone: body.phone, - notes: body.notes + const customer: CustomerDetails = { + name: String(body.name || '').trim(), + email: String(body.email || '').trim(), + phone: String(body.phone || '').trim(), + notes: String(body.notes || '').trim() + }; + if (!customer.name) throw error(400, 'Name is required'); + if (!customer.email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) { + throw error(400, 'A valid email is required'); + } + + // Re-validate every line server-side (source of truth for the total). + let totalCents = 0; + for (const line of basket.lines) { + const item = await pb.collection('items').getOne(line.item).catch(() => null); + if (!item || !item.active) throw error(409, `"${line.itemName ?? 'An item'}" is no longer available`); + + if (line.lineType === 'slot') { + const slot = await pb.collection('slots').getOne(line.slot!).catch(() => null); + if (!slot || slot.status !== 'held') { + throw error(409, `Your time slot for "${item.name}" has expired — please pick it again`); + } + } else { + if (item.stock != null && item.stock < line.quantity) { + throw error(409, `Only ${item.stock} of "${item.name}" left in stock`); + } + } + totalCents += Math.round(item.price * 100) * line.quantity; + } + + if (totalCents <= 0) throw error(400, 'Basket total must be positive'); + + let paymentIntent; + if (basket.stripePaymentIntentId) { + // Reuse an existing intent when possible (page reload / retry). + try { + const existing = await getStripe().paymentIntents.retrieve(basket.stripePaymentIntentId); + if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') { + paymentIntent = await getStripe().paymentIntents.update(existing.id, { + amount: totalCents, + metadata: { basket_id: basket.id } + }); + } + } catch { + // Intent missing/invalid — fall through and create a new one + } + } + + if (!paymentIntent) { + paymentIntent = await getStripe().paymentIntents.create({ + amount: totalCents, + currency: getCurrency(), + automatic_payment_methods: { enabled: true }, + receipt_email: customer.email, + metadata: { + basket_id: basket.id, + line_summary: basket.lines + .map((l) => `${l.quantity}× ${l.itemName ?? l.item}`) + .join('; ') + .slice(0, 450) + } + }); + } + + await pb.collection('baskets').update(basket.id, { + stripePaymentIntentId: paymentIntent.id, + email: customer.email, + customerDetails: customer }); - return json({ clientSecret }); -}); + + return json({ clientSecret: paymentIntent.client_secret }); +}; diff --git a/app-public/src/routes/api/webhooks/stripe/+server.ts b/app-public/src/routes/api/webhooks/stripe/+server.ts index f1aa81c..fe47d9a 100644 --- a/app-public/src/routes/api/webhooks/stripe/+server.ts +++ b/app-public/src/routes/api/webhooks/stripe/+server.ts @@ -1,25 +1,128 @@ import { json, error } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; -import { jsonErrors, sendAndRecordOrderEmails, shopFetch } from '$lib/server/shop'; -import type { OrderEmailData } from '$lib/server/email'; +import { env } from '$env/dynamic/private'; +import { getStripe } from '$lib/stripe.server'; +import { getAdminPb } from '$lib/server/pb-admin'; +import { getFileUrl } from '$lib/pb'; +import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket'; +import { sendOrderEmails } from '$lib/server/email'; +import type PocketBase from 'pocketbase'; -// Stripe webhook endpoint (keeps the URL configured in the Stripe dashboard). -// PocketBase verifies the signature and creates the order; this app only -// sends the booking emails, which it can render (pocketbase/pb_hooks/shop). -export const POST: RequestHandler = jsonErrors(async ({ request }) => { +async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { + const basketId = paymentIntent.metadata?.basket_id; + if (!basketId) return; // Not one of ours + + // Idempotency: if an order already exists for this intent, we're done. + const existing = await pb + .collection('orders') + .getFirstListItem(pb.filter('stripePaymentIntentId = {:id}', { id: paymentIntent.id })) + .catch(() => null); + if (existing) return; + + const basket = await pb.collection('baskets').getOne(basketId).catch(() => null); + if (!basket) return; + + const lines = await pb + .collection('basket_lines') + .getFullList({ filter: pb.filter('basket = {:basketId}', { basketId }), expand: 'item,slot' }); + + // Create the order + const order = await pb.collection('orders').create({ + basket: basketId, + email: basket.email || paymentIntent.receipt_email || '', + customerDetails: basket.customerDetails || {}, + total: paymentIntent.amount / 100, + status: 'paid', + stripePaymentIntentId: paymentIntent.id + }); + + // Snapshot order lines, flip slots to booked, decrement item stock + for (const line of lines) { + const item = line.expand?.item; + const slot = line.expand?.slot; + await pb.collection('order_lines').create({ + order: order.id, + item: line.item, + slot: line.slot || null, + quantity: line.quantity, + lineType: line.lineType, + name: item?.name ?? 'Unknown item', + price: item?.price ?? 0, + start: slot?.start || null + }); + + if (line.lineType === 'slot' && line.slot) { + await pb + .collection('slots') + .update(line.slot, { status: 'booked', heldUntil: null, order: order.id }) + .catch(() => {}); + } else if (line.lineType === 'item' && item?.stock != null) { + await pb + .collection('items') + .update(item.id, { stock: Math.max(0, item.stock - line.quantity) }) + .catch(() => {}); + } + } + + // Basket completed — lines can go (order_lines hold the snapshot). + for (const line of lines) { + await pb.collection('basket_lines').delete(line.id).catch(() => {}); + } + await pb.collection('baskets').update(basketId, { status: 'completed' }).catch(() => {}); + + // Confirmation to the customer + alert to the studio. Not awaited: SMTP can + // be slow and Stripe only needs the 2xx. sendOrderEmails never throws and + // records the outcome on the order, so failures can be resent from /orders. + void sendOrderEmails(pb, order.id); +} + +async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) { + const basketId = paymentIntent.metadata?.basket_id; + if (!basketId) return; + + // The card was refused (or the payment otherwise failed). Keep the slots + // held for the customer so they can retry without re-picking them — just + // reset the hold to the standard 10-minute window. Starting payment again + // (create-intent) will extend it back to 30 min. + await extendBasketHolds(pb, basketId, SLOT_HOLD_MS).catch(() => {}); + + if (paymentIntent.id) { + await pb + .collection('baskets') + .update(basketId, { stripePaymentIntentId: null }) + .catch(() => {}); + } +} + +export const POST: RequestHandler = async ({ request }) => { + const secret = env.STRIPE_WEBHOOK_SECRET; + if (!secret) throw error(500, 'STRIPE_WEBHOOK_SECRET is not configured'); + + // Signature verification MUST use the raw request body. + const body = await request.text(); const signature = request.headers.get('stripe-signature'); if (!signature) throw error(400, 'Missing Stripe-Signature header'); - // Forward the exact body: the signature covers the raw bytes. - const result = await shopFetch<{ received: boolean; orderEmail: OrderEmailData | null }>('/stripe-webhook', { - method: 'POST', - headers: { 'Content-Type': request.headers.get('content-type') || 'application/json', 'Stripe-Signature': signature }, - body: await request.text() - }); + let event; + try { + event = getStripe().webhooks.constructEvent(body, signature, secret); + } catch (e) { + throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`); + } - // Not awaited: SMTP can be slow and Stripe only needs the 2xx. Failures are - // recorded on the order and can be resent from the admin's /orders. - if (result.orderEmail) void sendAndRecordOrderEmails(result.orderEmail); + const pb = await getAdminPb(); + + switch (event.type) { + case 'payment_intent.succeeded': + await handlePaymentSucceeded(pb, event.data.object); + break; + case 'payment_intent.payment_failed': + await handlePaymentFailed(pb, event.data.object); + break; + default: + // Unhandled event types are fine — acknowledge receipt. + break; + } return json({ received: true }); -}); +}; diff --git a/app-public/src/routes/checkout/return/+page.server.ts b/app-public/src/routes/checkout/return/+page.server.ts index 61e5eda..e3346ac 100644 --- a/app-public/src/routes/checkout/return/+page.server.ts +++ b/app-public/src/routes/checkout/return/+page.server.ts @@ -1,19 +1,64 @@ import type { PageServerLoad } from './$types'; -import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop'; - -type OrderStatus = - | { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' } - | { state: 'paid'; order: Record; lines: Record[] }; +import { getStripe } from '$lib/stripe.server'; +import { getAdminPb } from '$lib/server/pb-admin'; +import { BASKET_COOKIE } from '$lib/server/basket'; +import type { OrderRecord } from '$lib/types'; export const load: PageServerLoad = async ({ url, cookies }) => { const intentId = url.searchParams.get('payment_intent'); if (!intentId) return { state: 'missing' as const }; - // PocketBase checks the intent with Stripe and looks up the order (the - // webhook is the source of truth and may not have landed yet). - const status = await shopFetch(`/order?payment_intent=${encodeURIComponent(intentId)}`); - if (status.state !== 'paid') return { state: status.state }; + let intent; + try { + intent = await getStripe().paymentIntents.retrieve(intentId); + } catch { + return { state: 'invalid' as const }; + } + + const pb = await getAdminPb(); + + // Webhook may not have landed yet — the webhook is the source of truth. + const order = await pb + .collection('orders') + .getFirstListItem(`stripePaymentIntentId = "${intentId}"`) + .catch(() => null); + + if (!order) { + // Payment succeeded but webhook is still in flight. + if (intent.status === 'succeeded') return { state: 'processing' as const }; + return { state: intent.status === 'canceled' ? ('canceled' as const) : ('failed' as const) }; + } + + // Sort by id, not 'created' — the order_lines collection was imported without + // autodate fields. PocketBase ids are time-sortable ULIDs, so this preserves + // chronological order without requiring a schema migration. + const orderLines = await pb + .collection('order_lines') + .getFullList({ filter: `order = "${order.id}"`, sort: 'id' }); cookies.delete(BASKET_COOKIE, { path: '/' }); - return { state: 'paid' as const, order: mapOrder(status.order, status.lines) }; + + const result: OrderRecord = { + id: order.id, + basket: order.basket, + email: order.email, + customerDetails: order.customerDetails, + total: order.total, + status: order.status, + stripePaymentIntentId: order.stripePaymentIntentId, + createdAt: order.created, + lines: orderLines.map((l) => ({ + id: l.id, + order: l.order, + item: l.item, + slot: l.slot || null, + quantity: l.quantity, + lineType: l.lineType, + name: l.name, + price: l.price, + start: l.start || null + })) + }; + + return { state: 'paid' as const, order: result }; }; diff --git a/app-public/src/routes/checkout/return/+page.svelte b/app-public/src/routes/checkout/return/+page.svelte index 15f9406..b09b23d 100644 --- a/app-public/src/routes/checkout/return/+page.svelte +++ b/app-public/src/routes/checkout/return/+page.svelte @@ -25,7 +25,7 @@
{#if data.state === 'paid' && data.order} -
✓
+
✓

Thank you, {data.order.customerDetails?.name || 'friend'}!

Your booking is confirmed. A receipt was sent to {data.order.email}. @@ -51,7 +51,7 @@ - Book another + Book another {:else if data.state === 'processing'}

Processing your payment…

@@ -63,10 +63,10 @@ {:else if data.state === 'canceled' || data.state === 'failed'}

Payment not completed

Your payment didn't go through — no money was captured. Please try again.

- Back to the shop + Back to the shop {:else}

Nothing to see here

This link is missing a payment reference.

- Back to the shop + Back to the shop {/if}
diff --git a/docker-compose.yml b/docker-compose.yml index a7b0682..416bbc3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,104 +1,95 @@ -services: - pocketbase: - # Pinned: schema (pb_schema.json) and migrations target this version's - # format/JS API. Upgrade deliberately — read the PocketBase changelog, - # back up pb_data, then bump the tag and test migrations locally. - image: docker.io/spectado/pocketbase:0.23.12 - container_name: massage-pocketbase - restart: unless-stopped - # Internal only — accessed via the caddy reverse proxy - expose: - - "80" - volumes: - - pocketbase:/pb_data - # Versioned schema changes; PocketBase applies pending ones on start. - - ./pocketbase/pb_migrations:/pb_migrations:ro,Z - # Shop API (baskets, slot holds, Stripe payments, orders) — the only - # place commerce data is written. See pocketbase/pb_hooks/shop/lib.js. - - ./pocketbase/pb_hooks:/pb_hooks:ro,Z - environment: - STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} - STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} - STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - # Shared with app-public: lets it record booking-email status on orders. - INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-} - - app-admin: - build: - context: . - dockerfile: app-admin/Dockerfile - container_name: massage-app-admin - restart: unless-stopped - depends_on: - - pocketbase - environment: - PORT: 3001 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 - PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 - ORIGIN: http://admin.${DOMAIN:-localhost}:8080 - PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 - BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 - STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends - SMTP_HOST: ${SMTP_HOST:-} - SMTP_PORT: ${SMTP_PORT:-587} - SMTP_USER: ${SMTP_USER:-} - SMTP_PASS: ${SMTP_PASS:-} - EMAIL_FROM: ${EMAIL_FROM:-} - EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} - SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} - # Internal only — served via the caddy reverse proxy - expose: - - "3001" - - app-public: - build: - context: . - dockerfile: app-public/Dockerfile - container_name: massage-app-public - restart: unless-stopped - depends_on: - - pocketbase - environment: - PORT: 3000 - POCKETBASE_INTERNAL_URL: http://pocketbase:80 - PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 - ORIGIN: http://www.${DOMAIN:-localhost}:8080 - # No PocketBase or Stripe secrets here: shop writes happen in PocketBase - # (pb_hooks/shop). The publishable key is public by design. - PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} - STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} - INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-} - # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook - SMTP_HOST: ${SMTP_HOST:-} - SMTP_PORT: ${SMTP_PORT:-587} - SMTP_USER: ${SMTP_USER:-} - SMTP_PASS: ${SMTP_PASS:-} - EMAIL_FROM: ${EMAIL_FROM:-} - EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} - SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} - # Internal only — served via the caddy reverse proxy - expose: - - "3000" - - caddy: - image: docker.io/library/caddy:2-alpine - container_name: massage-caddy - restart: unless-stopped - ports: - - "8080:8080" - environment: - DOMAIN: ${DOMAIN:-localhost} - # Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 - # (matches the ORIGIN vars below). Switch to "https" only if you also - # update ORIGIN/PUBLIC_* URLs and provide a cert issuer. - CADDY_SCHEME: ${CADDY_SCHEME:-http} - volumes: - - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z - depends_on: - - app-admin - - app-public - - pocketbase - -volumes: - pocketbase: +services: + pocketbase: + image: spectado/pocketbase:latest + container_name: massage-pocketbase + restart: unless-stopped + # Internal only — accessed via the caddy reverse proxy + expose: + - "80" + volumes: + - pocketbase:/pb_data + + app-admin: + build: + context: . + dockerfile: app-admin/Dockerfile + container_name: massage-app-admin + restart: unless-stopped + depends_on: + - pocketbase + environment: + PORT: 3001 + POCKETBASE_INTERNAL_URL: http://pocketbase:80 + PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 + ORIGIN: http://admin.${DOMAIN:-localhost}:8080 + PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 + BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 + # Commerce (reservation & payment system) — set these in a root-level .env + POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} + POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} + STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} + # Internal only — served via the caddy reverse proxy + expose: + - "3001" + + app-public: + build: + context: . + dockerfile: app-public/Dockerfile + container_name: massage-app-public + restart: unless-stopped + depends_on: + - pocketbase + environment: + PORT: 3000 + POCKETBASE_INTERNAL_URL: http://pocketbase:80 + PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 + ORIGIN: http://www.${DOMAIN:-localhost}:8080 + # Commerce (reservation & payment system) — set these in a root-level .env + POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} + POCKETBASE_ADMIN_PASSWORD: ${POCKETBASE_ADMIN_PASSWORD:-} + STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} + STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} + PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-} + STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} + # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook + SMTP_HOST: ${SMTP_HOST:-} + SMTP_PORT: ${SMTP_PORT:-587} + SMTP_USER: ${SMTP_USER:-} + SMTP_PASS: ${SMTP_PASS:-} + EMAIL_FROM: ${EMAIL_FROM:-} + EMAIL_FROM_NAME: ${EMAIL_FROM_NAME:-} + SITE_TIMEZONE: ${SITE_TIMEZONE:-Europe/Oslo} + # Internal only — served via the caddy reverse proxy + expose: + - "3000" + + caddy: + image: caddy:2-alpine + container_name: massage-caddy + restart: unless-stopped + ports: + - "8080:8080" + environment: + DOMAIN: ${DOMAIN:-localhost} + # Scheme used in Caddyfile site addresses. "http" = plain HTTP on :8080 + # (matches the ORIGIN vars below). Switch to "https" only if you also + # update ORIGIN/PUBLIC_* URLs and provide a cert issuer. + CADDY_SCHEME: ${CADDY_SCHEME:-http} + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z + depends_on: + - app-admin + - app-public + - pocketbase + +volumes: + pocketbase: diff --git a/packages/shared/src/blocks/CheckoutBlock.svelte b/packages/shared/src/blocks/CheckoutBlock.svelte index bd12b04..5a9b4cb 100644 --- a/packages/shared/src/blocks/CheckoutBlock.svelte +++ b/packages/shared/src/blocks/CheckoutBlock.svelte @@ -347,7 +347,7 @@ {#if payState === 'idle' || payState === 'creating'}