Shop and checkout: bundles, gift details, codes, confirm without paying
Bundle cards list what they contain and how long the code is valid. In the basket a bundle can be marked as a gift (for / message). Checkout takes a code: covered bookings show "Paid with your code" and cost 0, with what the code has left; when nothing is left to pay the button is Confirm booking and no Stripe step happens. The result page and the confirmation email show bought codes and code-paid bookings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
parent
32984ac01d
commit
e824f16e31
12 changed files with 388 additions and 35 deletions
|
|
@ -1,7 +1,7 @@
|
|||
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 type { Basket, BasketLine, OrderRecord, PassSummary } from '$lib/types';
|
||||
import { sendOrderEmailsFromData, type OrderEmailData } from '$lib/server/email';
|
||||
|
||||
// Client for the shop API in PocketBase (pocketbase/pb_hooks/shop). All
|
||||
|
|
@ -51,7 +51,7 @@ export function postJson<T>(path: string, data: unknown): Promise<T> {
|
|||
});
|
||||
}
|
||||
|
||||
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[] } | null;
|
||||
type BasketPayload = { record: Record<string, any>; lines: Record<string, any>[]; pass?: PassSummary | null } | null;
|
||||
|
||||
/** PocketBase's "2026-01-01 10:00:00.000Z" → ISO. */
|
||||
const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).toISOString();
|
||||
|
|
@ -59,7 +59,7 @@ const pbInstant = (value: string) => new Date(String(value).replace(' ', 'T')).t
|
|||
/** Map the API's raw basket records (plus `unitPrice`/`end` per line) to the `Basket` type used by the UI. */
|
||||
export function mapBasket(payload: BasketPayload): Basket | null {
|
||||
if (!payload) return null;
|
||||
const { record, lines } = payload;
|
||||
const { record, lines, pass } = payload;
|
||||
const mappedLines: BasketLine[] = lines.map((line) => {
|
||||
const item = line.expand?.item;
|
||||
const slot = line.expand?.slot;
|
||||
|
|
@ -79,6 +79,10 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
|||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||
slotKind: slot?.kind,
|
||||
slotCapacity: slot?.capacity,
|
||||
passCovered: !!line.pass,
|
||||
giftTo: line.giftTo || '',
|
||||
giftMessage: line.giftMessage || '',
|
||||
bundle: line.bundle || undefined,
|
||||
heldUntil: line.heldUntil ? pbInstant(line.heldUntil) : undefined
|
||||
};
|
||||
});
|
||||
|
|
@ -90,6 +94,7 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
|||
customerDetails: record.customerDetails || null,
|
||||
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
||||
lines: mappedLines,
|
||||
pass: pass ?? null,
|
||||
serverNow: Date.now()
|
||||
};
|
||||
}
|
||||
|
|
@ -102,7 +107,7 @@ export async function getBasket(basketId: string | undefined): Promise<Basket |
|
|||
return mapBasket(basket);
|
||||
}
|
||||
|
||||
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[]): OrderRecord {
|
||||
export function mapOrder(order: Record<string, any>, lines: Record<string, any>[], passes: PassSummary[] = []): OrderRecord {
|
||||
return {
|
||||
id: order.id,
|
||||
basket: order.basket,
|
||||
|
|
@ -122,8 +127,10 @@ export function mapOrder(order: Record<string, any>, lines: Record<string, any>[
|
|||
name: l.name,
|
||||
price: l.price,
|
||||
start: l.start || null,
|
||||
minutes: l.minutes || null
|
||||
}))
|
||||
minutes: l.minutes || null,
|
||||
passCode: l.passCode || ''
|
||||
})),
|
||||
passes
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,9 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
|||
minutes: body.minutes,
|
||||
start: body.start,
|
||||
seats: body.seats,
|
||||
code: body.code,
|
||||
giftTo: body.giftTo,
|
||||
giftMessage: body.giftMessage,
|
||||
lineId: body.lineId,
|
||||
quantity: body.quantity,
|
||||
basketId: cookies.get(BASKET_COOKIE) || ''
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { BASKET_COOKIE, jsonErrors, postJson } from '$lib/server/shop';
|
||||
import { BASKET_COOKIE, jsonErrors, postJson, sendAndRecordOrderEmails } from '$lib/server/shop';
|
||||
import type { OrderEmailData } from '$lib/server/email';
|
||||
|
||||
type CheckoutResult = { clientSecret: string } | { free: true; orderId: string; orderEmail: OrderEmailData };
|
||||
|
||||
// Starts payment: PocketBase re-validates the basket, extends slot holds and
|
||||
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop).
|
||||
// creates the Stripe PaymentIntent (pocketbase/pb_hooks/shop). When codes
|
||||
// cover the whole basket there is nothing to pay: PocketBase creates the
|
||||
// order straight away, and the booking emails are sent from here (as the
|
||||
// Stripe webhook route does after a payment).
|
||||
export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
|
|
@ -12,12 +18,16 @@ export const POST: RequestHandler = jsonErrors(async ({ request, cookies }) => {
|
|||
throw error(400, 'Invalid JSON body');
|
||||
}
|
||||
|
||||
const { clientSecret } = await postJson<{ clientSecret: string }>('/checkout', {
|
||||
const result = await postJson<CheckoutResult>('/checkout', {
|
||||
basketId: cookies.get(BASKET_COOKIE) || '',
|
||||
name: body.name,
|
||||
email: body.email,
|
||||
phone: body.phone,
|
||||
notes: body.notes
|
||||
});
|
||||
return json({ clientSecret });
|
||||
if ('free' in result) {
|
||||
void sendAndRecordOrderEmails(result.orderEmail);
|
||||
return json({ free: true, orderId: result.orderId });
|
||||
}
|
||||
return json({ clientSecret: result.clientSecret });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,19 +1,27 @@
|
|||
import type { PageServerLoad } from './$types';
|
||||
import { BASKET_COOKIE, mapOrder, shopFetch } from '$lib/server/shop';
|
||||
import type { PassSummary } from '$lib/types';
|
||||
|
||||
type OrderStatus =
|
||||
| { state: 'missing' | 'invalid' | 'processing' | 'canceled' | 'failed' }
|
||||
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[] };
|
||||
| { state: 'paid'; order: Record<string, any>; lines: Record<string, any>[]; passes: PassSummary[] };
|
||||
|
||||
export const load: PageServerLoad = async ({ url, cookies }) => {
|
||||
// After a Stripe payment: ?payment_intent=… (checked with Stripe by
|
||||
// PocketBase; the webhook may not have created the order yet). An order
|
||||
// paid entirely with codes: ?order=…, which PocketBase only shows to the
|
||||
// basket it came from (this visitor's cookie).
|
||||
const intentId = url.searchParams.get('payment_intent');
|
||||
if (!intentId) return { state: 'missing' as const };
|
||||
const orderId = url.searchParams.get('order');
|
||||
let query: string;
|
||||
if (intentId) query = `payment_intent=${encodeURIComponent(intentId)}`;
|
||||
else if (orderId) query = `order=${encodeURIComponent(orderId)}&basket=${encodeURIComponent(cookies.get(BASKET_COOKIE) || '')}`;
|
||||
else return { state: 'missing' as const };
|
||||
|
||||
// PocketBase checks the intent with Stripe and looks up the order (the
|
||||
// webhook is the source of truth and may not have landed yet).
|
||||
const status = await shopFetch<OrderStatus>(`/order?payment_intent=${encodeURIComponent(intentId)}`);
|
||||
const status = await shopFetch<OrderStatus>(`/order?${query}`);
|
||||
if (status.state !== 'paid') return { state: status.state };
|
||||
|
||||
cookies.delete(BASKET_COOKIE, { path: '/' });
|
||||
return { state: 'paid' as const, order: mapOrder(status.order, status.lines) };
|
||||
// Keep the cookie for a code-paid order: it is what lets this page show it on reload.
|
||||
if (intentId) cookies.delete(BASKET_COOKIE, { path: '/' });
|
||||
return { state: 'paid' as const, order: mapOrder(status.order, status.lines, status.passes) };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { formatInstant, formatPrice } from '$shared/calendar';
|
||||
import { formatDuration } from '$shared/items';
|
||||
|
||||
let { data } = $props();
|
||||
|
||||
|
|
@ -32,6 +33,9 @@
|
|||
{#if line.start}
|
||||
<div class="text-sm text-charcoal/60">{formatSlotDate(line.start)}</div>
|
||||
{/if}
|
||||
{#if line.passCode}
|
||||
<div class="text-sm text-charcoal/60">Paid with code {line.passCode}</div>
|
||||
{/if}
|
||||
</div>
|
||||
<span>{formatPrice(line.price * line.quantity, data.currency)}</span>
|
||||
</li>
|
||||
|
|
@ -42,6 +46,28 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{#if data.order.passes?.length}
|
||||
<!-- Bundles bought: their codes (also in the confirmation email). -->
|
||||
<div class="mt-6 rounded-box border border-sage/40 bg-sage/10 p-6 text-left">
|
||||
<h2 class="font-serif text-xl">Your {data.order.passes.length === 1 ? 'code' : 'codes'}</h2>
|
||||
<p class="mt-1 text-sm text-charcoal/70">Enter a code in the basket when you book — the sessions it includes are then already paid for.</p>
|
||||
{#each data.order.passes as pass (pass.id)}
|
||||
<div class="mt-4 rounded-xl bg-white p-4">
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<span class="font-mono text-2xl font-semibold tracking-widest">{pass.code}</span>
|
||||
<span class="text-sm text-charcoal/60">{pass.expiresAt ? `Valid until ${formatInstant(pass.expiresAt, data.timezone, { day: 'numeric', month: 'long', year: 'numeric' })}` : 'No expiry'}</span>
|
||||
</div>
|
||||
<p class="mt-1 font-semibold">{pass.name}{pass.recipientName ? ` · for ${pass.recipientName}` : ''}</p>
|
||||
<ul class="mt-1 text-sm text-charcoal/70">
|
||||
{#each pass.parts as part (`${part.item}|${part.minutes}`)}
|
||||
<li>{part.count}× {part.name}{part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with your order'}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<a class="btn mt-8 rounded-full border-0 px-8 text-primary-content" 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>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue