Shop: move commerce logic into PocketBase hooks; public app unprivileged

The public (internet-facing) app logged in as the PocketBase superuser and
held the Stripe secret key, so any bug in it could become full control of
the database. Baskets, slot holds, Stripe PaymentIntents, the webhook that
creates orders, and the payment-result lookup now run in PocketBase JS
hooks (pocketbase/pb_hooks/shop, routes under /api/shop/*, plus a cron
that releases expired holds every minute).

The public app's routes keep their URLs but only proxy to those routes and
manage the basket cookie; it has no PocketBase or Stripe secret. Booking
emails are still rendered and sent by the public app (same renderer as the
admin preview) from order data the webhook hook returns; it records the
outcome via a narrow endpoint guarded by INTERNAL_API_SECRET.

Also: slot add and order creation are now transactional; shop listings
load anonymously (already public via API rules); shop API errors always
reach the browser as JSON; the superuser client and stripe package are
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 12:34:58 +00:00
parent 1f929c68ca
commit 773fecc090
14 changed files with 914 additions and 507 deletions

View file

@ -1,15 +1,17 @@
# Secrets read by docker-compose.yml via ${VAR:-} substitution. # Secrets read by docker-compose.yml via ${VAR:-} substitution.
# Copy to .env at the project root and fill in. # 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_... STRIPE_SECRET_KEY=sk_test_...
PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_... PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_... STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_CURRENCY=eur STRIPE_CURRENCY=eur
# PocketBase superuser credentials (used by server-side basket/checkout/webhook APIs) # Shared by PocketBase and the public app so the public app can record
POCKETBASE_ADMIN_EMAIL=admin@example.com # booking-email status on orders (its only write). Generate a long random
POCKETBASE_ADMIN_PASSWORD=changeme # value, e.g.: openssl rand -hex 32
INTERNAL_API_SECRET=
# Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP). # Booking emails via Brevo's SMTP relay (Brevo → SMTP & API → SMTP).
# Leave SMTP_HOST empty in development: emails are then written to the # Leave SMTP_HOST empty in development: emails are then written to the

View file

@ -14,7 +14,6 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.26.9", "pocketbase": "^0.26.9",
"stripe": "^22.3.2",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
@ -1987,23 +1986,6 @@
"node": ">=0.10.0" "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": { "node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",

View file

@ -26,7 +26,6 @@
"daisyui": "^5.5.19", "daisyui": "^5.5.19",
"nodemailer": "^10.0.12", "nodemailer": "^10.0.12",
"pocketbase": "^0.26.9", "pocketbase": "^0.26.9",
"stripe": "^22.3.2",
"tailwindcss": "^4.3.0" "tailwindcss": "^4.3.0"
} }
} }

View 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));
}

View file

@ -1,7 +1,6 @@
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { ItemRecord, SlotRecord } from '$lib/types'; import type { ItemRecord, SlotRecord } from '$lib/types';
import { getAdminPb } from '$lib/server/pb-admin'; import { BASKET_COOKIE, getBasket } from '$lib/server/shop';
import { BASKET_COOKIE, loadBasket, sweepExpiredHolds } from '$lib/server/basket';
import { loadShopData } from '$shared/server/shop'; import { loadShopData } from '$shared/server/shop';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
@ -23,24 +22,18 @@ export const load: LayoutServerLoad = async ({ locals, cookies }) => {
if (!header.homePage) header.homePage = defaultHeader.homePage; if (!header.homePage) header.homePage = defaultHeader.homePage;
// Commerce data for the public site. // Commerce data for the public site. The listing is public data (API
let basket = null; // rules allow active items / available slots); the basket comes from the
let items: ItemRecord[] = []; // shop API in PocketBase. Failures leave the shop empty, never break a page.
let slots: SlotRecord[] = []; const [shop, basket] = await Promise.all([
loadShopData(locals.pb).catch((e) => {
try { console.warn('Shop data unavailable (shop blocks will be empty):', e instanceof Error ? e.message : e);
const pb = await getAdminPb(); return null;
await sweepExpiredHolds(pb); }),
getBasket(cookies.get(BASKET_COOKIE)).catch(() => null)
const basketId = cookies.get(BASKET_COOKIE); ]);
if (basketId) basket = await loadBasket(pb, basketId); const items: ItemRecord[] = shop?.items ?? [];
const slots: SlotRecord[] = shop?.slots ?? [];
({ 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);
}
return { header, footer, colors, user: locals.user, basket, items, slots }; return { header, footer, colors, user: locals.user, basket, items, slots };
}; };

View file

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

View file

@ -1,26 +1,10 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { getAdminPb } from '$lib/server/pb-admin'; import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
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<string, unknown>; let body: Record<string, unknown>;
try { try {
body = await request.json(); body = await request.json();
@ -28,75 +12,12 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
throw error(400, 'Invalid JSON body'); throw error(400, 'Invalid JSON body');
} }
const customer: CustomerDetails = { const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
name: String(body.name || '').trim(), basketId: cookies.get(BASKET_COOKIE) || '',
email: String(body.email || '').trim(), name: body.name,
phone: String(body.phone || '').trim(), email: body.email,
notes: String(body.notes || '').trim() phone: body.phone,
}; notes: body.notes
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 }
}); });
} return json({ clientSecret });
} catch {
// Intent missing/invalid — fall through and create a new one
}
}
if (!paymentIntent) {
paymentIntent = await getStripe().paymentIntents.create({
amount: totalCents,
currency: getCurrency(),
automatic_payment_methods: { enabled: true },
receipt_email: customer.email,
metadata: {
basket_id: basket.id,
line_summary: basket.lines
.map((l) => `${l.quantity}× ${l.itemName ?? l.item}`)
.join('; ')
.slice(0, 450)
}
}); });
}
await pb.collection('baskets').update(basket.id, {
stripePaymentIntentId: paymentIntent.id,
email: customer.email,
customerDetails: customer
});
return json({ clientSecret: paymentIntent.client_secret });
};

View file

@ -1,128 +1,25 @@
import { json, error } from '@sveltejs/kit'; import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private'; import { jsonErrors, sendAndRecordOrderEmails, shopFetch } from '$lib/server/shop';
import { getStripe } from '$lib/stripe.server'; import type { OrderEmailData } from '$lib/server/email';
import { getAdminPb } from '$lib/server/pb-admin';
import { getFileUrl } from '$lib/pb';
import { SLOT_HOLD_MS, extendBasketHolds } from '$lib/server/basket';
import { sendOrderEmails } from '$lib/server/email';
import type PocketBase from 'pocketbase';
async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) { // Stripe webhook endpoint (keeps the URL configured in the Stripe dashboard).
const basketId = paymentIntent.metadata?.basket_id; // PocketBase verifies the signature and creates the order; this app only
if (!basketId) return; // Not one of ours // sends the booking emails, which it can render (pocketbase/pb_hooks/shop).
export const POST: RequestHandler = jsonErrors(async ({ request }) => {
// 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'); const signature = request.headers.get('stripe-signature');
if (!signature) throw error(400, 'Missing Stripe-Signature header'); if (!signature) throw error(400, 'Missing Stripe-Signature header');
let event; // Forward the exact body: the signature covers the raw bytes.
try { const result = await shopFetch<{ received: boolean; orderEmail: OrderEmailData | null }>('/stripe-webhook', {
event = getStripe().webhooks.constructEvent(body, signature, secret); method: 'POST',
} catch (e) { headers: { 'Content-Type': request.headers.get('content-type') || 'application/json', 'Stripe-Signature': signature },
throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`); body: await request.text()
} });
const pb = await getAdminPb(); // 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.
switch (event.type) { if (result.orderEmail) void sendAndRecordOrderEmails(result.orderEmail);
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 }); return json({ received: true });
}; });

View file

@ -1,64 +1,19 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { getStripe } from '$lib/stripe.server'; import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
import { getAdminPb } from '$lib/server/pb-admin';
import { BASKET_COOKIE } from '$lib/server/basket'; type OrderStatus =
import type { OrderRecord } from '$lib/types'; | { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
export const load: PageServerLoad = async ({ url, cookies }) => { export const load: PageServerLoad = async ({ url, cookies }) => {
const intentId = url.searchParams.get('payment_intent'); const intentId = url.searchParams.get('payment_intent');
if (!intentId) return { state: 'missing' as const }; if (!intentId) return { state: 'missing' as const };
let intent; // PocketBase checks the intent with Stripe and looks up the order (the
try { // webhook is the source of truth and may not have landed yet).
intent = await getStripe().paymentIntents.retrieve(intentId); const status = await shopFetch<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`);
} catch { if (status.state !== 'paid') return { state: status.state };
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: '/' }); 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 };
}; };

View file

@ -13,6 +13,15 @@ services:
- pocketbase:/pb_data - pocketbase:/pb_data
# Versioned schema changes; PocketBase applies pending ones on start. # Versioned schema changes; PocketBase applies pending ones on start.
- ./pocketbase/pb_migrations:/pb_migrations:ro,Z - ./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: app-admin:
build: build:
@ -29,9 +38,6 @@ services:
ORIGIN: http://admin.${DOMAIN:-localhost}:8080 ORIGIN: http://admin.${DOMAIN:-localhost}:8080
PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080 PUBLIC_SITE_URL: http://www.${DOMAIN:-localhost}:8080
BODY_SIZE_LIMIT: 52428800 # 50MB — import payload embeds all images as base64 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} STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
# Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends # Booking emails (Brevo SMTP relay) — admin needs these for resend/test sends
SMTP_HOST: ${SMTP_HOST:-} SMTP_HOST: ${SMTP_HOST:-}
@ -58,13 +64,11 @@ services:
POCKETBASE_INTERNAL_URL: http://pocketbase:80 POCKETBASE_INTERNAL_URL: http://pocketbase:80
PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080 PUBLIC_POCKETBASE_URL: http://db.${DOMAIN:-localhost}:8080
ORIGIN: http://www.${DOMAIN:-localhost}:8080 ORIGIN: http://www.${DOMAIN:-localhost}:8080
# Commerce (reservation & payment system) — set these in a root-level .env # No PocketBase or Stripe secrets here: shop writes happen in PocketBase
POCKETBASE_ADMIN_EMAIL: ${POCKETBASE_ADMIN_EMAIL:-} # (pb_hooks/shop). The publishable key is public by design.
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:-} PUBLIC_STRIPE_PUBLISHABLE_KEY: ${PUBLIC_STRIPE_PUBLISHABLE_KEY:-}
STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur} STRIPE_CURRENCY: ${STRIPE_CURRENCY:-eur}
INTERNAL_API_SECRET: ${INTERNAL_API_SECRET:-}
# Booking emails (Brevo SMTP relay) — sent from the Stripe webhook # Booking emails (Brevo SMTP relay) — sent from the Stripe webhook
SMTP_HOST: ${SMTP_HOST:-} SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-587} SMTP_PORT: ${SMTP_PORT:-587}

View file

@ -62,13 +62,14 @@ export function emailSiteUrl(): string {
} }
export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> { export async function loadEmailSettings(pb: PocketBase): Promise<EmailSettings> {
const [business, colors] = await Promise.all([ const [footer, colors] = await Promise.all([getGlobalData(pb, 'footer', {}), getGlobalData(pb, 'colors', {})]);
getGlobalData(pb, 'footer', defaultFooter), return emailSettingsFrom(footer, colors);
getGlobalData(pb, 'colors', defaultColors) }
]);
function emailSettingsFrom(footer: Partial<FooterGlobal> | null, colors: Partial<ColorsGlobal> | null): EmailSettings {
return { return {
business, business: { ...defaultFooter, ...(footer || {}) },
colors, colors: { ...defaultColors, ...(colors || {}) },
siteUrl: emailSiteUrl(), siteUrl: emailSiteUrl(),
timezone: env.SITE_TIMEZONE || 'Europe/Oslo', timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
currency: env.STRIPE_CURRENCY || 'eur' 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; 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); * Everything the booking emails for one order need, as raw PocketBase
const lineRecords = await pb * records (REST JSON shape). Built by `loadOrderEmailData` (admin resend) or
.collection('order_lines') * by the PocketBase shop hooks (`orderEmailData` in pb_hooks/shop/lib.js,
.getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item', sort: 'start' }); * 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 lines: EmailLine[] = lineRecords.map((line) => {
const start = line.start ? new Date(line.start).toISOString() : null; const start = line.start ? new Date(line.start).toISOString() : null;
@ -143,32 +180,34 @@ async function loadOrderContext(pb: PocketBase, orderId: string, settings: Email
lines, lines,
...settings ...settings
}; };
return { order, ctx, lineIds: lineRecords.map((line) => line.id) }; return { ctx, lineIds: lineRecords.map((line) => line.id) };
} }
/** /** Email status fields to write on the order (customerEmailSentAt / clientEmailSentAt / emailError). */
* Render and send the booking emails for a paid order, then record the export type OrderEmailPatch = Record<string, string>;
* outcome on the order (customerEmailSentAt / clientEmailSentAt / emailError).
* Never throws — a failed email must not fail the Stripe webhook; the admin
* can resend from /orders.
*/
export async function sendOrderEmails(
pb: PocketBase,
orderId: string,
kinds: EmailKind[] = ['customer', 'client']
): Promise<Partial<Record<EmailKind, EmailOutcome>>> {
const outcomes: Partial<Record<EmailKind, EmailOutcome>> = {};
try {
const settings = await loadEmailSettings(pb);
const { order, ctx, lineIds } = await loadOrderContext(pb, orderId, settings);
const patch: Record<string, string> = {}; /**
const errorLines = String(order.emailError || '') * 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') .split('\n')
.filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind]))); .filter((line) => line && !kinds.some((kind) => line.startsWith(ERROR_PREFIX[kind])));
for (const kind of kinds) { 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) { if (!template.enabled) {
outcomes[kind] = 'disabled'; outcomes[kind] = 'disabled';
continue; continue;
@ -205,14 +244,31 @@ export async function sendOrderEmails(
} }
patch.emailError = errorLines.join('\n').slice(0, 2000); 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) { } catch (e) {
console.error(`[email] could not prepare emails for order ${orderId}:`, e); console.error(`[email] could not prepare emails for order ${orderId}:`, e);
for (const kind of kinds) outcomes[kind] ??= 'failed'; 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; return outcomes;
} }

View file

@ -7,8 +7,8 @@ import type { ItemRecord, SlotRecord } from '../types';
* blocks. Used by the public layout and the admin draft preview so both * blocks. Used by the public layout and the admin draft preview so both
* render the same shop. * render the same shop.
* *
* `pb` must be able to read items, slots and media (admin client on the * Works with an anonymous client: the API rules expose active items,
* public site, the logged-in superuser in the admin). Errors propagate. * available slots and media publicly. Errors propagate.
*/ */
export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> { export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> {
const [itemRecords, slotRecords] = await Promise.all([ const [itemRecords, slotRecords] = await Promise.all([

View 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);
});

View 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
};