Compare commits
3 commits
bcb6cf80c7
...
9fab662bee
| Author | SHA1 | Date | |
|---|---|---|---|
| 9fab662bee | |||
| 773fecc090 | |||
| 1f929c68ca |
24 changed files with 964 additions and 779 deletions
10
.env.example
10
.env.example
|
|
@ -1,15 +1,17 @@
|
|||
# Secrets read by docker-compose.yml via ${VAR:-} substitution.
|
||||
# Copy to .env at the project root and fill in.
|
||||
|
||||
# Stripe
|
||||
# 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_SECRET_KEY=sk_test_...
|
||||
PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
|
||||
STRIPE_WEBHOOK_SECRET=whsec_...
|
||||
STRIPE_CURRENCY=eur
|
||||
|
||||
# PocketBase superuser credentials (used by server-side basket/checkout/webhook APIs)
|
||||
POCKETBASE_ADMIN_EMAIL=admin@example.com
|
||||
POCKETBASE_ADMIN_PASSWORD=changeme
|
||||
# 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=
|
||||
|
||||
# Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP).
|
||||
# Leave SMTP_HOST empty in development: emails are then written to the
|
||||
|
|
|
|||
13
AGENTS.md
13
AGENTS.md
|
|
@ -54,7 +54,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
|
|||
│ │ ├── scrollReveal.ts # Re-exports from $shared
|
||||
│ │ ├── stripe-client.ts # Re-exports from $shared
|
||||
│ │ ├── basket.svelte.ts # Re-exports from $shared
|
||||
│ │ └── server/ # Re-exports from $shared/server (pb-admin, basket); stripe.server.ts is public-only
|
||||
│ │ └── server/ # shop.ts (client for PocketBase's /api/shop routes, basket cookie) + $shared/server re-exports
|
||||
│ ├── routes/
|
||||
│ │ ├── +layout.svelte # Root layout (always renders Header/Footer)
|
||||
│ │ ├── +page.svelte # Home page (slug=home)
|
||||
|
|
@ -69,6 +69,7 @@ app-public/ # SvelteKit public app (serves *.<domain>)
|
|||
├── 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
|
||||
docker-compose.yml # app-admin + app-public + pocketbase + caddy services
|
||||
Caddyfile # Subdomain-based routing
|
||||
```
|
||||
|
|
@ -127,7 +128,8 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
|
|||
- 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, baskets, basket_lines) are superuser-only; the public app does them server-side via `getAdminPb()`.
|
||||
- **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).
|
||||
|
|
@ -159,7 +161,7 @@ DOMAIN=localhost docker compose up --build
|
|||
|
||||
# Type checking (needs node_modules in packages/shared too, or every shared
|
||||
# file that imports a package fails with "Cannot find module")
|
||||
cd packages/shared && npm ci
|
||||
cd packages/shared && npm install # no lockfile here, so not `npm ci`
|
||||
cd app-admin && npm run check
|
||||
cd app-public && npm run check
|
||||
|
||||
|
|
@ -177,5 +179,6 @@ cd app-public && npm run build
|
|||
- `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`.
|
||||
- `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are required for **any** commerce data: without them the public app logs `Commerce data unavailable` and Shop blocks show "Nothing is available". Shop data is loaded by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`).
|
||||
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
|
||||
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
|
||||
- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`); if a Shop block has nothing to show it says "Nothing is available".
|
||||
|
|
|
|||
10
README.md
10
README.md
|
|
@ -79,7 +79,7 @@ If the `globals` records do not exist, the app falls back to safe defaults and t
|
|||
|
||||
### Migrations
|
||||
|
||||
`pocketbase/pb_migrations/` is mounted into the PocketBase container, which applies any new migration once when it starts (`docker compose up` / restart). The first one (`1791244800_lock_rules_dates_unique.js`) closes public sign-up on the `users` collection, makes order/basket writes superuser-only, adds `created`/`updated` dates and unique slug/key indexes. On an existing install, check the PocketBase log after restarting — if duplicate page slugs or global keys exist, the unique index is skipped with a log line.
|
||||
`pocketbase/pb_migrations/` is mounted into the PocketBase container, which applies any new migration once when it starts (`docker compose up` / restart). The first one (`1791244800_lock_rules_dates_unique.js`) closes public sign-up on the `users` collection, makes order/basket writes superuser-only, adds `created`/`updated` dates and unique slug/key indexes. On an existing install, check the PocketBase log after restarting — if duplicate page slugs or global keys exist, the unique index is skipped with a log line. `1791331200_lock_order_lines.js` makes `order_lines` writes superuser-only (they were public).
|
||||
|
||||
> **Security:** every CMS collection allows writes to *any* signed-in user, so the `users` collection must not allow public sign-up. The migration enforces this; if you manage PocketBase by hand, keep `users` → API rules → Create set to superuser-only.
|
||||
|
||||
|
|
@ -136,10 +136,12 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
|
|||
|
||||
The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client).
|
||||
|
||||
**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that releases expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
|
||||
|
||||
Setup:
|
||||
|
||||
1. Add the Stripe + PocketBase-admin vars from `.env.example` to `.env` at the project root.
|
||||
2. `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` are the credentials of the PocketBase superuser you created — the basket/checkout/webhook APIs use a server-side admin client so collection rules can stay admin-only.
|
||||
1. Add the Stripe vars and `INTERNAL_API_SECRET` (e.g. `openssl rand -hex 32`) from `.env.example` to `.env` at the project root. docker-compose gives the Stripe secret key and webhook secret to **PocketBase only**.
|
||||
2. Hook changes apply on PocketBase restart (the directory is mounted read-only at `/pb_hooks`).
|
||||
3. For local webhook testing, forward Stripe events with the CLI:
|
||||
```sh
|
||||
stripe listen --forward-to www.localhost:8080/api/webhooks/stripe
|
||||
|
|
@ -150,7 +152,7 @@ Setup:
|
|||
|
||||
## Booking emails (Brevo)
|
||||
|
||||
After the Stripe webhook creates an order it sends two emails through an SMTP relay (Brevo) with `nodemailer`:
|
||||
After the Stripe webhook creates an order (in PocketBase, which hands the order data back to the public app's webhook route) the public app 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.
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
export * from '$shared/server/pb-admin';
|
||||
18
app-public/package-lock.json
generated
18
app-public/package-lock.json
generated
|
|
@ -14,7 +14,6 @@
|
|||
"daisyui": "^5.5.19",
|
||||
"nodemailer": "^10.0.12",
|
||||
"pocketbase": "^0.26.9",
|
||||
"stripe": "^22.3.2",
|
||||
"tailwindcss": "^4.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -1987,23 +1986,6 @@
|
|||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/stripe": {
|
||||
"version": "22.5.0",
|
||||
"resolved": "https://registry.npmjs.org/stripe/-/stripe-22.5.0.tgz",
|
||||
"integrity": "sha512-QVwMwriC0bbySx6R4dpsvJ0W//GojC1kwWVS6rPSoVqDUIZX4Hy3TaUrd2AZeXEAaKbfWIjQjvo3vKAReHZ0vQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/node": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/supports-preserve-symlinks-flag": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@
|
|||
"daisyui": "^5.5.19",
|
||||
"nodemailer": "^10.0.12",
|
||||
"pocketbase": "^0.26.9",
|
||||
"stripe": "^22.3.2",
|
||||
"tailwindcss": "^4.3.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
export * from '$shared/server/basket';
|
||||
|
|
@ -1 +0,0 @@
|
|||
export * from '$shared/server/pb-admin';
|
||||
138
app-public/src/lib/server/shop.ts
Normal file
138
app-public/src/lib/server/shop.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
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<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
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<E extends Parameters<RequestHandler>[0]>(handler: (event: E) => Promise<Response>) {
|
||||
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<T>(path: string, data: unknown): Promise<T> {
|
||||
return shopFetch<T>(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | 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<Basket | null> {
|
||||
// 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<string, any>, lines: Record<string, any>[]): 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));
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
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';
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
|
||||
import type { ItemRecord, SlotRecord } from '$lib/types';
|
||||
import { getAdminPb } from '$lib/server/pb-admin';
|
||||
import { BASKET_COOKIE, loadBasket, sweepExpiredHolds } from '$lib/server/basket';
|
||||
import { BASKET_COOKIE, getBasket } from '$lib/server/shop';
|
||||
import { loadShopData } from '$shared/server/shop';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
|
|
@ -23,24 +22,18 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => {
|
|||
|
||||
if (!header.homePage) header.homePage = defaultHeader.homePage;
|
||||
|
||||
// Commerce data for the public site.
|
||||
let basket = null;
|
||||
let items: ItemRecord[] = [];
|
||||
let slots: SlotRecord[] = [];
|
||||
|
||||
try {
|
||||
const pb = await getAdminPb();
|
||||
await sweepExpiredHolds(pb);
|
||||
|
||||
const basketId = cookies.get(BASKET_COOKIE);
|
||||
if (basketId) basket = await loadBasket(pb, basketId);
|
||||
|
||||
({ items, slots } = await loadShopData(pb));
|
||||
} catch (e) {
|
||||
// Admin PB not configured (e.g. fresh dev env) — commerce features off;
|
||||
// Shop blocks then show their "nothing available" message.
|
||||
console.warn('Commerce data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e);
|
||||
}
|
||||
// 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 ?? [];
|
||||
|
||||
return { header, footer, colors, user: locals.user, basket, items, slots };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,54 +1,15 @@
|
|||
import { json, error, type Cookies } from '@sveltejs/kit';
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getAdminPb } from '$lib/server/pb-admin';
|
||||
import {
|
||||
BASKET_COOKIE,
|
||||
BASKET_TTL_MS,
|
||||
SLOT_HOLD_MS,
|
||||
sweepExpiredHolds,
|
||||
loadBasket,
|
||||
createBasket,
|
||||
touchBasket,
|
||||
releaseLineHold
|
||||
} from '$lib/server/basket';
|
||||
import type PocketBase from 'pocketbase';
|
||||
import { BASKET_COOKIE, BASKET_COOKIE_MAX_AGE, getBasket, jsonErrors, mapBasket, postJson } from '$lib/server/shop';
|
||||
|
||||
function setBasketCookie(cookies: Cookies, basketId: string) {
|
||||
cookies.set(BASKET_COOKIE, basketId, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
maxAge: BASKET_TTL_MS / 1000
|
||||
});
|
||||
}
|
||||
// Basket API for the browser. The logic (stock, slot holds, expiry) is in
|
||||
// PocketBase — pocketbase/pb_hooks/shop; this route only adds the 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 GET: RequestHandler = jsonErrors(async ({ cookies }) => {
|
||||
return json({ basket: await getBasket(cookies.get(BASKET_COOKIE)) });
|
||||
});
|
||||
|
||||
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await request.json();
|
||||
|
|
@ -56,112 +17,17 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
|||
throw error(400, 'Invalid JSON body');
|
||||
}
|
||||
|
||||
const action = String(body.action || '');
|
||||
|
||||
// All mutations need a basket — lazily created on first add.
|
||||
const { basket } = await resolveBasket(pb, cookies, action === 'add_item' || action === 'add_slot');
|
||||
if (!basket) throw error(400, 'No active basket — add an item first');
|
||||
|
||||
switch (action) {
|
||||
case 'add_item': {
|
||||
const itemId = String(body.itemId || '');
|
||||
const quantity = Math.max(1, Number(body.quantity) || 1);
|
||||
if (!itemId) throw error(400, 'itemId is required');
|
||||
|
||||
const item = await pb.collection('items').getOne(itemId).catch(() => null);
|
||||
if (!item || !item.active) throw error(404, 'Item not found');
|
||||
if (item.type !== 'item') throw error(400, 'Use add_slot for bookable services');
|
||||
|
||||
const existing = basket.lines.find((l) => l.lineType === 'item' && l.item === itemId);
|
||||
const newQty = (existing?.quantity ?? 0) + quantity;
|
||||
if (item.stock != null && newQty > item.stock) {
|
||||
throw error(409, `Only ${item.stock} in stock`);
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await pb.collection('basket_lines').update(existing.id, { quantity: newQty });
|
||||
} else {
|
||||
await pb.collection('basket_lines').create({
|
||||
basket: basket.id,
|
||||
item: itemId,
|
||||
quantity,
|
||||
lineType: 'item'
|
||||
const { basket } = await postJson<{ basket: Parameters<typeof mapBasket>[0] }>('/basket', {
|
||||
action: body.action,
|
||||
itemId: body.itemId,
|
||||
slotId: body.slotId,
|
||||
lineId: body.lineId,
|
||||
quantity: body.quantity,
|
||||
basketId: cookies.get(BASKET_COOKIE) || ''
|
||||
});
|
||||
}
|
||||
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 });
|
||||
};
|
||||
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 });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,26 +1,10 @@
|
|||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getAdminPb } from '$lib/server/pb-admin';
|
||||
import { BASKET_COOKIE, SLOT_CHECKOUT_HOLD_MS, sweepExpiredHolds, loadBasket, extendBasketHolds } from '$lib/server/basket';
|
||||
import { getStripe, getCurrency } from '$lib/stripe.server';
|
||||
import type { CustomerDetails } from '$lib/types';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
const pb = await getAdminPb();
|
||||
|
||||
const basketId = cookies.get(BASKET_COOKIE);
|
||||
// Payment is starting — extend any held slots to the checkout hold (30 min)
|
||||
// so a booked service survives the customer entering card details or
|
||||
// retrying a declined card. Extend BEFORE sweeping so a slot whose hold
|
||||
// just lapsed is rescued rather than released at the moment they try to pay.
|
||||
if (basketId) await extendBasketHolds(pb, basketId, SLOT_CHECKOUT_HOLD_MS);
|
||||
await sweepExpiredHolds(pb);
|
||||
|
||||
if (!basketId) throw error(400, 'No active basket');
|
||||
const basket = await loadBasket(pb, basketId);
|
||||
if (!basket) throw error(400, 'Your session has expired — please re-select your items');
|
||||
if (!basket.lines.length) throw error(400, 'Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
|
||||
import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
|
||||
|
||||
// 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<string, unknown>;
|
||||
try {
|
||||
body = await request.json();
|
||||
|
|
@ -28,75 +12,12 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
|||
throw error(400, 'Invalid JSON body');
|
||||
}
|
||||
|
||||
const customer: CustomerDetails = {
|
||||
name: String(body.name || '').trim(),
|
||||
email: String(body.email || '').trim(),
|
||||
phone: String(body.phone || '').trim(),
|
||||
notes: String(body.notes || '').trim()
|
||||
};
|
||||
if (!customer.name) throw error(400, 'Name is required');
|
||||
if (!customer.email || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) {
|
||||
throw error(400, 'A valid email is required');
|
||||
}
|
||||
|
||||
// Re-validate every line server-side (source of truth for the total).
|
||||
let totalCents = 0;
|
||||
for (const line of basket.lines) {
|
||||
const item = await pb.collection('items').getOne(line.item).catch(() => null);
|
||||
if (!item || !item.active) throw error(409, `"${line.itemName ?? 'An item'}" is no longer available`);
|
||||
|
||||
if (line.lineType === 'slot') {
|
||||
const slot = await pb.collection('slots').getOne(line.slot!).catch(() => null);
|
||||
if (!slot || slot.status !== 'held') {
|
||||
throw error(409, `Your time slot for "${item.name}" has expired — please pick it again`);
|
||||
}
|
||||
} else {
|
||||
if (item.stock != null && item.stock < line.quantity) {
|
||||
throw error(409, `Only ${item.stock} of "${item.name}" left in stock`);
|
||||
}
|
||||
}
|
||||
totalCents += Math.round(item.price * 100) * line.quantity;
|
||||
}
|
||||
|
||||
if (totalCents <= 0) throw error(400, 'Basket total must be positive');
|
||||
|
||||
let paymentIntent;
|
||||
if (basket.stripePaymentIntentId) {
|
||||
// Reuse an existing intent when possible (page reload / retry).
|
||||
try {
|
||||
const existing = await getStripe().paymentIntents.retrieve(basket.stripePaymentIntentId);
|
||||
if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') {
|
||||
paymentIntent = await getStripe().paymentIntents.update(existing.id, {
|
||||
amount: totalCents,
|
||||
metadata: { basket_id: basket.id }
|
||||
const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
|
||||
basketId: cookies.get(BASKET_COOKIE) || '',
|
||||
name: body.name,
|
||||
email: body.email,
|
||||
phone: body.phone,
|
||||
notes: body.notes
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Intent missing/invalid — fall through and create a new one
|
||||
}
|
||||
}
|
||||
|
||||
if (!paymentIntent) {
|
||||
paymentIntent = await getStripe().paymentIntents.create({
|
||||
amount: totalCents,
|
||||
currency: getCurrency(),
|
||||
automatic_payment_methods: { enabled: true },
|
||||
receipt_email: customer.email,
|
||||
metadata: {
|
||||
basket_id: basket.id,
|
||||
line_summary: basket.lines
|
||||
.map((l) => `${l.quantity}× ${l.itemName ?? l.item}`)
|
||||
.join('; ')
|
||||
.slice(0, 450)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
await pb.collection('baskets').update(basket.id, {
|
||||
stripePaymentIntentId: paymentIntent.id,
|
||||
email: customer.email,
|
||||
customerDetails: customer
|
||||
});
|
||||
|
||||
return json({ clientSecret: paymentIntent.client_secret });
|
||||
};
|
||||
return json({ clientSecret });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,128 +1,25 @@
|
|||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getStripe } from '$lib/stripe.server';
|
||||
import { getAdminPb } from '$lib/server/pb-admin';
|
||||
import { getFileUrl } from '$lib/pb';
|
||||
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
|
||||
import { sendOrderEmails } from '$lib/server/email';
|
||||
import type PocketBase from 'pocketbase';
|
||||
import { jsonErrors, sendAndRecordOrderEmails, shopFetch } from '$lib/server/shop';
|
||||
import type { OrderEmailData } from '$lib/server/email';
|
||||
|
||||
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();
|
||||
// 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 }) => {
|
||||
const signature = request.headers.get('stripe-signature');
|
||||
if (!signature) throw error(400, 'Missing Stripe-Signature header');
|
||||
|
||||
let event;
|
||||
try {
|
||||
event = getStripe().webhooks.constructEvent(body, signature, secret);
|
||||
} catch (e) {
|
||||
throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`);
|
||||
}
|
||||
// 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()
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
// 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);
|
||||
|
||||
return json({ received: true });
|
||||
};
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,64 +1,19 @@
|
|||
import type { PageServerLoad } from './$types';
|
||||
import { getStripe } from '$lib/stripe.server';
|
||||
import { getAdminPb } from '$lib/server/pb-admin';
|
||||
import { BASKET_COOKIE } from '$lib/server/basket';
|
||||
import type { OrderRecord } from '$lib/types';
|
||||
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
|
||||
|
||||
type OrderStatus =
|
||||
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
|
||||
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
|
||||
|
||||
export const load: PageServerLoad = async ({ url, cookies }) => {
|
||||
const intentId = url.searchParams.get('payment_intent');
|
||||
if (!intentId) return { state: 'missing' as const };
|
||||
|
||||
let intent;
|
||||
try {
|
||||
intent = await getStripe().paymentIntents.retrieve(intentId);
|
||||
} catch {
|
||||
return { state: 'invalid' as const };
|
||||
}
|
||||
|
||||
const pb = await getAdminPb();
|
||||
|
||||
// Webhook may not have landed yet — the webhook is the source of truth.
|
||||
const order = await pb
|
||||
.collection('orders')
|
||||
.getFirstListItem(`stripePaymentIntentId = "${intentId}"`)
|
||||
.catch(() => null);
|
||||
|
||||
if (!order) {
|
||||
// Payment succeeded but webhook is still in flight.
|
||||
if (intent.status === 'succeeded') return { state: 'processing' as const };
|
||||
return { state: intent.status === 'canceled' ? ('canceled' as const) : ('failed' as const) };
|
||||
}
|
||||
|
||||
// Sort by id, not 'created' — the order_lines collection was imported without
|
||||
// autodate fields. PocketBase ids are time-sortable ULIDs, so this preserves
|
||||
// chronological order without requiring a schema migration.
|
||||
const orderLines = await pb
|
||||
.collection('order_lines')
|
||||
.getFullList({ filter: `order = "${order.id}"`, sort: 'id' });
|
||||
// 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<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`);
|
||||
if (status.state !== 'paid') return { state: status.state };
|
||||
|
||||
cookies.delete(BASKET_COOKIE, { path: '/' });
|
||||
|
||||
const result: OrderRecord = {
|
||||
id: order.id,
|
||||
basket: order.basket,
|
||||
email: order.email,
|
||||
customerDetails: order.customerDetails,
|
||||
total: order.total,
|
||||
status: order.status,
|
||||
stripePaymentIntentId: order.stripePaymentIntentId,
|
||||
createdAt: order.created,
|
||||
lines: orderLines.map((l) => ({
|
||||
id: l.id,
|
||||
order: l.order,
|
||||
item: l.item,
|
||||
slot: l.slot || null,
|
||||
quantity: l.quantity,
|
||||
lineType: l.lineType,
|
||||
name: l.name,
|
||||
price: l.price,
|
||||
start: l.start || null
|
||||
}))
|
||||
};
|
||||
|
||||
return { state: 'paid' as const, order: result };
|
||||
return { state: 'paid' as const, order: mapOrder(status.order, status.lines) };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,6 +13,15 @@ services:
|
|||
- 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:
|
||||
|
|
@ -29,9 +38,6 @@ services:
|
|||
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:-}
|
||||
|
|
@ -58,13 +64,11 @@ services:
|
|||
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:-}
|
||||
# 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}
|
||||
|
|
|
|||
|
|
@ -1,187 +0,0 @@
|
|||
import type PocketBase from 'pocketbase';
|
||||
import type { Basket, BasketLine } from '../types';
|
||||
import { getFileUrl } from '../pb';
|
||||
|
||||
export const BASKET_COOKIE = 'basket_id';
|
||||
/** Basket lifetime — refreshed on every basket API call. */
|
||||
export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
/** How long a slot stays held once added to a basket / after a failed payment. */
|
||||
export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min
|
||||
/** Hold extended to this once a payment is in progress, so the slot survives
|
||||
* the customer entering card details / retrying a declined card. */
|
||||
export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min
|
||||
|
||||
function now() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
function iso(date: Date) {
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release any slots whose hold has expired, removing their basket lines
|
||||
* and flipping them back to `available`. Also marks expired active
|
||||
* baskets as `abandoned`. Runs lazily on basket reads / checkout.
|
||||
*
|
||||
* The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather
|
||||
* than via a PocketBase date-string filter, so a slot is never released
|
||||
* *before* its hold genuinely lapses — regardless of how PocketBase stores /
|
||||
* compares the date field. A slot is held for the full SLOT_HOLD_MS (or
|
||||
* SLOT_CHECKOUT_HOLD_MS during payment).
|
||||
*/
|
||||
export async function sweepExpiredHolds(pb: PocketBase) {
|
||||
const nowMs = Date.now();
|
||||
|
||||
// 1. Release expired slot holds (and drop the lines holding them)
|
||||
const heldSlots = await pb
|
||||
.collection('slots')
|
||||
.getFullList({ filter: `status = 'held'` })
|
||||
.catch(() => []);
|
||||
for (const slot of heldSlots) {
|
||||
const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN;
|
||||
// Still valid, or no parseable hold to judge by — leave it alone.
|
||||
if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue;
|
||||
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `slot = "${slot.id}"` })
|
||||
.catch(() => []);
|
||||
for (const line of lines) {
|
||||
await pb.collection('basket_lines').delete(line.id).catch(() => {});
|
||||
}
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(slot.id, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// 2. Abandon expired active baskets (their slot holds were already
|
||||
// covered by heldUntil above — same 10-min window < 24h basket TTL)
|
||||
const nowIso = iso(now());
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` })
|
||||
.then(async (expired) => {
|
||||
for (const basket of expired) {
|
||||
await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Map raw PB records (with expand) to our Basket type. */
|
||||
function mapBasket(record: Record<string, any>, lines: Record<string, any>[]): Basket {
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/** Load a basket + its lines (with item/slot expand) by basket id. */
|
||||
export async function loadBasket(pb: PocketBase, basketId: string): Promise<Basket | null> {
|
||||
try {
|
||||
const record = await pb.collection('baskets').getOne(basketId);
|
||||
if (record.status !== 'active') return null;
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' });
|
||||
return mapBasket(record, lines);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a fresh active basket. */
|
||||
export async function createBasket(pb: PocketBase): Promise<Basket> {
|
||||
const record = await pb.collection('baskets').create({
|
||||
status: 'active',
|
||||
expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS))
|
||||
});
|
||||
return {
|
||||
id: record.id,
|
||||
status: 'active',
|
||||
expiresAt: record.expiresAt,
|
||||
email: null,
|
||||
customerDetails: null,
|
||||
stripePaymentIntentId: null,
|
||||
lines: []
|
||||
};
|
||||
}
|
||||
|
||||
/** Touch the basket expiry (rolling TTL). */
|
||||
export async function touchBasket(pb: PocketBase, basketId: string) {
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Release a slot hold for a basket line (slot back to available). */
|
||||
export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) {
|
||||
if (!line.slot) return;
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(line.slot, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-reserve (extend) the hold on every slot line in a basket, as long as
|
||||
* the slot is still in `held` status. Used:
|
||||
* - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a
|
||||
* service survives the customer entering card details / retrying a
|
||||
* declined card;
|
||||
* - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer
|
||||
* can retry within a fresh 10-minute window.
|
||||
* The slot is genuinely still the customer's (nobody else could grab it
|
||||
* while `held`), so renewing is safe. Slots whose status is no longer
|
||||
* `held` (e.g. released and re-booked by someone else) are returned so the
|
||||
* caller can inform the user.
|
||||
*/
|
||||
export async function extendBasketHolds(
|
||||
pb: PocketBase,
|
||||
basketId: string,
|
||||
durationMs = SLOT_HOLD_MS
|
||||
): Promise<string[]> {
|
||||
const unheld: string[] = [];
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` })
|
||||
.catch(() => []);
|
||||
const until = iso(new Date(Date.now() + durationMs));
|
||||
for (const line of lines) {
|
||||
const slotId = line.slot;
|
||||
if (!slotId) continue;
|
||||
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
|
||||
if (slot && slot.status === 'held') {
|
||||
await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {});
|
||||
} else {
|
||||
unheld.push(line.id);
|
||||
}
|
||||
}
|
||||
return unheld;
|
||||
}
|
||||
|
|
@ -62,13 +62,14 @@ export function emailSiteUrl(): string {
|
|||
}
|
||||
|
||||
export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> {
|
||||
const [business, colors] = await Promise.all([
|
||||
getGlobalData(pb, 'footer', defaultFooter),
|
||||
getGlobalData(pb, 'colors', defaultColors)
|
||||
]);
|
||||
const [footer, colors] = await Promise.all([getGlobalData(pb, 'footer', {}), getGlobalData(pb, 'colors', {})]);
|
||||
return emailSettingsFrom(footer, colors);
|
||||
}
|
||||
|
||||
function emailSettingsFrom(footer: Partial<FooterGlobal> | null, colors: Partial<ColorsGlobal> | null): EmailSettings {
|
||||
return {
|
||||
business,
|
||||
colors,
|
||||
business: { ...defaultFooter, ...(footer || {}) },
|
||||
colors: { ...defaultColors, ...(colors || {}) },
|
||||
siteUrl: emailSiteUrl(),
|
||||
timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
|
||||
currency: env.STRIPE_CURRENCY || 'eur'
|
||||
|
|
@ -104,11 +105,47 @@ function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSetting
|
|||
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' });
|
||||
/**
|
||||
* Everything the booking emails for one order need, as raw PocketBase
|
||||
* records (REST JSON shape). Built by `loadOrderEmailData` (admin resend) or
|
||||
* by the PocketBase shop hooks (`orderEmailData` in pb_hooks/shop/lib.js,
|
||||
* after a payment) — keep the two in sync.
|
||||
*/
|
||||
export type OrderEmailData = {
|
||||
order: Record<string, any>;
|
||||
/** order_lines with `expand.slot` and `expand.item` */
|
||||
lines: Record<string, any>[];
|
||||
templates: Partial<Record<EmailTemplateKey, Record<string, any> | null>>;
|
||||
footer: Partial<FooterGlobal> | null;
|
||||
colors: Partial<ColorsGlobal> | null;
|
||||
};
|
||||
|
||||
export async function loadOrderEmailData(pb: PocketBase, orderId: string): Promise<OrderEmailData> {
|
||||
const globalData = (key: string) =>
|
||||
pb
|
||||
.collection('globals')
|
||||
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
||||
.then((record) => record.data || null)
|
||||
.catch(() => null);
|
||||
const template = (key: string) =>
|
||||
pb
|
||||
.collection('email_templates')
|
||||
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
||||
.catch(() => null);
|
||||
const [order, lines, customer_confirmation, client_alert, footer, colors] = await Promise.all([
|
||||
pb.collection('orders').getOne(orderId),
|
||||
pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' }),
|
||||
template('customer_confirmation'),
|
||||
template('client_alert'),
|
||||
globalData('footer'),
|
||||
globalData('colors')
|
||||
]);
|
||||
return { order, lines, templates: { customer_confirmation, client_alert }, footer, colors };
|
||||
}
|
||||
|
||||
function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
||||
const order = data.order;
|
||||
const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || '')));
|
||||
|
||||
const lines: EmailLine[] = lineRecords.map((line) => {
|
||||
const start = line.start ? new Date(line.start).toISOString() : null;
|
||||
|
|
@ -143,32 +180,34 @@ async function loadOrderContext(pb: PocketBase, orderId: string, settings: Email
|
|||
lines,
|
||||
...settings
|
||||
};
|
||||
return { order, ctx, lineIds: lineRecords.map((line) => line.id) };
|
||||
return { 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);
|
||||
/** Email status fields to write on the order (customerEmailSentAt / clientEmailSentAt / emailError). */
|
||||
export type OrderEmailPatch = Record<string, string>;
|
||||
|
||||
const patch: Record<string, string> = {};
|
||||
const errorLines = String(order.emailError || '')
|
||||
/**
|
||||
* Render and send the booking emails for a paid order. Never throws — a
|
||||
* failed email must not fail the payment flow; the admin can resend from
|
||||
* /orders. Returns the outcomes and the status patch for the caller to save.
|
||||
*/
|
||||
export async function sendOrderEmailsFromData(
|
||||
data: OrderEmailData,
|
||||
kinds: EmailKind[] = ['customer', 'client']
|
||||
): Promise<{ outcomes: Partial<Record<EmailKind, EmailOutcome>>; patch: OrderEmailPatch }> {
|
||||
const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {};
|
||||
const patch: OrderEmailPatch = {};
|
||||
const orderId = String(data.order?.id || '');
|
||||
try {
|
||||
const settings = emailSettingsFrom(data.footer, data.colors);
|
||||
const { ctx, lineIds } = orderEmailContext(data, settings);
|
||||
|
||||
const errorLines = String(data.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]);
|
||||
const template = normalizeEmailTemplate(TEMPLATE_KEY[kind], data.templates[TEMPLATE_KEY[kind]] ?? null);
|
||||
if (!template.enabled) {
|
||||
outcomes[kind] = 'disabled';
|
||||
continue;
|
||||
|
|
@ -205,14 +244,31 @@ export async function sendOrderEmails(
|
|||
}
|
||||
|
||||
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, patch };
|
||||
}
|
||||
|
||||
/** Load, send and record the booking emails for an order (admin resend, with the signed-in admin's client). */
|
||||
export async function sendOrderEmails(
|
||||
pb: PocketBase,
|
||||
orderId: string,
|
||||
kinds: EmailKind[] = ['customer', 'client']
|
||||
): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
|
||||
let data: OrderEmailData;
|
||||
try {
|
||||
data = await loadOrderEmailData(pb, orderId);
|
||||
} catch (e) {
|
||||
console.error(`[email] could not load order ${orderId}:`, e);
|
||||
return Object.fromEntries(kinds.map((kind) => [kind, 'failed' as const]));
|
||||
}
|
||||
const { outcomes, patch } = await sendOrderEmailsFromData(data, kinds);
|
||||
await pb
|
||||
.collection('orders')
|
||||
.update(orderId, patch)
|
||||
.catch((e) => console.error(`[email] could not record email status on order ${orderId}:`, e));
|
||||
return outcomes;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,53 +0,0 @@
|
|||
import PocketBase, { ClientResponseError } from 'pocketbase';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
let adminPb: PocketBase | null = null;
|
||||
let authPromise: Promise<PocketBase> | null = null;
|
||||
|
||||
async function authenticate(): Promise<PocketBase> {
|
||||
const url = env.POCKETBASE_INTERNAL_URL;
|
||||
const pb = new PocketBase(url);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
const email = env.POCKETBASE_ADMIN_EMAIL;
|
||||
const password = env.POCKETBASE_ADMIN_PASSWORD;
|
||||
if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set');
|
||||
|
||||
await pb.collection('_superusers').authWithPassword(email, password);
|
||||
adminPb = pb;
|
||||
return pb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-only PocketBase client authenticated as admin.
|
||||
* Used by basket/checkout/webhook API routes that need to bypass
|
||||
* collection-level API rules (create baskets, hold slots, create orders).
|
||||
*
|
||||
* Concurrent callers share one in-flight auth attempt; if the cached token
|
||||
* has since been invalidated (401 on first use), we re-authenticate once.
|
||||
*/
|
||||
export async function getAdminPb(): Promise<PocketBase> {
|
||||
if (adminPb?.authStore.isValid) return adminPb;
|
||||
authPromise ??= authenticate().finally(() => {
|
||||
authPromise = null;
|
||||
});
|
||||
return authPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with the admin client; on a 401 (stale/invalidated token),
|
||||
* re-authenticate and retry exactly once.
|
||||
*/
|
||||
export async function withAdminPb<T>(fn: (pb: PocketBase) => Promise<T>): Promise<T> {
|
||||
const pb = await getAdminPb();
|
||||
try {
|
||||
return await fn(pb);
|
||||
} catch (e) {
|
||||
if (e instanceof ClientResponseError && e.status === 401) {
|
||||
pb.authStore.clear();
|
||||
adminPb = null;
|
||||
return fn(await getAdminPb());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,8 +7,8 @@ import type { ItemRecord, SlotRecord } from '../types';
|
|||
* blocks. Used by the public layout and the admin draft preview so both
|
||||
* render the same shop.
|
||||
*
|
||||
* `pb` must be able to read items, slots and media (admin client on the
|
||||
* public site, the logged-in superuser in the admin). Errors propagate.
|
||||
* Works with an anonymous client: the API rules expose active items,
|
||||
* available slots and media publicly. Errors propagate.
|
||||
*/
|
||||
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> {
|
||||
const [itemRecords, slotRecords] = await Promise.all([
|
||||
|
|
|
|||
|
|
@ -458,9 +458,9 @@
|
|||
"system": false,
|
||||
"listRule": "@request.auth.id != ''",
|
||||
"viewRule": "@request.auth.id != ''",
|
||||
"createRule": "",
|
||||
"updateRule": "",
|
||||
"deleteRule": "",
|
||||
"createRule": null,
|
||||
"updateRule": null,
|
||||
"deleteRule": null,
|
||||
"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 },
|
||||
|
|
|
|||
44
pocketbase/pb_hooks/shop.pb.js
Normal file
44
pocketbase/pb_hooks/shop.pb.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/// Shop API — see shop/lib.js. The public app proxies to these routes (it
|
||||
/// holds the basket cookie); they are also reachable directly, so every one
|
||||
/// treats its input as untrusted. The basket id acts as the customer's
|
||||
/// bearer token, exactly like the cookie it comes from.
|
||||
|
||||
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
shop.sweepExpiredHolds($app);
|
||||
return e.json(200, { basket: shop.basketPayload($app, shop.loadActiveBasket($app, e.request.pathValue('id'))) });
|
||||
});
|
||||
|
||||
routerAdd('POST', '/api/shop/basket', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
return e.json(200, { basket: shop.basketAction($app, e.requestInfo().body) });
|
||||
});
|
||||
|
||||
routerAdd('POST', '/api/shop/checkout', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
return e.json(200, shop.startCheckout($app, e.requestInfo().body));
|
||||
});
|
||||
|
||||
routerAdd('POST', '/api/shop/stripe-webhook', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
// The signature covers the exact bytes Stripe sent: read the raw body.
|
||||
const raw = toString(e.request.body);
|
||||
return e.json(200, shop.handleStripeWebhook($app, raw, e.request.header.get('Stripe-Signature')));
|
||||
});
|
||||
|
||||
routerAdd('GET', '/api/shop/order', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
return e.json(200, shop.orderStatus($app, e.request.url.query().get('payment_intent')));
|
||||
});
|
||||
|
||||
routerAdd('POST', '/api/shop/order-email-status', (e) => {
|
||||
const shop = require(`${__hooks}/shop/lib.js`);
|
||||
shop.recordEmailStatus($app, e.request.header.get('X-Internal-Secret'), e.requestInfo().body);
|
||||
return e.noContent(204);
|
||||
});
|
||||
|
||||
// Expired holds are also swept before every basket/checkout call; this
|
||||
// frees slots for the shop listing even when nobody is using a basket.
|
||||
cronAdd('shopSweepHolds', '* * * * *', () => {
|
||||
require(`${__hooks}/shop/lib.js`).sweepExpiredHolds($app);
|
||||
});
|
||||
550
pocketbase/pb_hooks/shop/lib.js
Normal file
550
pocketbase/pb_hooks/shop/lib.js
Normal file
|
|
@ -0,0 +1,550 @@
|
|||
// Shop logic, run inside PocketBase (JSVM). Everything that writes commerce
|
||||
// data — baskets, slot holds, Stripe payments, orders — lives here, so the
|
||||
// public app needs no privileged credentials: it only proxies requests and
|
||||
// keeps the basket cookie. Routes are registered in ../shop.pb.js.
|
||||
//
|
||||
// JSVM notes (PocketBase 0.23): code is synchronous; route/cron handlers run
|
||||
// in isolated contexts, so each handler `require()`s this module; `$app` here
|
||||
// bypasses collection API rules.
|
||||
|
||||
const BASKET_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
/** How long a slot stays held once added to a basket / after a failed payment. */
|
||||
const SLOT_HOLD_MS = 10 * 60 * 1000;
|
||||
/** Hold while a payment is in progress (entering card details, retrying a declined card). */
|
||||
const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000;
|
||||
/** Stripe's default tolerance for webhook timestamps. */
|
||||
const WEBHOOK_TOLERANCE_S = 300;
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
function isoIn(ms) {
|
||||
return new Date(Date.now() + ms).toISOString();
|
||||
}
|
||||
|
||||
/** PocketBase datetime string ("2026-01-01 10:00:00.000Z") → epoch ms, NaN if empty. */
|
||||
function toMs(value) {
|
||||
const s = String(value || '');
|
||||
return s ? Date.parse(s.replace(' ', 'T')) : NaN;
|
||||
}
|
||||
|
||||
/** Record → plain JSON object (the same shape the REST API returns, including expand). */
|
||||
function plain(record) {
|
||||
return JSON.parse(JSON.stringify(record));
|
||||
}
|
||||
|
||||
function findOrNull(app, collection, id) {
|
||||
if (!id) return null;
|
||||
try {
|
||||
return app.findRecordById(collection, id);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function findAll(app, collection, filter, params, sort) {
|
||||
return app.findRecordsByFilter(collection, filter, sort || '', 0, 0, params || {});
|
||||
}
|
||||
|
||||
function newRecord(app, collection, data) {
|
||||
const record = new Record(app.findCollectionByNameOrId(collection));
|
||||
record.load(data);
|
||||
return record;
|
||||
}
|
||||
|
||||
function conflict(message) {
|
||||
return new ApiError(409, message);
|
||||
}
|
||||
|
||||
// ── Holds and baskets ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Release slots whose hold has lapsed (dropping the basket lines holding
|
||||
* them) and abandon expired baskets. Runs every minute (cron) and before
|
||||
* basket/checkout operations, so expiry is exact where it matters.
|
||||
*/
|
||||
function sweepExpiredHolds(app) {
|
||||
const now = Date.now();
|
||||
for (const slot of findAll(app, 'slots', "status = 'held'")) {
|
||||
const until = toMs(slot.getString('heldUntil'));
|
||||
// Still valid, or no parseable hold to judge by — leave it alone.
|
||||
if (Number.isNaN(until) || until > now) continue;
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
for (const line of findAll(tx, 'basket_lines', 'slot = {:slot}', { slot: slot.id })) tx.delete(line);
|
||||
const fresh = tx.findRecordById('slots', slot.id);
|
||||
if (fresh.getString('status') !== 'held') return;
|
||||
fresh.set('status', 'available');
|
||||
fresh.set('heldUntil', '');
|
||||
tx.save(fresh);
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[shop] could not release slot', slot.id, e);
|
||||
}
|
||||
}
|
||||
|
||||
for (const basket of findAll(app, 'baskets', "status = 'active' && expiresAt < @now")) {
|
||||
basket.set('status', 'abandoned');
|
||||
try {
|
||||
app.save(basket);
|
||||
} catch (e) {
|
||||
console.error('[shop] could not abandon basket', basket.id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadActiveBasket(app, basketId) {
|
||||
const basket = findOrNull(app, 'baskets', String(basketId || ''));
|
||||
return basket && basket.getString('status') === 'active' ? basket : null;
|
||||
}
|
||||
|
||||
function basketLines(app, basketId) {
|
||||
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: basketId });
|
||||
}
|
||||
|
||||
/** The basket as returned to the public app, which maps it to the `Basket` type. */
|
||||
function basketPayload(app, basket) {
|
||||
if (!basket) return null;
|
||||
const lines = basketLines(app, basket.id);
|
||||
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
|
||||
return { record: plain(basket), lines: lines.map(plain) };
|
||||
}
|
||||
|
||||
function createBasket(app) {
|
||||
const basket = newRecord(app, 'baskets', { status: 'active', expiresAt: isoIn(BASKET_TTL_MS) });
|
||||
app.save(basket);
|
||||
return basket;
|
||||
}
|
||||
|
||||
function releaseSlotHold(app, slotId) {
|
||||
const slot = findOrNull(app, 'slots', slotId);
|
||||
if (!slot || slot.getString('status') !== 'held') return;
|
||||
slot.set('status', 'available');
|
||||
slot.set('heldUntil', '');
|
||||
app.save(slot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renew the hold on every slot line in a basket whose slot is still `held`
|
||||
* (nobody else can take a held slot, so renewing is safe). Used at checkout
|
||||
* start (30 min) and after a failed payment (10 min, so the customer can retry).
|
||||
*/
|
||||
function extendBasketHolds(app, basketId, durationMs) {
|
||||
const until = isoIn(durationMs);
|
||||
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
|
||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
||||
if (slot && slot.getString('status') === 'held') {
|
||||
slot.set('heldUntil', until);
|
||||
app.save(slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Basket mutations. `body.basketId` is the customer's basket (from their
|
||||
* cookie); a basket is created on the first add. Returns the basket payload.
|
||||
*/
|
||||
function basketAction(app, body) {
|
||||
sweepExpiredHolds(app);
|
||||
|
||||
const action = String(body.action || '');
|
||||
let basket = loadActiveBasket(app, body.basketId);
|
||||
if (!basket && (action === 'add_item' || action === 'add_slot')) basket = createBasket(app);
|
||||
if (!basket) throw new BadRequestError('No active basket — add an item first');
|
||||
const lines = basketLines(app, basket.id);
|
||||
|
||||
switch (action) {
|
||||
case 'add_item': {
|
||||
const itemId = String(body.itemId || '');
|
||||
const quantity = Math.max(1, Math.floor(Number(body.quantity)) || 1);
|
||||
const item = findOrNull(app, 'items', itemId);
|
||||
if (!item || !item.getBool('active')) throw new NotFoundError('Item not found');
|
||||
if (item.getString('type') !== 'item') throw new BadRequestError('Use add_slot for bookable services');
|
||||
|
||||
const existing = lines.find((l) => l.getString('lineType') === 'item' && l.getString('item') === itemId);
|
||||
const newQty = (existing ? existing.getInt('quantity') : 0) + quantity;
|
||||
const stock = item.get('stock');
|
||||
if (stock != null && stock !== '' && newQty > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
||||
|
||||
if (existing) {
|
||||
existing.set('quantity', newQty);
|
||||
app.save(existing);
|
||||
} else {
|
||||
app.save(newRecord(app, 'basket_lines', { basket: basket.id, item: itemId, quantity, lineType: 'item' }));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'add_slot': {
|
||||
const slotId = String(body.slotId || '');
|
||||
if (lines.some((l) => l.getString('slot') === slotId)) throw conflict('Slot already in your basket');
|
||||
const slot = findOrNull(app, 'slots', slotId);
|
||||
if (!slot) throw new NotFoundError('Slot not found');
|
||||
if (slot.getString('status') !== 'available') throw conflict('Slot is no longer available');
|
||||
|
||||
// Line + hold in one transaction. basket_lines.slot is UNIQUE, so of
|
||||
// two concurrent requests for the same slot only one can succeed.
|
||||
try {
|
||||
app.runInTransaction((tx) => {
|
||||
const fresh = tx.findRecordById('slots', slotId);
|
||||
if (fresh.getString('status') !== 'available') throw new Error('taken');
|
||||
tx.save(newRecord(tx, 'basket_lines', { basket: basket.id, item: fresh.getString('item'), slot: slotId, quantity: 1, lineType: 'slot' }));
|
||||
fresh.set('status', 'held');
|
||||
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||
tx.save(fresh);
|
||||
});
|
||||
} catch (_) {
|
||||
throw conflict('Slot was just reserved by someone else');
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'update_quantity': {
|
||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||
if (line.getString('lineType') === 'slot') throw new BadRequestError('Slot lines have fixed quantity 1');
|
||||
const quantity = Number(body.quantity);
|
||||
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
|
||||
const item = findOrNull(app, 'items', line.getString('item'));
|
||||
const stock = item ? item.get('stock') : null;
|
||||
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
||||
line.set('quantity', quantity);
|
||||
app.save(line);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'remove_line': {
|
||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||
const slotId = line.getString('slot');
|
||||
app.delete(line);
|
||||
if (slotId) releaseSlotHold(app, slotId);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new BadRequestError('Unknown action: ' + action);
|
||||
}
|
||||
|
||||
basket.set('expiresAt', isoIn(BASKET_TTL_MS)); // rolling TTL
|
||||
app.save(basket);
|
||||
return basketPayload(app, basket);
|
||||
}
|
||||
|
||||
// ── Stripe ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** Stripe's form encoding, including nested objects (`metadata[basket_id]=…`). */
|
||||
function formEncode(params, prefix) {
|
||||
const parts = [];
|
||||
for (const key of Object.keys(params)) {
|
||||
const value = params[key];
|
||||
if (value === undefined || value === null) continue;
|
||||
const name = prefix ? `${prefix}[${key}]` : key;
|
||||
if (typeof value === 'object') parts.push(formEncode(value, name));
|
||||
else parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(String(value)));
|
||||
}
|
||||
return parts.filter(Boolean).join('&');
|
||||
}
|
||||
|
||||
/** Call the Stripe REST API. Throws an Error with Stripe's message on failure. */
|
||||
function stripe(method, path, params) {
|
||||
const key = $os.getenv('STRIPE_SECRET_KEY');
|
||||
if (!key) throw new InternalServerError('Payments are not configured (STRIPE_SECRET_KEY is not set)');
|
||||
// STRIPE_API_BASE only exists for local testing against stripe-mock.
|
||||
const base = ($os.getenv('STRIPE_API_BASE') || 'https://api.stripe.com').replace(/\/$/, '');
|
||||
const res = $http.send({
|
||||
url: base + path,
|
||||
method,
|
||||
headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: params ? formEncode(params) : '',
|
||||
timeout: 20
|
||||
});
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
const message = (res.json && res.json.error && res.json.error.message) || 'Stripe request failed (HTTP ' + res.statusCode + ')';
|
||||
throw new Error(message);
|
||||
}
|
||||
return res.json;
|
||||
}
|
||||
|
||||
function currency() {
|
||||
return ($os.getenv('STRIPE_CURRENCY') || 'eur').toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Start (or resume) payment for a basket: validate every line against the
|
||||
* database (the source of truth for the total), then create or update the
|
||||
* Stripe PaymentIntent. Returns the client secret for Stripe Elements.
|
||||
*/
|
||||
function startCheckout(app, body) {
|
||||
const basketId = String(body.basketId || '');
|
||||
// Extend holds BEFORE sweeping, so a slot whose hold just lapsed is rescued
|
||||
// rather than released at the moment the customer tries to pay.
|
||||
if (basketId) extendBasketHolds(app, basketId, SLOT_CHECKOUT_HOLD_MS);
|
||||
sweepExpiredHolds(app);
|
||||
|
||||
if (!basketId) throw new BadRequestError('No active basket');
|
||||
const basket = loadActiveBasket(app, basketId);
|
||||
if (!basket) throw new BadRequestError('Your session has expired — please re-select your items');
|
||||
const lines = basketLines(app, basket.id);
|
||||
if (!lines.length) throw new BadRequestError('Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
|
||||
|
||||
const customer = {
|
||||
name: String(body.name || '').trim(),
|
||||
email: String(body.email || '').trim(),
|
||||
phone: String(body.phone || '').trim(),
|
||||
notes: String(body.notes || '').trim()
|
||||
};
|
||||
if (!customer.name) throw new BadRequestError('Name is required');
|
||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(customer.email)) throw new BadRequestError('A valid email is required');
|
||||
|
||||
let totalCents = 0;
|
||||
const summary = [];
|
||||
for (const line of lines) {
|
||||
const item = findOrNull(app, 'items', line.getString('item'));
|
||||
if (!item || !item.getBool('active')) throw conflict('An item in your basket is no longer available');
|
||||
const quantity = line.getInt('quantity');
|
||||
if (line.getString('lineType') === 'slot') {
|
||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
||||
if (!slot || slot.getString('status') !== 'held') {
|
||||
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
|
||||
}
|
||||
} else {
|
||||
const stock = item.get('stock');
|
||||
if (stock != null && stock !== '' && item.getInt('stock') < quantity) {
|
||||
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
|
||||
}
|
||||
}
|
||||
totalCents += Math.round(item.getFloat('price') * 100) * quantity;
|
||||
summary.push(`${quantity}× ${item.getString('name')}`);
|
||||
}
|
||||
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
|
||||
|
||||
let intent = null;
|
||||
const existingId = basket.getString('stripePaymentIntentId');
|
||||
if (existingId) {
|
||||
// Reuse the intent on reload/retry while it can still take a payment.
|
||||
try {
|
||||
const existing = stripe('GET', '/v1/payment_intents/' + encodeURIComponent(existingId));
|
||||
if (existing.status === 'requires_payment_method' || existing.status === 'requires_confirmation') {
|
||||
intent = stripe('POST', '/v1/payment_intents/' + encodeURIComponent(existingId), {
|
||||
amount: totalCents,
|
||||
metadata: { basket_id: basket.id }
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
// Missing/invalid — create a new one below.
|
||||
}
|
||||
}
|
||||
if (!intent) {
|
||||
try {
|
||||
intent = stripe('POST', '/v1/payment_intents', {
|
||||
amount: totalCents,
|
||||
currency: currency(),
|
||||
automatic_payment_methods: { enabled: true },
|
||||
receipt_email: customer.email,
|
||||
metadata: { basket_id: basket.id, line_summary: summary.join('; ').slice(0, 450) }
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[shop] Stripe create intent failed:', e);
|
||||
throw new ApiError(502, 'Payment could not be started — please try again');
|
||||
}
|
||||
}
|
||||
|
||||
basket.set('stripePaymentIntentId', intent.id);
|
||||
basket.set('email', customer.email);
|
||||
basket.set('customerDetails', customer);
|
||||
app.save(basket);
|
||||
return { clientSecret: intent.client_secret };
|
||||
}
|
||||
|
||||
/** Verify a `Stripe-Signature` header (v1 HMAC-SHA256 over "timestamp.body"). */
|
||||
function verifyStripeSignature(rawBody, header, secret) {
|
||||
let timestamp = 0;
|
||||
const signatures = [];
|
||||
for (const part of String(header || '').split(',')) {
|
||||
const [k, v] = part.split('=');
|
||||
if (k === 't') timestamp = Number(v);
|
||||
else if (k === 'v1' && v) signatures.push(v);
|
||||
}
|
||||
if (!timestamp || !signatures.length) return false;
|
||||
if (Math.abs(Date.now() / 1000 - timestamp) > WEBHOOK_TOLERANCE_S) return false;
|
||||
const expected = $security.hs256(timestamp + '.' + rawBody, secret);
|
||||
return signatures.some((sig) => $security.equal(sig, expected));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe webhook. Returns `{ received, orderEmail }`; `orderEmail` is the
|
||||
* data for the booking emails when this call created a new order (the public
|
||||
* app renders and sends them — see packages/shared/src/server/email).
|
||||
*/
|
||||
function handleStripeWebhook(app, rawBody, signature) {
|
||||
const secret = $os.getenv('STRIPE_WEBHOOK_SECRET');
|
||||
if (!secret) throw new InternalServerError('STRIPE_WEBHOOK_SECRET is not configured');
|
||||
if (!verifyStripeSignature(rawBody, signature, secret)) throw new BadRequestError('Webhook signature verification failed');
|
||||
|
||||
const event = JSON.parse(rawBody);
|
||||
const intent = (event.data && event.data.object) || {};
|
||||
if (event.type === 'payment_intent.succeeded') {
|
||||
const orderId = createOrderFromIntent(app, intent);
|
||||
return { received: true, orderEmail: orderId ? orderEmailData(app, orderId) : null };
|
||||
}
|
||||
if (event.type === 'payment_intent.payment_failed') {
|
||||
const basketId = intent.metadata && intent.metadata.basket_id;
|
||||
if (basketId) {
|
||||
// Keep the slots for the customer to retry (fresh 10-minute window);
|
||||
// starting payment again extends them back to 30 minutes.
|
||||
extendBasketHolds(app, basketId, SLOT_HOLD_MS);
|
||||
const basket = findOrNull(app, 'baskets', basketId);
|
||||
if (basket) {
|
||||
basket.set('stripePaymentIntentId', '');
|
||||
app.save(basket);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { received: true, orderEmail: null };
|
||||
}
|
||||
|
||||
/** Turn a paid basket into an order. Idempotent per PaymentIntent; returns the new order id, or null. */
|
||||
function createOrderFromIntent(app, intent) {
|
||||
const basketId = intent.metadata && intent.metadata.basket_id;
|
||||
if (!basketId || !intent.id) return null; // not one of ours
|
||||
|
||||
let orderId = null;
|
||||
app.runInTransaction((tx) => {
|
||||
const existing = findAll(tx, 'orders', 'stripePaymentIntentId = {:id}', { id: intent.id });
|
||||
if (existing.length) return; // Stripe retried — already handled
|
||||
const basket = findOrNull(tx, 'baskets', basketId);
|
||||
if (!basket) return;
|
||||
|
||||
const lines = basketLines(tx, basketId);
|
||||
const order = newRecord(tx, 'orders', {
|
||||
basket: basketId,
|
||||
email: basket.getString('email') || intent.receipt_email || '',
|
||||
customerDetails: JSON.parse(toString(basket.get('customerDetails')) || 'null') || {},
|
||||
total: intent.amount / 100,
|
||||
status: 'paid',
|
||||
stripePaymentIntentId: intent.id
|
||||
});
|
||||
tx.save(order);
|
||||
|
||||
// Snapshot lines, book slots, decrement stock.
|
||||
for (const line of lines) {
|
||||
const item = findOrNull(tx, 'items', line.getString('item'));
|
||||
const slot = findOrNull(tx, 'slots', line.getString('slot'));
|
||||
tx.save(
|
||||
newRecord(tx, 'order_lines', {
|
||||
order: order.id,
|
||||
item: line.getString('item'),
|
||||
slot: line.getString('slot'),
|
||||
quantity: line.getInt('quantity'),
|
||||
lineType: line.getString('lineType'),
|
||||
name: item ? item.getString('name') : 'Unknown item',
|
||||
price: item ? item.getFloat('price') : 0,
|
||||
start: slot ? slot.getString('start') : ''
|
||||
})
|
||||
);
|
||||
if (line.getString('lineType') === 'slot' && slot) {
|
||||
slot.set('status', 'booked');
|
||||
slot.set('heldUntil', '');
|
||||
slot.set('order', order.id);
|
||||
tx.save(slot);
|
||||
} else if (item && item.get('stock') != null && item.get('stock') !== '') {
|
||||
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
|
||||
tx.save(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Basket done — order_lines hold the snapshot.
|
||||
for (const line of lines) tx.delete(line);
|
||||
basket.set('status', 'completed');
|
||||
tx.save(basket);
|
||||
orderId = order.id;
|
||||
});
|
||||
return orderId;
|
||||
}
|
||||
|
||||
// ── Orders ──────────────────────────────────────────────────────────────
|
||||
|
||||
function globalData(app, key) {
|
||||
try {
|
||||
return plain(app.findFirstRecordByFilter('globals', 'key = {:key}', { key })).data || null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function emailTemplate(app, key) {
|
||||
try {
|
||||
return plain(app.findFirstRecordByFilter('email_templates', 'key = {:key}', { key }));
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything the booking emails need — the shape of `OrderEmailData` in packages/shared/src/server/email. */
|
||||
function orderEmailData(app, orderId) {
|
||||
const order = app.findRecordById('orders', orderId);
|
||||
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: orderId }, 'start');
|
||||
for (const line of lines) app.expandRecord(line, ['slot', 'item'], null);
|
||||
return {
|
||||
order: plain(order),
|
||||
lines: lines.map(plain),
|
||||
templates: {
|
||||
customer_confirmation: emailTemplate(app, 'customer_confirmation'),
|
||||
client_alert: emailTemplate(app, 'client_alert')
|
||||
},
|
||||
footer: globalData(app, 'footer'),
|
||||
colors: globalData(app, 'colors')
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment result page. The PaymentIntent id comes from Stripe's redirect;
|
||||
* it is checked with Stripe first, so made-up ids reveal nothing.
|
||||
*/
|
||||
function orderStatus(app, paymentIntentId) {
|
||||
const id = String(paymentIntentId || '');
|
||||
if (!/^pi_[A-Za-z0-9_]+$/.test(id)) return { state: 'missing' };
|
||||
let intent;
|
||||
try {
|
||||
intent = stripe('GET', '/v1/payment_intents/' + encodeURIComponent(id));
|
||||
} catch (_) {
|
||||
return { state: 'invalid' };
|
||||
}
|
||||
|
||||
const orders = findAll(app, 'orders', 'stripePaymentIntentId = {:id}', { id });
|
||||
if (!orders.length) {
|
||||
// The webhook is the source of truth and may not have landed yet.
|
||||
if (intent.status === 'succeeded') return { state: 'processing' };
|
||||
return { state: intent.status === 'canceled' ? 'canceled' : 'failed' };
|
||||
}
|
||||
const order = orders[0];
|
||||
const lines = findAll(app, 'order_lines', 'order = {:order}', { order: order.id }, 'id');
|
||||
return { state: 'paid', order: plain(order), lines: lines.map(plain) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the booking-email outcome reported by the public app. Requires the
|
||||
* shared INTERNAL_API_SECRET and only touches the email status fields.
|
||||
*/
|
||||
function recordEmailStatus(app, secretHeader, body) {
|
||||
const secret = $os.getenv('INTERNAL_API_SECRET');
|
||||
if (!secret || !$security.equal(String(secretHeader || ''), secret)) throw new ForbiddenError('Forbidden');
|
||||
const order = findOrNull(app, 'orders', String(body.orderId || ''));
|
||||
if (!order) throw new NotFoundError('Order not found');
|
||||
const patch = body.patch || {};
|
||||
for (const field of ['customerEmailSentAt', 'clientEmailSentAt', 'emailError']) {
|
||||
if (typeof patch[field] === 'string') order.set(field, patch[field].slice(0, 2000));
|
||||
}
|
||||
app.save(order);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sweepExpiredHolds,
|
||||
loadActiveBasket,
|
||||
basketPayload,
|
||||
basketAction,
|
||||
startCheckout,
|
||||
handleStripeWebhook,
|
||||
orderStatus,
|
||||
recordEmailStatus
|
||||
};
|
||||
33
pocketbase/pb_migrations/1791331200_lock_order_lines.js
Normal file
33
pocketbase/pb_migrations/1791331200_lock_order_lines.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// order_lines was writable by anyone (create/update/delete rules were empty
|
||||
// strings = public), so the line items of real orders could be forged or
|
||||
// deleted through the REST API. Orders are now created by the shop hooks
|
||||
// (pb_hooks/shop), which bypass API rules, so writes are superuser-only.
|
||||
|
||||
function find(app, name) {
|
||||
try {
|
||||
return app.findCollectionByNameOrId(name);
|
||||
} catch (e) {
|
||||
return null; // fresh install: pb_schema.json (already fixed) is imported later
|
||||
}
|
||||
}
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const collection = find(app, 'order_lines');
|
||||
if (!collection) return;
|
||||
collection.createRule = null;
|
||||
collection.updateRule = null;
|
||||
collection.deleteRule = null;
|
||||
app.save(collection);
|
||||
},
|
||||
(app) => {
|
||||
const collection = find(app, 'order_lines');
|
||||
if (!collection) return;
|
||||
collection.createRule = '';
|
||||
collection.updateRule = '';
|
||||
collection.deleteRule = '';
|
||||
app.save(collection);
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue