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
|
|
@ -9,6 +9,7 @@ export type BasketStore = ReturnType<typeof createBasketStore>;
|
|||
export function createBasketStore(initial: Basket | null) {
|
||||
let lines = $state<BasketLine[]>(initial?.lines ?? []);
|
||||
let status = $state<Basket['status']>(initial?.status ?? 'active');
|
||||
let pass = $state<Basket['pass']>(initial?.pass ?? null);
|
||||
// Browser clock minus server clock, so hold countdowns survive a wrong clock.
|
||||
let clockOffset = $state(clockOffsetOf(initial));
|
||||
|
||||
|
|
@ -40,6 +41,7 @@ export function createBasketStore(initial: Basket | null) {
|
|||
function applyBasket(basket: Basket | null) {
|
||||
lines = basket?.lines ?? [];
|
||||
status = basket?.status ?? 'active';
|
||||
pass = basket?.pass ?? null;
|
||||
clockOffset = clockOffsetOf(basket);
|
||||
}
|
||||
|
||||
|
|
@ -93,6 +95,20 @@ export function createBasketStore(initial: Basket | null) {
|
|||
await applySlotChange(await callApi({ action: 'renew_holds' }));
|
||||
}
|
||||
|
||||
/** Apply a bundle/voucher code: the bookings it covers cost nothing. */
|
||||
async function applyCode(code: string) {
|
||||
applyBasket(await callApi({ action: 'apply_code', code }));
|
||||
}
|
||||
|
||||
async function removeCode() {
|
||||
applyBasket(await callApi({ action: 'remove_code' }));
|
||||
}
|
||||
|
||||
/** Who a bundle in the basket is for (empty: not a gift). */
|
||||
async function setGift(lineId: string, giftTo: string, giftMessage: string) {
|
||||
applyBasket(await callApi({ action: 'set_gift', lineId, giftTo, giftMessage }));
|
||||
}
|
||||
|
||||
return {
|
||||
get lines() {
|
||||
return lines;
|
||||
|
|
@ -109,13 +125,19 @@ export function createBasketStore(initial: Basket | null) {
|
|||
get holdDeadline() {
|
||||
return holdDeadline;
|
||||
},
|
||||
get pass() {
|
||||
return pass;
|
||||
},
|
||||
refresh,
|
||||
syncFrom,
|
||||
addItemLine,
|
||||
addSlotLine,
|
||||
updateQuantity,
|
||||
removeLine,
|
||||
renewHolds
|
||||
renewHolds,
|
||||
applyCode,
|
||||
removeCode,
|
||||
setGift
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -47,14 +47,64 @@
|
|||
// Prices in the shop currency (STRIPE_CURRENCY, via layout data).
|
||||
const currency = $derived<string>(page.data.currency ?? DEFAULT_CURRENCY);
|
||||
|
||||
/** Codes cover everything: the order is confirmed without a payment step. */
|
||||
const nothingToPay = $derived(basket.lines.length > 0 && basket.total === 0);
|
||||
|
||||
const payLabel = $derived(
|
||||
payState === 'confirming'
|
||||
? 'Confirming…'
|
||||
: payState === 'creating'
|
||||
? 'Preparing payment…'
|
||||
: `Pay ${formatPrice(basket.total, currency)}`
|
||||
? nothingToPay
|
||||
? 'Confirming…'
|
||||
: 'Preparing payment…'
|
||||
: nothingToPay
|
||||
? 'Confirm booking'
|
||||
: `Pay ${formatPrice(basket.total, currency)}`
|
||||
);
|
||||
|
||||
// ── Bundle/voucher code ──
|
||||
let codeInput = $state('');
|
||||
let codeError = $state('');
|
||||
let codeBusy = $state(false);
|
||||
|
||||
async function applyCode() {
|
||||
if (!codeInput.trim() || codeBusy) return;
|
||||
codeBusy = true;
|
||||
codeError = '';
|
||||
try {
|
||||
await basket.applyCode(codeInput.trim());
|
||||
codeInput = '';
|
||||
} catch (e) {
|
||||
codeError = e instanceof Error ? e.message : 'Could not apply the code.';
|
||||
} finally {
|
||||
codeBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeCode() {
|
||||
codeBusy = true;
|
||||
codeError = '';
|
||||
try {
|
||||
await basket.removeCode();
|
||||
} catch (e) {
|
||||
codeError = e instanceof Error ? e.message : 'Could not remove the code.';
|
||||
} finally {
|
||||
codeBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Gifts (bundle lines) ──
|
||||
let giftOpen = $state<Record<string, boolean>>({});
|
||||
|
||||
async function saveGift(line: BasketLine, giftTo: string, giftMessage: string) {
|
||||
if (giftTo === (line.giftTo ?? '') && giftMessage === (line.giftMessage ?? '')) return;
|
||||
try {
|
||||
await basket.setGift(line.id, giftTo, giftMessage);
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Could not save the gift details.';
|
||||
}
|
||||
}
|
||||
|
||||
const timezone = $derived<string>(page.data.timezone ?? DEFAULT_TIMEZONE);
|
||||
|
||||
/** "Fri 15 Jan, 10:00" in the studio's timezone. */
|
||||
|
|
@ -179,7 +229,13 @@
|
|||
`Could not start payment (${res.status}). If you booked a time slot, its hold may have expired — please pick it again from the shop section.`
|
||||
);
|
||||
}
|
||||
const { clientSecret } = await res.json();
|
||||
const result = await res.json();
|
||||
if (result.free) {
|
||||
// Paid in full with a code: the order exists, no payment step.
|
||||
goto('/checkout/return?order=' + encodeURIComponent(result.orderId));
|
||||
return;
|
||||
}
|
||||
const { clientSecret } = result;
|
||||
// Starting payment holds the slots longer; show the new countdown.
|
||||
await basket.refresh();
|
||||
|
||||
|
|
@ -349,11 +405,45 @@
|
|||
{#if line.lineType === 'slot' && line.start}
|
||||
<p class="text-sm text-fg-body/70">{formatSlotTime(line.start)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</p>
|
||||
{/if}
|
||||
{#if line.itemPrice == null}
|
||||
{#if line.passCovered}
|
||||
<p class="text-sm font-medium text-sage-dark">Paid with your code</p>
|
||||
{:else if line.itemPrice == null}
|
||||
<p class="text-sm text-terracotta">No longer offered at this length — please remove it and pick again.</p>
|
||||
{:else}
|
||||
<p class="text-sm text-fg-body/70">{formatPrice(line.itemPrice, currency)}</p>
|
||||
{/if}
|
||||
{#if line.bundle}
|
||||
<p class="text-sm text-fg-body/70">
|
||||
{line.bundle.parts.map((p) => `${p.count}× ${p.name}${p.minutes ? ` (${formatDuration(p.minutes)})` : ''}`).join(', ')}{line.bundle.validMonths
|
||||
? ` · valid ${line.bundle.validMonths} months`
|
||||
: ''}
|
||||
</p>
|
||||
{#if giftOpen[line.id] || line.giftTo}
|
||||
<div class="mt-2 grid gap-2 sm:grid-cols-2">
|
||||
<input
|
||||
type="text"
|
||||
maxlength="180"
|
||||
placeholder="For (their name)"
|
||||
aria-label="Who the gift is for"
|
||||
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
|
||||
value={line.giftTo ?? ''}
|
||||
onchange={(e) => saveGift(line, e.currentTarget.value.trim(), line.giftMessage ?? '')}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
maxlength="1000"
|
||||
placeholder="Message (optional)"
|
||||
aria-label="Gift message"
|
||||
class="rounded-lg border border-charcoal/15 bg-white px-3 py-1.5 text-sm"
|
||||
value={line.giftMessage ?? ''}
|
||||
onchange={(e) => saveGift(line, line.giftTo ?? '', e.currentTarget.value.trim())}
|
||||
/>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-fg-body/60">Shown with the code in your confirmation email — forward it to them, or print it.</p>
|
||||
{:else}
|
||||
<button type="button" class="mt-1 text-sm text-sage-dark underline underline-offset-2" onclick={() => (giftOpen[line.id] = true)}>This is a gift</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Products, and places in a group session (capacity > 1); the server checks what's left. -->
|
||||
|
|
@ -406,6 +496,50 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bundle / voucher code: covers bookings of the same service and length. -->
|
||||
<div class="mt-4 rounded-2xl border border-charcoal/10 bg-white p-5">
|
||||
{#if basket.pass}
|
||||
{@const left = basket.pass.parts.filter((p) => p.redeemable)}
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<p class="font-medium">Code <span class="font-mono tracking-wider">{basket.pass.code}</span> · {basket.pass.name}</p>
|
||||
<p class="text-sm text-fg-body/70">
|
||||
{left.map((p) => `${p.left} × ${p.name} (${formatDuration(p.minutes ?? 0)})`).join(', ')} left after this basket{basket.pass.expiresAt
|
||||
? ` · valid until ${formatInstant(basket.pass.expiresAt, timezone, { day: 'numeric', month: 'long', year: 'numeric' })}`
|
||||
: ''}.
|
||||
</p>
|
||||
{#if !basket.lines.some((l) => l.passCovered)}
|
||||
<p class="mt-1 text-sm text-terracotta">Nothing in your basket matches this code — book one of the sessions above, at the same length.</p>
|
||||
{/if}
|
||||
</div>
|
||||
<button type="button" class="text-sm text-fg-body/70 underline underline-offset-2 disabled:opacity-50" disabled={codeBusy} onclick={removeCode}>Remove code</button>
|
||||
</div>
|
||||
{:else}
|
||||
<form
|
||||
class="flex flex-wrap items-center gap-2"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
applyCode();
|
||||
}}
|
||||
>
|
||||
<label class="text-sm font-medium" for="checkout-code">Have a bundle or voucher code?</label>
|
||||
<input
|
||||
id="checkout-code"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
placeholder="ABCD-2345"
|
||||
class="w-36 rounded-xl border border-charcoal/15 bg-white px-3 py-2 font-mono tracking-wider uppercase focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={codeInput}
|
||||
/>
|
||||
<button type="submit" class="rounded-full border border-charcoal/20 px-4 py-2 text-sm font-medium transition hover:bg-charcoal/5 disabled:opacity-50" disabled={codeBusy || !codeInput.trim()}>
|
||||
{codeBusy ? 'Checking…' : 'Apply'}
|
||||
</button>
|
||||
</form>
|
||||
{/if}
|
||||
{#if codeError}<p class="mt-2 text-sm text-terracotta" role="alert">{codeError}</p>{/if}
|
||||
</div>
|
||||
|
||||
<div class="mt-10 grid gap-10 md:grid-cols-2">
|
||||
<!-- Customer details -->
|
||||
<form
|
||||
|
|
@ -519,7 +653,9 @@
|
|||
|
||||
{#if payState === 'idle' && !errorMsg}
|
||||
<p class="mt-4 text-sm text-fg-body/70">
|
||||
Fill in your details and press Pay to continue to secure payment.
|
||||
{nothingToPay
|
||||
? 'Nothing to pay — your code covers everything. Fill in your details and press Confirm booking.'
|
||||
: 'Fill in your details and press Pay to continue to secure payment.'}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@
|
|||
|
||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||
let result: ItemRecord[] = items;
|
||||
if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
|
||||
if (data.itemTypeFilter && data.itemTypeFilter !== 'all') {
|
||||
result = result.filter((i) => i.type === data.itemTypeFilter);
|
||||
}
|
||||
if (data.itemIds?.length) {
|
||||
|
|
@ -63,6 +63,9 @@
|
|||
|
||||
let isList = $derived(data.layout === 'list');
|
||||
|
||||
/** Item id → name, for what bundles contain. */
|
||||
let itemNames = $derived(new Map(items.map((item: ItemRecord) => [item.id, item.name])));
|
||||
|
||||
/** Changes whenever the basket's bookings do, so open pickers reload (a booking blocks other times). */
|
||||
let basketBookingsKey = $derived(
|
||||
basket.lines
|
||||
|
|
@ -290,7 +293,7 @@
|
|||
{@const isService = item.type === 'item_with_time'}
|
||||
{@const duration = isService ? selectedDuration(item, ui) : null}
|
||||
{@const bookable = !isService || !!duration}
|
||||
{@const soldOut = !isService && item.stock === 0}
|
||||
{@const soldOut = item.type === 'item' && item.stock === 0}
|
||||
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
|
||||
<article
|
||||
class={isList
|
||||
|
|
@ -319,6 +322,17 @@
|
|||
{#if item.description}
|
||||
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
|
||||
{/if}
|
||||
{#if item.type === 'bundle'}
|
||||
<!-- What the bundle contains; its code books the sessions later. -->
|
||||
<ul class="mt-2 space-y-0.5 text-sm text-charcoal/80">
|
||||
{#each item.bundleParts as part (`${part.item}|${part.minutes}`)}
|
||||
<li>{part.count}× {itemNames.get(part.item) ?? 'Item'}{part.minutes ? ` (${formatDuration(part.minutes)})` : ''}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
<p class="mt-1 text-xs text-charcoal/60">
|
||||
You get a code to book the sessions whenever suits you{item.validMonths ? ` — valid ${item.validMonths} months` : ''}. It can be given as a gift.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-auto pt-3">
|
||||
{#if isService && item.durations.length > 1}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { ColorsGlobal, CustomerDetails, EmailBlock, EmailTemplate, FooterGlobal } from '../types';
|
||||
import { formatDuration } from '../items';
|
||||
|
||||
// Pure email rendering — no server or browser APIs, so the admin editor can
|
||||
// render its live preview client-side with exactly the code that sends.
|
||||
|
|
@ -12,6 +13,18 @@ export type EmailLine = {
|
|||
quantity: number;
|
||||
start: string | null;
|
||||
end: string | null;
|
||||
/** The code that paid for this booking. */
|
||||
passCode?: string;
|
||||
};
|
||||
|
||||
/** A bundle/voucher code bought in this order. */
|
||||
export type EmailPass = {
|
||||
code: string; // ABCD-2345
|
||||
name: string;
|
||||
expiresAt: string; // ISO, '' = no expiry
|
||||
recipientName: string;
|
||||
message: string;
|
||||
parts: { name: string; minutes: number | null; count: number }[];
|
||||
};
|
||||
|
||||
export type EmailContext = {
|
||||
|
|
@ -20,6 +33,8 @@ export type EmailContext = {
|
|||
currency: string;
|
||||
customer: CustomerDetails;
|
||||
lines: EmailLine[];
|
||||
/** Codes bought in this order — shown under the booking details. */
|
||||
passes?: EmailPass[];
|
||||
business: FooterGlobal;
|
||||
colors: ColorsGlobal;
|
||||
siteUrl: string;
|
||||
|
|
@ -97,6 +112,20 @@ function formatTime(iso: string, timezone: string): string {
|
|||
}).format(new Date(iso));
|
||||
}
|
||||
|
||||
function formatDate(iso: string, timezone: string): string {
|
||||
return new Intl.DateTimeFormat('en-GB', { timeZone: safeTimeZone(timezone), day: 'numeric', month: 'long', year: 'numeric' }).format(new Date(iso));
|
||||
}
|
||||
|
||||
/** "Valid until 25 October 2027" / "No expiry". */
|
||||
function passValidity(pass: EmailPass, timezone: string) {
|
||||
return pass.expiresAt ? `Valid until ${formatDate(pass.expiresAt, timezone)}` : 'No expiry';
|
||||
}
|
||||
|
||||
/** "3× Massage (1 hour)" / "1× Oil — handed over with this order". */
|
||||
function passPartLabel(part: EmailPass['parts'][number]) {
|
||||
return `${part.count}× ${part.name}${part.minutes ? ` (${formatDuration(part.minutes)})` : ' — handed over with this order'}`;
|
||||
}
|
||||
|
||||
/** "Monday 6 October 2026 at 10:00 – 11:00" (end omitted when unknown). */
|
||||
export function formatLineWhen(line: EmailLine, timezone: string): string {
|
||||
if (!line.start) return '';
|
||||
|
|
@ -236,6 +265,7 @@ function renderBookingDetails(block: EmailBlock, ctx: EmailContext): string {
|
|||
<td valign="top" style="${cell}padding:10px 12px 10px 0;border-bottom:1px solid ${BORDER};">
|
||||
<div style="font-size:16px;font-weight:600;line-height:1.4;">${escapeHtml(qty + line.name)}</div>
|
||||
${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">${escapeHtml(when)}</div>` : ''}
|
||||
${line.passCode ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheading};">Paid with code ${escapeHtml(line.passCode)}</div>` : ''}
|
||||
</td>
|
||||
<td valign="top" align="right" style="${cell}padding:10px 0;border-bottom:1px solid ${BORDER};font-size:15px;white-space:nowrap;">${escapeHtml(formatMoney(line.price * line.quantity, ctx.currency))}</td>
|
||||
</tr>`;
|
||||
|
|
@ -243,7 +273,25 @@ ${when ? `<div style="font-size:14px;line-height:1.5;color:${ctx.colors.subheadi
|
|||
.join('');
|
||||
const total = `<tr><td style="${cell}padding:12px 12px 0 0;font-size:16px;font-weight:700;">Total paid</td><td align="right" style="${cell}padding:12px 0 0;font-size:16px;font-weight:700;white-space:nowrap;">${escapeHtml(formatMoney(ctx.total, ctx.currency))}</td></tr>`;
|
||||
const table = `<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%">${lines}${total}</table>`;
|
||||
return boxed(sectionTitle(block.data.title ?? '', ctx) + table, ctx);
|
||||
return boxed(sectionTitle(block.data.title ?? '', ctx) + table + renderPasses(ctx), ctx);
|
||||
}
|
||||
|
||||
/** The codes an order bought, under its booking details. */
|
||||
function renderPasses(ctx: EmailContext): string {
|
||||
if (!ctx.passes?.length) return '';
|
||||
const small = `font-family:${FONT_BODY};font-size:14px;line-height:1.5;color:${ctx.colors.subheading};margin:4px 0 0;`;
|
||||
const cards = ctx.passes
|
||||
.map(
|
||||
(pass) => `<div style="margin:12px 0 0;padding:14px 16px;border:1px dashed ${ctx.colors.accent};border-radius:8px;">
|
||||
<div style="font-family:'Courier New',Courier,monospace;font-size:24px;font-weight:700;letter-spacing:3px;color:${ctx.colors.text};">${escapeHtml(pass.code)}</div>
|
||||
<div style="font-family:${FONT_BODY};font-size:16px;font-weight:600;line-height:1.4;color:${ctx.colors.text};margin:6px 0 0;">${escapeHtml(pass.name)}${pass.recipientName ? ` · for ${escapeHtml(pass.recipientName)}` : ''}</div>
|
||||
${pass.message ? `<p style="${small}font-style:italic;">“${escapeHtml(pass.message).replace(/\n/g, '<br>')}”</p>` : ''}
|
||||
<p style="${small}">${pass.parts.map((part) => escapeHtml(passPartLabel(part))).join('<br>')}</p>
|
||||
<p style="${small}">${escapeHtml(passValidity(pass, ctx.timezone))}. Enter the code in the basket when booking.</p>
|
||||
</div>`
|
||||
)
|
||||
.join('');
|
||||
return `<div style="font-family:${FONT_BODY};font-size:16px;font-weight:700;color:${ctx.colors.text};margin:20px 0 0;">Your ${ctx.passes.length === 1 ? 'code' : 'codes'}</div>${cards}`;
|
||||
}
|
||||
|
||||
function renderCustomerDetails(block: EmailBlock, ctx: EmailContext): string {
|
||||
|
|
@ -323,9 +371,20 @@ function renderBlockText(block: EmailBlock, ctx: EmailContext, values: Record<st
|
|||
const lines = ctx.lines.map((line) => {
|
||||
const when = formatLineWhen(line, ctx.timezone);
|
||||
const qty = line.quantity > 1 ? `${line.quantity}× ` : '';
|
||||
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}`;
|
||||
return `- ${qty}${line.name} — ${formatMoney(line.price * line.quantity, ctx.currency)}${when ? `\n ${when}` : ''}${line.passCode ? `\n Paid with code ${line.passCode}` : ''}`;
|
||||
});
|
||||
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}`;
|
||||
const passes = (ctx.passes ?? []).map((pass) =>
|
||||
[
|
||||
`\n${pass.code} — ${pass.name}${pass.recipientName ? ` (for ${pass.recipientName})` : ''}`,
|
||||
pass.message && `"${pass.message}"`,
|
||||
...pass.parts.map((part) => ` ${passPartLabel(part)}`),
|
||||
` ${passValidity(pass, ctx.timezone)}. Enter the code in the basket when booking.`
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
);
|
||||
const codes = passes.length ? `\n\nYOUR ${passes.length === 1 ? 'CODE' : 'CODES'}${passes.join('\n')}` : '';
|
||||
return `${title}${lines.join('\n')}\nTotal paid: ${formatMoney(ctx.total, ctx.currency)}${codes}`;
|
||||
}
|
||||
case 'customer_details': {
|
||||
const { name, email, phone, notes } = ctx.customer;
|
||||
|
|
|
|||
|
|
@ -27,3 +27,8 @@ export function formatDuration(minutes: number) {
|
|||
export function lowestPrice(durations: ItemDuration[]) {
|
||||
return durations.length ? Math.min(...durations.map((d) => d.price)) : null;
|
||||
}
|
||||
|
||||
/** A stored code `ABCD2345` → `ABCD-2345`, as shown to people (the shop hooks format it the same way). */
|
||||
export function formatCode(code: string) {
|
||||
return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ import {
|
|||
type FooterGlobal
|
||||
} from '../../types';
|
||||
import { normalizeEmailTemplate } from '../../email/defaults';
|
||||
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine } from '../../email/render';
|
||||
import { renderEmail, sampleEmailContext, type EmailContext, type EmailLine, type EmailPass } from '../../email/render';
|
||||
import { formatCode } from '../../items';
|
||||
import { buildIcs } from './ics';
|
||||
import { sendEmail, type SendResult } from './transport';
|
||||
|
||||
|
|
@ -113,8 +114,10 @@ function bookingIcs(ctx: EmailContext, lineIds: string[], settings: EmailSetting
|
|||
*/
|
||||
export type OrderEmailData = {
|
||||
order: Record<string, any>;
|
||||
/** order_lines with `expand.slot` and `expand.item` */
|
||||
/** order_lines with `expand.slot`, `expand.item` and `expand.pass` */
|
||||
lines: Record<string, any>[];
|
||||
/** passes this order bought (codes) */
|
||||
passes?: Record<string, any>[];
|
||||
templates: Partial<Record<EmailTemplateKey, Record<string, any> | null>>;
|
||||
footer: Partial<FooterGlobal> | null;
|
||||
colors: Partial<ColorsGlobal> | null;
|
||||
|
|
@ -132,15 +135,16 @@ export async function loadOrderEmailData(pb: PocketBase, orderId: string): Promi
|
|||
.collection('email_templates')
|
||||
.getFirstListItem(pb.filter('key = {:key}', { key }))
|
||||
.catch(() => null);
|
||||
const [order, lines, customer_confirmation, client_alert, footer, colors] = await Promise.all([
|
||||
const [order, lines, passes, 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' }),
|
||||
pb.collection('order_lines').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), expand: 'slot,item,pass', sort: 'start' }),
|
||||
pb.collection('passes').getFullList({ filter: pb.filter('order = {:orderId}', { orderId }), sort: 'created' }),
|
||||
template('customer_confirmation'),
|
||||
template('client_alert'),
|
||||
globalData('footer'),
|
||||
globalData('colors')
|
||||
]);
|
||||
return { order, lines, templates: { customer_confirmation, client_alert }, footer, colors };
|
||||
return { order, lines, passes, templates: { customer_confirmation, client_alert }, footer, colors };
|
||||
}
|
||||
|
||||
function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
||||
|
|
@ -159,10 +163,24 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
|||
price: Number(line.price) || 0,
|
||||
quantity: Number(line.quantity) || 1,
|
||||
start,
|
||||
end
|
||||
end,
|
||||
passCode: line.expand?.pass?.code ? formatCode(String(line.expand.pass.code)) : undefined
|
||||
};
|
||||
});
|
||||
|
||||
const passes: EmailPass[] = (data.passes ?? []).map((pass) => ({
|
||||
code: formatCode(String(pass.code || '')),
|
||||
name: String(pass.name || ''),
|
||||
expiresAt: pass.expiresAt ? new Date(String(pass.expiresAt).replace(' ', 'T')).toISOString() : '',
|
||||
recipientName: String(pass.recipientName || ''),
|
||||
message: String(pass.message || ''),
|
||||
parts: (Array.isArray(pass.parts) ? pass.parts : []).map((part: Record<string, any>) => ({
|
||||
name: String(part.name || ''),
|
||||
minutes: part.minutes ? Number(part.minutes) : null,
|
||||
count: Number(part.count) || 0
|
||||
}))
|
||||
}));
|
||||
|
||||
const details = (order.customerDetails || {}) as Partial<CustomerDetails>;
|
||||
const customer: CustomerDetails = {
|
||||
name: String(details.name || ''),
|
||||
|
|
@ -176,6 +194,7 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
|
|||
total: Number(order.total) || 0,
|
||||
customer,
|
||||
lines,
|
||||
passes,
|
||||
...settings
|
||||
};
|
||||
return { ctx, lineIds: lineRecords.map((line) => line.id) };
|
||||
|
|
|
|||
|
|
@ -117,11 +117,14 @@ export const defaultPrivacy: PrivacyGlobal = {
|
|||
|
||||
// ── Commerce types ─────────────────────────────────────────────────────
|
||||
|
||||
export type ItemType = 'item' | 'item_with_time';
|
||||
export type ItemType = 'item' | 'item_with_time' | 'bundle';
|
||||
|
||||
/** One length a service can be booked for, and its price. */
|
||||
export type ItemDuration = { minutes: number; price: number };
|
||||
|
||||
/** Part of a bundle: a service at one length (`minutes`), or a product (`minutes` null), `count` times. */
|
||||
export type BundlePart = { item: string; minutes: number | null; count: number };
|
||||
|
||||
export type ItemRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
|
|
@ -133,6 +136,8 @@ export type ItemRecord = {
|
|||
type: ItemType;
|
||||
stock: number | null;
|
||||
durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
|
||||
bundleParts: BundlePart[]; // bundle: what it contains
|
||||
validMonths: number | null; // bundle: how long its code can be used after purchase (null: no expiry)
|
||||
bufferMinutes: number | null; // get-ready time after each appointment
|
||||
capacity: number | null; // places in a new group session (>1 = group)
|
||||
active: boolean;
|
||||
|
|
@ -158,6 +163,32 @@ export type BookableTime = {
|
|||
free: number; // places still bookable
|
||||
};
|
||||
|
||||
/** A part of a code (pass) with its share of the price and what's left to book. */
|
||||
export type PassPart = {
|
||||
item: string;
|
||||
name: string;
|
||||
minutes: number | null;
|
||||
count: number;
|
||||
value: number;
|
||||
/** Services are booked with the code; products were handed over with the purchase. */
|
||||
redeemable: boolean;
|
||||
used: number;
|
||||
held: number;
|
||||
left: number;
|
||||
};
|
||||
|
||||
/** A bundle/voucher code as the customer and the admin see it. */
|
||||
export type PassSummary = {
|
||||
id: string;
|
||||
code: string; // ABCD-2345
|
||||
name: string;
|
||||
expiresAt: string; // ISO, '' = no expiry
|
||||
status: 'active' | 'void';
|
||||
recipientName: string;
|
||||
message: string;
|
||||
parts: PassPart[];
|
||||
};
|
||||
|
||||
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
||||
|
||||
export type BasketLine = {
|
||||
|
|
@ -178,6 +209,13 @@ export type BasketLine = {
|
|||
itemImageUrl?: string;
|
||||
slotKind?: SlotKind;
|
||||
slotCapacity?: number;
|
||||
/** Slot lines: the basket's code pays for this booking. */
|
||||
passCovered?: boolean;
|
||||
/** Bundle lines: who it's for (shown with its code in the confirmation email). */
|
||||
giftTo?: string;
|
||||
giftMessage?: string;
|
||||
/** Bundle lines: what's in it. */
|
||||
bundle?: { validMonths: number; parts: { item: string; name: string; minutes: number | null; count: number; value: number }[] };
|
||||
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
|
||||
heldUntil?: string;
|
||||
};
|
||||
|
|
@ -190,6 +228,8 @@ export type Basket = {
|
|||
customerDetails: CustomerDetails | null;
|
||||
stripePaymentIntentId: string | null;
|
||||
lines: BasketLine[];
|
||||
/** The code applied at checkout, with what it has left. */
|
||||
pass?: PassSummary | null;
|
||||
/** Server clock (epoch ms) when this was read, so browsers with a wrong clock count holds down correctly. */
|
||||
serverNow?: number;
|
||||
};
|
||||
|
|
@ -214,6 +254,8 @@ export type OrderRecord = {
|
|||
customerEmailSentAt?: string;
|
||||
clientEmailSentAt?: string;
|
||||
emailError?: string;
|
||||
/** Codes this order bought. */
|
||||
passes?: PassSummary[];
|
||||
};
|
||||
|
||||
export type OrderLine = {
|
||||
|
|
@ -228,6 +270,8 @@ export type OrderLine = {
|
|||
start: string | null;
|
||||
/** Slot lines: the booked length. */
|
||||
minutes: number | null;
|
||||
/** The code that paid for this booking ('' if none). */
|
||||
passCode?: string;
|
||||
};
|
||||
|
||||
// ── Block data types ──────────────────────────────────────────────────
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue