Added shop and checkout to the CMS

Checkout is done with stripe
Added reservation system
This commit is contained in:
Jakub Dorfman 2026-07-29 18:18:23 +02:00
parent 09e54033dd
commit 702d99b9ed
42 changed files with 3332 additions and 21 deletions

View file

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

View file

@ -3,11 +3,21 @@
import favicon from '$lib/assets/favicon.svg';
import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte';
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
import { onMount } from 'svelte';
let { children, data } = $props();
let isAdmin = $derived(data.url?.pathname?.startsWith('/admin'));
// One basket store per public layout instance — provided to all children
// (Header indicator, ShopBlock, CheckoutBlock). Never module-level state.
const basketStore = createBasketStore(data.basket ?? null);
setBasketContext(basketStore);
// Keep the store in sync when layout data refreshes (e.g. after checkout
// clears the cookie and data.basket becomes null).
$effect(() => basketStore.syncFrom(data.basket ?? null));
onMount(() => {
if (data.colors && !isAdmin) {
const root = document.documentElement;

View file

@ -8,4 +8,4 @@
<title>{data.page.title}</title>
</svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} />
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />

View file

@ -7,4 +7,4 @@
<title>{data.page.title}</title>
</svelte:head>
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} />
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />

View file

@ -59,6 +59,9 @@
<div class="flex-none gap-2">
<a class="btn btn-ghost" href="/admin/pages">Pages</a>
<a class="btn btn-ghost" href="/admin/calendar">Calendar</a>
<a class="btn btn-ghost" href="/admin/items">Items</a>
<a class="btn btn-ghost" href="/admin/slots">Slots</a>
<a class="btn btn-ghost" href="/admin/orders">Orders</a>
<a class="btn btn-ghost" href="/admin/globals">Globals</a>
<div class="dropdown dropdown-end">
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">

View file

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

View file

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

View file

@ -0,0 +1,34 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => {
// Sort by id, not 'created' — commerce collections were imported without
// autodate fields. PocketBase ids are time-sortable ULIDs.
const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []);
const orders = [];
for (const record of records) {
const lineRecords = await locals.pb
.collection('order_lines')
.getFullList({ filter: `order = "${record.id}"` })
.catch(() => []);
orders.push({
id: record.id,
email: String(record.email || ''),
customerDetails: record.customerDetails || {},
total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
lines: lineRecords.map((line) => ({
id: line.id,
name: String(line.name || ''),
price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : ''
}))
});
}
return { orders };
};

View file

@ -0,0 +1,58 @@
<script lang="ts">
let { data } = $props();
let orders = $derived(data.orders || []);
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
</script>
<svelte:head><title>Orders | CMS</title></svelte:head>
<div class="space-y-6">
<div>
<h1 class="text-3xl font-bold">Orders</h1>
<p class="text-base-content/60">Confirmed bookings and purchases.</p>
</div>
{#if orders.length === 0}
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">No orders yet.</div>
{/if}
{#each orders as order}
<div class="rounded-box bg-base-100 p-5 shadow">
<div class="flex flex-col justify-between gap-3 md:flex-row md:items-center">
<div>
<h2 class="text-xl font-bold">{order.customerDetails?.name || order.email || 'Order'}</h2>
<p class="text-sm text-base-content/60">
{order.email}
{#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if}
{#if order.created} · {new Date(order.created).toLocaleString()}{/if}
</p>
</div>
<div class="flex items-center gap-3">
<span
class="badge capitalize"
class:badge-success={order.status === 'paid'}
class:badge-warning={order.status === 'pending'}
class:badge-error={order.status === 'refunded'}
>{order.status}</span>
<span class="text-lg font-bold">{eur.format(order.total)}</span>
</div>
</div>
<ul class="mt-4 space-y-1 border-t border-base-300 pt-4">
{#each order.lines as line}
<li>
{line.quantity}× {line.name} — {eur.format(line.price)}
{#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{new Date(line.start).toLocaleString()}</span>
{/if}
</li>
{/each}
</ul>
{#if order.customerDetails?.notes}
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
{/if}
</div>
{/each}
</div>

View file

@ -6,7 +6,12 @@ export const load: PageServerLoad = async ({ params, locals }) => {
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
return { page, eventCategories };
const items = await locals.pb
.collection('items')
.getFullList({ sort: 'name' })
.then((records) => records.map(({ id, name, type }) => ({ id, name, type })))
.catch(() => []);
return { page, eventCategories, items };
};
export const actions: Actions = {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,122 @@
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 type PocketBase from 'pocketbase';
async function handlePaymentSucceeded(pb: PocketBase, paymentIntent: any) {
const basketId = paymentIntent.metadata?.basket_id;
if (!basketId) return; // Not one of ours
// Idempotency: if an order already exists for this intent, we're done.
const existing = await pb
.collection('orders')
.getFirstListItem(`stripePaymentIntentId = "${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: `basket = "${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(() => {});
}
async function handlePaymentFailed(pb: PocketBase, paymentIntent: any) {
const basketId = paymentIntent.metadata?.basket_id;
if (!basketId) return;
// The card was refused (or the payment otherwise failed). Keep the slots
// held for the customer so they can retry without re-picking them — just
// reset the hold to the standard 10-minute window. Starting payment again
// (create-intent) will extend it back to 30 min.
await extendBasketHolds(pb, basketId, SLOT_HOLD_MS).catch(() => {});
if (paymentIntent.id) {
await pb
.collection('baskets')
.update(basketId, { stripePaymentIntentId: null })
.catch(() => {});
}
}
export const POST: RequestHandler = async ({ request }) => {
const secret = env.STRIPE_WEBHOOK_SECRET;
if (!secret) throw error(500, 'STRIPE_WEBHOOK_SECRET is not configured');
// Signature verification MUST use the raw request body.
const body = await request.text();
const signature = request.headers.get('stripe-signature');
if (!signature) throw error(400, 'Missing Stripe-Signature header');
let event;
try {
event = getStripe().webhooks.constructEvent(body, signature, secret);
} catch (e) {
throw error(400, `Webhook signature verification failed: ${e instanceof Error ? e.message : 'unknown'}`);
}
const pb = await getAdminPb();
switch (event.type) {
case 'payment_intent.succeeded':
await handlePaymentSucceeded(pb, event.data.object);
break;
case 'payment_intent.payment_failed':
await handlePaymentFailed(pb, event.data.object);
break;
default:
// Unhandled event types are fine — acknowledge receipt.
break;
}
return json({ received: true });
};

View file

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

View file

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