moved page rendering to a different service and access is now behind
admin.DOMAIN www.DOMAIN db.DOMAIN
This commit is contained in:
parent
c7f6b30b87
commit
1027da989e
126 changed files with 6356 additions and 1516 deletions
79
app-public/src/routes/+layout.server.ts
Normal file
79
app-public/src/routes/+layout.server.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
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) {
|
||||
try {
|
||||
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
return record.data || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals, cookies }) => {
|
||||
const [header, footer, colors] = await Promise.all([
|
||||
getGlobal(locals.pb, 'header', defaultHeader),
|
||||
getGlobal(locals.pb, 'footer', defaultFooter),
|
||||
getGlobal(locals.pb, 'colors', defaultColors)
|
||||
]);
|
||||
|
||||
if (!header.homePage) header.homePage = defaultHeader.homePage;
|
||||
|
||||
// Commerce data for the public site.
|
||||
let basket = null;
|
||||
let items: ItemRecord[] = [];
|
||||
let slots: SlotRecord[] = [];
|
||||
|
||||
try {
|
||||
const pb = await getAdminPb();
|
||||
await sweepExpiredHolds(pb);
|
||||
|
||||
const basketId = cookies.get(BASKET_COOKIE);
|
||||
if (basketId) basket = await loadBasket(pb, basketId);
|
||||
|
||||
const itemRecords = await pb
|
||||
.collection('items')
|
||||
.getFullList({ filter: 'active = true', sort: 'name', expand: 'image' })
|
||||
.catch(() => []);
|
||||
items = itemRecords.map((record) => {
|
||||
const media = record.expand?.image;
|
||||
return {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description || '',
|
||||
price: record.price,
|
||||
image: record.image || '',
|
||||
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
|
||||
type: record.type,
|
||||
stock: record.stock ?? null,
|
||||
duration: record.duration ?? null,
|
||||
active: record.active
|
||||
};
|
||||
});
|
||||
|
||||
const nowIso = new Date().toISOString();
|
||||
const slotRecords = await pb
|
||||
.collection('slots')
|
||||
.getFullList({ filter: `status = 'available' && start >= "${nowIso}"`, sort: 'start' })
|
||||
.catch(() => []);
|
||||
slots = slotRecords.map((record) => ({
|
||||
id: record.id,
|
||||
item: record.item,
|
||||
start: record.start,
|
||||
end: record.end || '',
|
||||
status: record.status,
|
||||
heldUntil: record.heldUntil || null,
|
||||
order: record.order || null,
|
||||
notes: record.notes || ''
|
||||
}));
|
||||
} catch (e) {
|
||||
// Admin PB not configured (e.g. fresh dev env) — commerce features off.
|
||||
console.warn('Commerce data unavailable:', e instanceof Error ? e.message : e);
|
||||
}
|
||||
|
||||
return { header, footer, colors, user: locals.user, basket, items, slots };
|
||||
};
|
||||
40
app-public/src/routes/+layout.svelte
Normal file
40
app-public/src/routes/+layout.svelte
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
<script lang="ts">
|
||||
import '../app.css';
|
||||
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();
|
||||
|
||||
// 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) {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--color-bg', data.colors.background);
|
||||
root.style.setProperty('--color-heading', data.colors.heading);
|
||||
root.style.setProperty('--color-subheading', data.colors.subheading);
|
||||
root.style.setProperty('--color-text', data.colors.text);
|
||||
root.style.setProperty('--color-primary', data.colors.primary);
|
||||
root.style.setProperty('--color-accent', data.colors.accent);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<link rel="icon" href={favicon} />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</svelte:head>
|
||||
|
||||
<Header header={data.header} />
|
||||
<main>{@render children()}</main>
|
||||
<Footer footer={data.footer} />
|
||||
33
app-public/src/routes/+page.server.ts
Normal file
33
app-public/src/routes/+page.server.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { error } from '@sveltejs/kit';
|
||||
import { defaultHeader, type CalendarEventRecord } from '$lib/types';
|
||||
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
// Get home page slug from header global, fallback to 'home'
|
||||
let homeSlug = defaultHeader.homePage;
|
||||
try {
|
||||
const header = await locals.pb.collection('globals').getFirstListItem('key = "header"');
|
||||
homeSlug = header.data?.homePage || homeSlug;
|
||||
} catch {
|
||||
// Use default
|
||||
}
|
||||
|
||||
try {
|
||||
const page = await locals.pb
|
||||
.collection('pages')
|
||||
.getFirstListItem(`slug = "${homeSlug}" && published = true`);
|
||||
let calendarEvents: CalendarEventRecord[] = [];
|
||||
if (hasUpcomingCalendarBlock(page.blocks || [])) {
|
||||
const range = getUpcomingCalendarRange();
|
||||
const events = await locals.pb.collection('events').getFullList({
|
||||
filter: `published = true && start <= "${range.end.toISOString()}"`,
|
||||
sort: 'start'
|
||||
});
|
||||
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
|
||||
}
|
||||
return { page, calendarEvents };
|
||||
} catch {
|
||||
throw error(404, 'Page not found');
|
||||
}
|
||||
};
|
||||
11
app-public/src/routes/+page.svelte
Normal file
11
app-public/src/routes/+page.svelte
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<script lang="ts">
|
||||
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{data.page.title}</title>
|
||||
</svelte:head>
|
||||
|
||||
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />
|
||||
24
app-public/src/routes/[slug]/+page.server.ts
Normal file
24
app-public/src/routes/[slug]/+page.server.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { error } from '@sveltejs/kit';
|
||||
import { eventOverlapsRange, getUpcomingCalendarRange, hasUpcomingCalendarBlock, normalizeEvent } from '$lib/calendar';
|
||||
import type { CalendarEventRecord } from '$lib/types';
|
||||
import type { PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, locals }) => {
|
||||
try {
|
||||
const page = await locals.pb
|
||||
.collection('pages')
|
||||
.getFirstListItem(`slug = "${params.slug}" && published = true`);
|
||||
let calendarEvents: CalendarEventRecord[] = [];
|
||||
if (hasUpcomingCalendarBlock(page.blocks || [])) {
|
||||
const range = getUpcomingCalendarRange();
|
||||
const events = await locals.pb.collection('events').getFullList({
|
||||
filter: `published = true && start <= "${range.end.toISOString()}"`,
|
||||
sort: 'start'
|
||||
});
|
||||
calendarEvents = events.map((event) => normalizeEvent(event)).filter((event) => eventOverlapsRange(event, range.start, range.end));
|
||||
}
|
||||
return { page, calendarEvents };
|
||||
} catch {
|
||||
throw error(404, 'Page not found');
|
||||
}
|
||||
};
|
||||
10
app-public/src/routes/[slug]/+page.svelte
Normal file
10
app-public/src/routes/[slug]/+page.svelte
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<script lang="ts">
|
||||
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
|
||||
let { data } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>{data.page.title}</title>
|
||||
</svelte:head>
|
||||
|
||||
<BlockRenderer blocks={data.page.blocks || []} calendarEvents={data.calendarEvents || []} items={data.items || []} slots={data.slots || []} />
|
||||
167
app-public/src/routes/api/basket/+server.ts
Normal file
167
app-public/src/routes/api/basket/+server.ts
Normal 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 });
|
||||
};
|
||||
102
app-public/src/routes/api/checkout/create-intent/+server.ts
Normal file
102
app-public/src/routes/api/checkout/create-intent/+server.ts
Normal 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 });
|
||||
};
|
||||
122
app-public/src/routes/api/webhooks/stripe/+server.ts
Normal file
122
app-public/src/routes/api/webhooks/stripe/+server.ts
Normal 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 });
|
||||
};
|
||||
64
app-public/src/routes/checkout/return/+page.server.ts
Normal file
64
app-public/src/routes/checkout/return/+page.server.ts
Normal 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 };
|
||||
};
|
||||
72
app-public/src/routes/checkout/return/+page.svelte
Normal file
72
app-public/src/routes/checkout/return/+page.svelte
Normal 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>
|
||||
Loading…
Add table
Add a link
Reference in a new issue