moved shared code to the shared package
This commit is contained in:
parent
1027da989e
commit
478a5fd466
46 changed files with 43 additions and 5959 deletions
|
|
@ -1,94 +1 @@
|
|||
import { getContext, setContext } from 'svelte';
|
||||
import type { Basket, BasketLine } from '$lib/types';
|
||||
|
||||
const BASKET_KEY = 'basket';
|
||||
|
||||
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');
|
||||
|
||||
const total = $derived(
|
||||
lines.reduce((sum, line) => sum + (line.itemPrice ?? 0) * line.quantity, 0)
|
||||
);
|
||||
const count = $derived(lines.reduce((sum, line) => sum + line.quantity, 0));
|
||||
|
||||
async function callApi(body: Record<string, unknown>): Promise<Basket | null> {
|
||||
const res = await fetch('/api/basket', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Basket request failed (${res.status})`);
|
||||
}
|
||||
const data = await res.json();
|
||||
return data.basket as Basket | null;
|
||||
}
|
||||
|
||||
function applyBasket(basket: Basket | null) {
|
||||
lines = basket?.lines ?? [];
|
||||
status = basket?.status ?? 'active';
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const res = await fetch('/api/basket');
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
applyBasket(data.basket);
|
||||
}
|
||||
|
||||
/** Overwrite local state from server-provided layout data. */
|
||||
function syncFrom(basket: Basket | null) {
|
||||
applyBasket(basket);
|
||||
}
|
||||
|
||||
async function addItemLine(itemId: string, quantity = 1) {
|
||||
applyBasket(await callApi({ action: 'add_item', itemId, quantity }));
|
||||
}
|
||||
|
||||
async function addSlotLine(slotId: string) {
|
||||
applyBasket(await callApi({ action: 'add_slot', slotId }));
|
||||
}
|
||||
|
||||
async function updateQuantity(lineId: string, quantity: number) {
|
||||
applyBasket(await callApi({ action: 'update_quantity', lineId, quantity }));
|
||||
}
|
||||
|
||||
async function removeLine(lineId: string) {
|
||||
applyBasket(await callApi({ action: 'remove_line', lineId }));
|
||||
}
|
||||
|
||||
return {
|
||||
get lines() {
|
||||
return lines;
|
||||
},
|
||||
get total() {
|
||||
return total;
|
||||
},
|
||||
get count() {
|
||||
return count;
|
||||
},
|
||||
get status() {
|
||||
return status;
|
||||
},
|
||||
refresh,
|
||||
syncFrom,
|
||||
addItemLine,
|
||||
addSlotLine,
|
||||
updateQuantity,
|
||||
removeLine
|
||||
};
|
||||
}
|
||||
|
||||
export function setBasketContext(store: BasketStore) {
|
||||
setContext(BASKET_KEY, store);
|
||||
}
|
||||
|
||||
export function getBasketContext(): BasketStore {
|
||||
const store = getContext<BasketStore>(BASKET_KEY);
|
||||
if (!store) throw new Error('Basket store not found in context — is this component inside the public layout?');
|
||||
return store;
|
||||
}
|
||||
export * from '$shared/basket.svelte';
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
<script lang="ts">
|
||||
import type { BlockBackground, BlockForeground } from '$lib/types';
|
||||
|
||||
let {
|
||||
background = { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 } satisfies BlockBackground,
|
||||
foreground = {} as BlockForeground,
|
||||
children
|
||||
} = $props<{
|
||||
background?: BlockBackground;
|
||||
foreground?: BlockForeground;
|
||||
children?: import('svelte').Snippet;
|
||||
}>();
|
||||
|
||||
function bgStyle() {
|
||||
const parts: string[] = [];
|
||||
if (background.type === 'color' && background.color) {
|
||||
parts.push(`background-color: ${background.color};`);
|
||||
}
|
||||
if (background.type === 'image' && background.imageUrl) {
|
||||
parts.push(`background-image: url(${background.imageUrl});`);
|
||||
parts.push(`background-size: cover;`);
|
||||
parts.push(`background-position: center;`);
|
||||
parts.push(`background-repeat: no-repeat;`);
|
||||
parts.push(`background-attachment: ${background.attachment};`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
function fgStyle() {
|
||||
const parts: string[] = [];
|
||||
if (foreground.headingColor) {
|
||||
parts.push(`--fg-heading: ${foreground.headingColor};`);
|
||||
}
|
||||
if (foreground.textColor) {
|
||||
parts.push(`--fg-body: ${foreground.textColor};`);
|
||||
}
|
||||
if (foreground.subheadingColor) {
|
||||
parts.push(`--fg-subheading: ${foreground.subheadingColor};`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
</script>
|
||||
|
||||
<div style={bgStyle() + ' ' + fgStyle()} class="relative">
|
||||
{#if background.type === 'image' && background.overlay && background.imageUrl}
|
||||
<div
|
||||
class="pointer-events-none absolute inset-0"
|
||||
style={`background-color: rgba(0,0,0,${background.overlayOpacity / 100});`}
|
||||
></div>
|
||||
{/if}
|
||||
<div class="relative z-10">
|
||||
{@render children()}
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
<script lang="ts">
|
||||
import type { CalendarEventRecord, ContentBlock, BlockBackground, BlockForeground, ItemRecord, SlotRecord } from '$lib/types';
|
||||
import BackgroundWrapper from './BackgroundWrapper.svelte';
|
||||
import TextBlock from './TextBlock.svelte';
|
||||
import ImageTextBlock from './ImageTextBlock.svelte';
|
||||
import TimelineBlock from './TimelineBlock.svelte';
|
||||
import HeroBlock from './HeroBlock.svelte';
|
||||
import ButtonBlock from './ButtonBlock.svelte';
|
||||
import SpacerBlock from './SpacerBlock.svelte';
|
||||
import TestimonialsBlock from './TestimonialsBlock.svelte';
|
||||
import UpcomingCalendarBlock from './UpcomingCalendarBlock.svelte';
|
||||
import ShopBlock from './ShopBlock.svelte';
|
||||
import CheckoutBlock from './CheckoutBlock.svelte';
|
||||
|
||||
let { blocks = [], calendarEvents = [], items = [], slots = [] } = $props<{
|
||||
blocks: ContentBlock[];
|
||||
calendarEvents?: CalendarEventRecord[];
|
||||
items?: ItemRecord[];
|
||||
slots?: SlotRecord[];
|
||||
}>();
|
||||
|
||||
function getBg(block: ContentBlock): BlockBackground {
|
||||
return (block.data._background as BlockBackground) || { type: 'none', color: '', imageUrl: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
|
||||
}
|
||||
|
||||
function getFg(block: ContentBlock): BlockForeground {
|
||||
return (block.data._foreground as BlockForeground) || {};
|
||||
}
|
||||
</script>
|
||||
|
||||
{#each blocks as block (block.id)}
|
||||
<BackgroundWrapper background={getBg(block)} foreground={getFg(block)}>
|
||||
{#if block.type === 'text'}
|
||||
<TextBlock data={block.data} />
|
||||
{:else if block.type === 'image_text'}
|
||||
<ImageTextBlock data={block.data} />
|
||||
{:else if block.type === 'timeline'}
|
||||
<TimelineBlock data={block.data} />
|
||||
{:else if block.type === 'hero'}
|
||||
<HeroBlock data={block.data} />
|
||||
{:else if block.type === 'button'}
|
||||
<ButtonBlock data={block.data} />
|
||||
{:else if block.type === 'spacer'}
|
||||
<SpacerBlock data={block.data} />
|
||||
{:else if block.type === 'testimonials'}
|
||||
<TestimonialsBlock data={block.data} />
|
||||
{:else if block.type === 'upcoming_calendar'}
|
||||
<UpcomingCalendarBlock data={block.data} events={calendarEvents} />
|
||||
{:else if block.type === 'shop'}
|
||||
<ShopBlock data={block.data} {items} {slots} />
|
||||
{:else if block.type === 'checkout'}
|
||||
<CheckoutBlock data={block.data} />
|
||||
{/if}
|
||||
</BackgroundWrapper>
|
||||
{/each}
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const alignmentClasses: Record<string, string> = {
|
||||
left: 'justify-start',
|
||||
center: 'justify-center',
|
||||
right: 'justify-end'
|
||||
};
|
||||
|
||||
const sizeClasses: Record<string, string> = {
|
||||
xs: 'btn-xs',
|
||||
sm: 'btn-sm',
|
||||
md: '',
|
||||
lg: 'btn-lg'
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="flex {alignmentClasses[data.alignment] || 'justify-center'}">
|
||||
<a
|
||||
href={data.href || '#'}
|
||||
class="btn btn-{data.variant || 'primary'} {sizeClasses[data.size] || ''}"
|
||||
style={data.color ? `background-color: ${data.color}; border-color: ${data.color};` : ''}
|
||||
>
|
||||
{data.label || 'Button'}
|
||||
</a>
|
||||
</div>
|
||||
|
|
@ -1,402 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import { goto } from '$app/navigation';
|
||||
import type { CheckoutBlockData } from '$lib/types';
|
||||
import { getBasketContext } from '$lib/basket.svelte';
|
||||
import { loadStripe } from '$lib/stripe-client';
|
||||
import type { Stripe, StripeElements, StripePaymentElement } from '@stripe/stripe-js';
|
||||
|
||||
let { data = {} } = $props<{ data: CheckoutBlockData }>();
|
||||
|
||||
const basket = getBasketContext();
|
||||
|
||||
const customer = $state({ name: '', email: '', phone: '', notes: '' });
|
||||
let payState = $state<'idle' | 'creating' | 'ready' | 'confirming' | 'error'>('idle');
|
||||
let errorMsg = $state('');
|
||||
|
||||
let paymentDiv = $state<HTMLDivElement | null>(null);
|
||||
let stripe: Stripe | null = null;
|
||||
let elements: StripeElements | null = null;
|
||||
let paymentElement: StripePaymentElement | null = null;
|
||||
let mountedForClientSecret: string | null = null;
|
||||
|
||||
// Tracks lines that have an update/remove request in flight, to disable their controls.
|
||||
let pendingLines = $state<Set<string>>(new Set());
|
||||
|
||||
// Reset the mounted Payment Element back to 'idle' when the basket changes
|
||||
// after the intent was created, so a new intent is made with the new total.
|
||||
let lastSig = '';
|
||||
let basketChanged = $state(false);
|
||||
$effect(() => {
|
||||
const sig = basket.lines.map((l) => `${l.id}:${l.quantity}`).join('|') + `@${basket.total}`;
|
||||
if (lastSig && sig !== lastSig && (payState === 'ready' || payState === 'creating')) {
|
||||
resetPayment();
|
||||
basketChanged = true;
|
||||
} else if (sig === lastSig) {
|
||||
basketChanged = false;
|
||||
}
|
||||
lastSig = sig;
|
||||
});
|
||||
|
||||
const currency = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const payLabel = $derived(
|
||||
payState === 'confirming'
|
||||
? 'Confirming…'
|
||||
: payState === 'creating'
|
||||
? 'Preparing payment…'
|
||||
: `Pay ${currency.format(basket.total)}`
|
||||
);
|
||||
|
||||
function formatSlotTime(iso: string) {
|
||||
return new Date(iso).toLocaleString(undefined, {
|
||||
weekday: 'short',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function resetPayment() {
|
||||
paymentElement?.unmount();
|
||||
paymentElement = null;
|
||||
elements = null;
|
||||
mountedForClientSecret = null;
|
||||
payState = 'idle';
|
||||
}
|
||||
|
||||
function validateCustomer(): boolean {
|
||||
if (!customer.name.trim() || !customer.email.trim()) {
|
||||
errorMsg = 'Please fill in your name and email address.';
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function startPayment() {
|
||||
errorMsg = '';
|
||||
basketChanged = false;
|
||||
if (!validateCustomer()) return;
|
||||
|
||||
payState = 'creating';
|
||||
try {
|
||||
// Refresh from server first — slot holds may have lapsed (10-min TTL)
|
||||
// and the client store would still show stale lines. The server
|
||||
// re-reserves any slot that is still held, so a service won't vanish
|
||||
// just because its hold expired while you were filling in this form.
|
||||
const slotLinesBefore = basket.lines.filter((l) => l.lineType === 'slot');
|
||||
await basket.refresh();
|
||||
|
||||
const lostSlots = slotLinesBefore.filter(
|
||||
(l) => !basket.lines.some((nl) => nl.id === l.id)
|
||||
);
|
||||
if (basket.lines.length === 0) {
|
||||
throw new Error('Your basket is empty — a time slot you selected may have expired. Please pick a slot from the shop and try again.');
|
||||
}
|
||||
if (lostSlots.length) {
|
||||
const names = lostSlots.map((l) => l.itemName).filter(Boolean).join(', ');
|
||||
throw new Error(
|
||||
names
|
||||
? `Your time slot for ${names} is no longer available (it may have expired or been booked by someone else). Please pick another slot from the shop.`
|
||||
: 'A time slot in your basket is no longer available — please pick another slot from the shop.'
|
||||
);
|
||||
}
|
||||
|
||||
const res = await fetch('/api/checkout/create-intent', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...customer })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(
|
||||
err?.message ||
|
||||
`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();
|
||||
|
||||
stripe = await loadStripe();
|
||||
if (!stripe) throw new Error('Payment system failed to load. Please refresh and try again.');
|
||||
|
||||
if (mountedForClientSecret !== clientSecret) {
|
||||
resetPayment();
|
||||
elements = stripe.elements({
|
||||
clientSecret,
|
||||
appearance: {
|
||||
theme: 'flat',
|
||||
variables: {
|
||||
colorPrimary: '#8a9a7b',
|
||||
colorBackground: '#ffffff',
|
||||
colorText: '#2c2c2c',
|
||||
colorDanger: '#c9825f',
|
||||
fontFamily: 'DM Sans, sans-serif',
|
||||
borderRadius: '12px'
|
||||
}
|
||||
}
|
||||
});
|
||||
paymentElement = elements.create('payment');
|
||||
if (browser && paymentDiv) {
|
||||
paymentElement.mount(paymentDiv);
|
||||
mountedForClientSecret = clientSecret;
|
||||
}
|
||||
}
|
||||
payState = 'ready';
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Something went wrong. Please try again.';
|
||||
payState = 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmPayment() {
|
||||
if (!stripe || !elements || !mountedForClientSecret) return;
|
||||
errorMsg = '';
|
||||
payState = 'confirming';
|
||||
|
||||
const { error } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: window.location.origin + '/checkout/return',
|
||||
receipt_email: customer.email
|
||||
},
|
||||
redirect: 'if_required'
|
||||
});
|
||||
|
||||
if (error) {
|
||||
errorMsg = error.message ?? 'Payment failed. Please try again.';
|
||||
payState = 'ready';
|
||||
} else {
|
||||
const intentId = mountedForClientSecret.split('_secret_')[0];
|
||||
goto('/checkout/return?payment_intent=' + encodeURIComponent(intentId));
|
||||
}
|
||||
}
|
||||
|
||||
async function changeQuantity(lineId: string, current: number, delta: number) {
|
||||
const qty = current + delta;
|
||||
if (qty < 1 || pendingLines.has(lineId)) return;
|
||||
pendingLines = new Set(pendingLines).add(lineId);
|
||||
try {
|
||||
await basket.updateQuantity(lineId, qty);
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Failed to update quantity.';
|
||||
} finally {
|
||||
const next = new Set(pendingLines);
|
||||
next.delete(lineId);
|
||||
pendingLines = next;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeLine(lineId: string) {
|
||||
if (pendingLines.has(lineId)) return;
|
||||
pendingLines = new Set(pendingLines).add(lineId);
|
||||
try {
|
||||
await basket.removeLine(lineId);
|
||||
} catch (e) {
|
||||
errorMsg = e instanceof Error ? e.message : 'Failed to remove item.';
|
||||
} finally {
|
||||
const next = new Set(pendingLines);
|
||||
next.delete(lineId);
|
||||
pendingLines = next;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-3xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<h2 class="font-serif text-3xl font-bold md:text-4xl">{data.title}</h2>
|
||||
{/if}
|
||||
{#if data.heading}
|
||||
<p class="mt-2 text-fg-body/70">{data.heading}</p>
|
||||
{/if}
|
||||
|
||||
{#if basket.lines.length === 0}
|
||||
<div class="mt-12 rounded-2xl border border-charcoal/10 bg-white/60 px-6 py-16 text-center">
|
||||
<p class="font-serif text-xl">Your basket is empty</p>
|
||||
<p class="mt-2 text-sm text-fg-body/70">Pick a service or product above.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Basket lines -->
|
||||
<ul class="mt-8 space-y-4">
|
||||
{#each basket.lines as line (line.id)}
|
||||
{@const pending = pendingLines.has(line.id)}
|
||||
<li class="flex items-center gap-4 rounded-2xl border border-charcoal/10 bg-white p-4 shadow-sm">
|
||||
{#if line.itemImageUrl}
|
||||
<img
|
||||
src={line.itemImageUrl}
|
||||
alt={line.itemName ?? 'Item'}
|
||||
class="h-16 w-16 shrink-0 rounded-xl object-cover"
|
||||
/>
|
||||
{:else}
|
||||
<div class="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl bg-sage/15 font-serif text-xl text-sage-dark">
|
||||
{(line.itemName ?? '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate font-medium">{line.itemName ?? 'Item'}</p>
|
||||
{#if line.lineType === 'slot' && line.slotStart}
|
||||
<p class="text-sm text-fg-body/70">{formatSlotTime(line.slotStart)}</p>
|
||||
{/if}
|
||||
<p class="text-sm text-fg-body/70">{currency.format(line.itemPrice ?? 0)}</p>
|
||||
</div>
|
||||
|
||||
{#if line.lineType === 'item'}
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
|
||||
disabled={pending || line.quantity <= 1}
|
||||
aria-label="Decrease quantity"
|
||||
onclick={() => changeQuantity(line.id, line.quantity, -1)}
|
||||
>
|
||||
−
|
||||
</button>
|
||||
<span class="w-6 text-center">{line.quantity}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full border border-charcoal/15 text-lg leading-none disabled:opacity-40"
|
||||
disabled={pending}
|
||||
aria-label="Increase quantity"
|
||||
onclick={() => changeQuantity(line.id, line.quantity, 1)}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<p class="w-20 shrink-0 text-right font-medium">
|
||||
{currency.format((line.itemPrice ?? 0) * line.quantity)}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-charcoal/50 transition-colors hover:bg-terracotta/10 hover:text-terracotta disabled:opacity-40"
|
||||
disabled={pending}
|
||||
aria-label="Remove {line.itemName ?? 'item'}"
|
||||
onclick={() => removeLine(line.id)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<!-- Totals -->
|
||||
<div class="mt-6 rounded-2xl border border-charcoal/10 bg-white p-5">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-fg-body/70">Subtotal</span>
|
||||
<span class="font-serif text-xl font-bold">{currency.format(basket.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-10 grid gap-10 md:grid-cols-2">
|
||||
<!-- Customer details -->
|
||||
<form
|
||||
class="space-y-4"
|
||||
novalidate
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
startPayment();
|
||||
}}
|
||||
>
|
||||
<h3 class="font-serif text-xl font-bold">Your details</h3>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-name">Name *</label>
|
||||
<input
|
||||
id="checkout-name"
|
||||
type="text"
|
||||
required
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.name}
|
||||
autocomplete="name"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-email">Email *</label>
|
||||
<input
|
||||
id="checkout-email"
|
||||
type="email"
|
||||
required
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.email}
|
||||
autocomplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-phone">Phone</label>
|
||||
<input
|
||||
id="checkout-phone"
|
||||
type="tel"
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.phone}
|
||||
autocomplete="tel"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium" for="checkout-notes">
|
||||
{data.notesLabel || 'Notes or special requests'}
|
||||
</label>
|
||||
<textarea
|
||||
id="checkout-notes"
|
||||
rows="3"
|
||||
class="w-full rounded-xl border border-charcoal/15 bg-white px-4 py-3 focus:ring-2 focus:ring-sage/50 focus:outline-none"
|
||||
bind:value={customer.notes}
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
{#if payState === 'idle' || payState === 'creating'}
|
||||
<button
|
||||
type="submit"
|
||||
class="btn w-full rounded-full border-0 text-white"
|
||||
style="background-color: var(--color-primary, #8a9a7b);"
|
||||
disabled={payState === 'creating'}
|
||||
>
|
||||
{payLabel}
|
||||
</button>
|
||||
{/if}
|
||||
</form>
|
||||
|
||||
<!-- Payment -->
|
||||
<div>
|
||||
<h3 class="font-serif text-xl font-bold">Payment</h3>
|
||||
|
||||
{#if errorMsg}
|
||||
<div class="mt-4 flex items-start justify-between gap-3 rounded-xl border border-terracotta/40 bg-terracotta/10 px-4 py-3 text-sm text-charcoal" role="alert">
|
||||
<span>{errorMsg}</span>
|
||||
<button type="button" class="shrink-0 font-bold" aria-label="Dismiss" onclick={() => (errorMsg = '')}>✕</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if basketChanged}
|
||||
<p class="mt-4 rounded-xl border border-sage/30 bg-sage/10 px-4 py-3 text-sm">
|
||||
Basket changed — please press Pay again.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
bind:this={paymentDiv}
|
||||
class="mt-4 rounded-xl border border-charcoal/15 bg-white p-4 {payState === 'ready' || payState === 'confirming' ? '' : 'hidden'}"
|
||||
hidden={payState !== 'ready' && payState !== 'confirming'}
|
||||
></div>
|
||||
|
||||
{#if payState === 'ready' || payState === 'confirming'}
|
||||
<button
|
||||
type="button"
|
||||
class="btn mt-4 w-full rounded-full border-0 text-white"
|
||||
style="background-color: var(--color-primary, #8a9a7b);"
|
||||
disabled={payState === 'confirming'}
|
||||
onclick={confirmPayment}
|
||||
>
|
||||
{payState === 'confirming' ? 'Confirming…' : `Confirm payment — ${currency.format(basket.total)}`}
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#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.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{
|
||||
data: {
|
||||
heading?: string;
|
||||
subheading?: string;
|
||||
buttonLabel?: string;
|
||||
buttonUrl?: string;
|
||||
};
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<section class="relative flex min-h-[80vh] items-center justify-center overflow-hidden px-6 py-20 md:min-h-[90vh]">
|
||||
<div class="relative z-10 mx-auto max-w-4xl text-center">
|
||||
<h1 class="animate-fade-in text-5xl leading-tight text-fg-heading md:text-7xl lg:text-8xl" style="font-family: 'Playfair Display', Georgia, serif;">
|
||||
{data.heading || 'Holistic and Experiential Learning about Happiness'}
|
||||
</h1>
|
||||
{#if data.subheading}
|
||||
<p class="animate-fade-in mx-auto mt-6 max-w-2xl text-lg leading-relaxed text-fg-subheading/70 md:text-xl" style="animation-delay: 0.15s;">
|
||||
{data.subheading}
|
||||
</p>
|
||||
{/if}
|
||||
{#if data.buttonLabel}
|
||||
<div class="animate-fade-in mt-10" style="animation-delay: 0.3s;">
|
||||
<a class="btn rounded-full border-0 bg-sage px-10 py-3 text-lg text-white shadow-lg transition hover:bg-sage-dark hover:shadow-xl" href={data.buttonUrl || '/book'}>
|
||||
{data.buttonLabel}
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
let { data } = $props<{
|
||||
data: { url?: string; alt?: string; content?: string; imagePosition?: 'left' | 'right' };
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<section use:scrollReveal class="reveal mx-auto max-w-6xl px-6 py-14 md:py-20">
|
||||
<div class="grid items-center gap-10 md:grid-cols-2">
|
||||
<div class:md:order-2={data.imagePosition === 'right'} class="overflow-hidden rounded-[2rem] bg-sage/10 shadow-sm">
|
||||
{#if data.url}
|
||||
<img class="aspect-[4/5] w-full object-cover" src={data.url} alt={data.alt || ''} />
|
||||
{:else}
|
||||
<div class="grid aspect-[4/5] place-items-center text-sage-dark">Upload an image</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="prose-wellness text-lg text-fg-body/80">
|
||||
{@html data.content || '<h2>A gentler rhythm</h2><p>Pair meaningful copy with a calming studio image.</p>'}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1,313 +0,0 @@
|
|||
<script lang="ts">
|
||||
import type { ShopBlockData, ItemRecord, SlotRecord } from '$lib/types';
|
||||
import { getBasketContext } from '$lib/basket.svelte';
|
||||
import { getCurrentAndNextMonths } from '$lib/calendar';
|
||||
|
||||
let { data = {}, items = [], slots = [] } = $props<{
|
||||
data: ShopBlockData;
|
||||
items?: ItemRecord[];
|
||||
slots?: SlotRecord[];
|
||||
}>();
|
||||
|
||||
const basket = getBasketContext();
|
||||
|
||||
// Per-card interaction state. Instances are created per component instance
|
||||
// (never shared at module level); keyed by item id so each card is independent.
|
||||
class CardState {
|
||||
pickerOpen = $state(false);
|
||||
selectedDayKey = $state<string | null>(null);
|
||||
adding = $state(false);
|
||||
errorMsg = $state<string | null>(null);
|
||||
justAdded = $state(false);
|
||||
pendingSlotId = $state<string | null>(null);
|
||||
}
|
||||
|
||||
let cardStates = $state<Record<string, CardState>>({});
|
||||
|
||||
const months = getCurrentAndNextMonths();
|
||||
const priceFormatter = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
const timeFormat: Intl.DateTimeFormatOptions = { hour: '2-digit', minute: '2-digit' };
|
||||
const weekdayLetters = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
|
||||
|
||||
let visibleItems: ItemRecord[] = $derived.by(() => {
|
||||
let result: ItemRecord[] = items;
|
||||
if (data.itemTypeFilter === 'item' || data.itemTypeFilter === 'item_with_time') {
|
||||
result = result.filter((i) => i.type === data.itemTypeFilter);
|
||||
}
|
||||
if (data.itemIds?.length) {
|
||||
const wanted = new Set(data.itemIds);
|
||||
result = result
|
||||
.filter((i) => wanted.has(i.id))
|
||||
.sort((a, b) => data.itemIds!.indexOf(a.id) - data.itemIds!.indexOf(b.id));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
// item id -> day key ('YYYY-MM-DD') -> slots on that day, sorted by start time
|
||||
let slotsByDay = $derived.by<Map<string, Map<string, SlotRecord[]>>>(() => {
|
||||
const map = new Map<string, Map<string, SlotRecord[]>>();
|
||||
for (const slot of slots) {
|
||||
const day = new Date(slot.start);
|
||||
if (Number.isNaN(day.getTime())) continue;
|
||||
const key = `${day.getFullYear()}-${`${day.getMonth() + 1}`.padStart(2, '0')}-${`${day.getDate()}`.padStart(2, '0')}`;
|
||||
let itemMap = map.get(slot.item);
|
||||
if (!itemMap) {
|
||||
itemMap = new Map();
|
||||
map.set(slot.item, itemMap);
|
||||
}
|
||||
const list = itemMap.get(key);
|
||||
if (list) list.push(slot);
|
||||
else itemMap.set(key, [slot]);
|
||||
}
|
||||
for (const itemMap of map.values()) {
|
||||
for (const list of itemMap.values()) {
|
||||
list.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime());
|
||||
}
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
let isList = $derived(data.layout === 'list');
|
||||
|
||||
// Lazily create card state for whatever items are rendered.
|
||||
$effect(() => {
|
||||
for (const item of visibleItems) {
|
||||
if (!cardStates[item.id]) cardStates[item.id] = new CardState();
|
||||
}
|
||||
});
|
||||
|
||||
function togglePicker(itemId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state) return;
|
||||
state.pickerOpen = !state.pickerOpen;
|
||||
state.errorMsg = null;
|
||||
state.justAdded = false;
|
||||
state.selectedDayKey = null;
|
||||
}
|
||||
|
||||
function errorMessage(e: unknown, fallback: string) {
|
||||
return e instanceof Error && e.message ? e.message : fallback;
|
||||
}
|
||||
|
||||
async function addItem(itemId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state || state.adding) return;
|
||||
state.adding = true;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
await basket.addItemLine(itemId, 1);
|
||||
} catch (e) {
|
||||
state.errorMsg = errorMessage(e, 'Could not add this item to your basket.');
|
||||
} finally {
|
||||
state.adding = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function addSlot(itemId: string, slotId: string) {
|
||||
const state = cardStates[itemId];
|
||||
if (!state || state.adding) return;
|
||||
state.adding = true;
|
||||
state.pendingSlotId = slotId;
|
||||
state.errorMsg = null;
|
||||
try {
|
||||
await basket.addSlotLine(slotId);
|
||||
state.justAdded = true;
|
||||
} catch (e) {
|
||||
state.errorMsg = errorMessage(e, 'Could not book this time slot.');
|
||||
} finally {
|
||||
state.adding = false;
|
||||
state.pendingSlotId = null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(iso: string) {
|
||||
return new Date(iso).toLocaleTimeString(undefined, timeFormat);
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-6xl px-6 py-16">
|
||||
{#if data.title}
|
||||
<h2 class="mb-12 text-center font-serif text-3xl text-charcoal md:text-4xl">{data.title}</h2>
|
||||
{/if}
|
||||
|
||||
<div class={isList ? 'flex flex-col gap-8' : 'grid gap-8 sm:grid-cols-2 lg:grid-cols-3'}>
|
||||
{#each visibleItems as item (item.id)}
|
||||
{@const ui = cardStates[item.id]}
|
||||
{@const itemSlotsByDay = slotsByDay.get(item.id)}
|
||||
{@const isService = item.type === 'item_with_time'}
|
||||
{@const soldOut = !isService && item.stock === 0}
|
||||
{@const itemInBasket = !isService && basket.lines.some((l) => l.item === item.id)}
|
||||
<article
|
||||
class={isList
|
||||
? 'rounded-2xl border border-charcoal/10 bg-white p-5 shadow-sm sm:flex sm:gap-6'
|
||||
: 'flex flex-col overflow-hidden rounded-2xl border border-charcoal/10 bg-white shadow-sm'}
|
||||
>
|
||||
{#if item.imageUrl}
|
||||
<img
|
||||
src={item.imageUrl}
|
||||
alt={item.name}
|
||||
class={isList ? 'h-44 w-full rounded-xl object-cover sm:h-auto sm:w-56 sm:shrink-0' : 'h-52 w-full object-cover'}
|
||||
/>
|
||||
{:else}
|
||||
<div
|
||||
class={isList
|
||||
? 'flex h-44 w-full items-center justify-center rounded-xl bg-sage/15 font-serif text-5xl text-sage-dark sm:h-auto sm:w-56 sm:shrink-0'
|
||||
: 'flex h-52 w-full items-center justify-center bg-sage/15 font-serif text-5xl text-sage-dark'}
|
||||
aria-hidden="true"
|
||||
>
|
||||
{item.name.trim().charAt(0).toUpperCase() || '·'}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class={isList ? 'mt-4 flex min-w-0 flex-1 flex-col sm:mt-0' : 'flex flex-1 flex-col p-5'}>
|
||||
<h3 class="font-serif text-xl text-charcoal">{item.name}</h3>
|
||||
{#if item.description}
|
||||
<p class="mt-1 line-clamp-3 text-sm text-charcoal/70">{item.description}</p>
|
||||
{/if}
|
||||
|
||||
<div class="mt-auto flex flex-wrap items-center gap-x-3 gap-y-1 pt-3">
|
||||
<span class="text-lg font-semibold text-sage-dark">{priceFormatter.format(item.price)}</span>
|
||||
{#if isService && item.duration != null}
|
||||
<span class="text-xs text-charcoal/60">{item.duration} min</span>
|
||||
{:else if !isService && item.stock != null && item.stock > 0 && item.stock <= 5}
|
||||
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
|
||||
Only {item.stock} left
|
||||
</span>
|
||||
{:else if soldOut}
|
||||
<span class="rounded-full bg-terracotta/15 px-2.5 py-0.5 text-xs font-medium text-terracotta">
|
||||
Sold out
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if ui?.errorMsg}
|
||||
<div
|
||||
class="mt-3 flex items-start justify-between gap-2 rounded-lg border border-terracotta/30 bg-terracotta/10 px-3 py-2 text-sm text-charcoal"
|
||||
role="alert"
|
||||
>
|
||||
<span>{ui.errorMsg}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 leading-none text-charcoal/60 hover:text-charcoal"
|
||||
aria-label="Dismiss error"
|
||||
onclick={() => (ui.errorMsg = null)}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-4 flex items-center gap-3">
|
||||
{#if isService}
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-full px-6 py-2.5 text-sm font-medium transition {ui?.pickerOpen
|
||||
? 'border border-charcoal/15 text-charcoal hover:bg-charcoal/5'
|
||||
: itemSlotsByDay?.size
|
||||
? 'bg-sage text-white hover:bg-sage-dark'
|
||||
: 'cursor-not-allowed bg-charcoal/10 text-charcoal/50'}"
|
||||
disabled={!itemSlotsByDay?.size && !ui?.pickerOpen}
|
||||
onclick={() => togglePicker(item.id)}
|
||||
>
|
||||
{itemSlotsByDay?.size ? (ui?.pickerOpen ? 'Close' : 'Book') : 'No availability'}
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-full bg-sage px-6 py-2.5 text-sm font-medium text-white transition hover:bg-sage-dark disabled:cursor-not-allowed disabled:bg-charcoal/10 disabled:text-charcoal/50"
|
||||
disabled={soldOut || ui?.adding}
|
||||
onclick={() => addItem(item.id)}
|
||||
>
|
||||
{#if ui?.adding}<span class="loading loading-spinner loading-xs"></span>{/if}
|
||||
{soldOut ? 'Sold out' : itemInBasket ? 'Add another' : 'Add to basket'}
|
||||
</button>
|
||||
{#if itemInBasket}
|
||||
<a
|
||||
href="/book"
|
||||
class="inline-flex items-center gap-1 text-sm font-medium text-sage-dark underline-offset-2 hover:underline"
|
||||
>✓ In basket</a
|
||||
>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if isService && ui?.pickerOpen && itemSlotsByDay}
|
||||
<div class={isList ? 'mt-5 border-t border-charcoal/10 pt-5 sm:basis-full' : 'border-t border-charcoal/10 bg-warm p-4'}>
|
||||
<p class="mb-3 text-sm font-medium text-charcoal/70">Select a date</p>
|
||||
<div class="grid gap-6 sm:grid-cols-2">
|
||||
{#each months as month (month.label)}
|
||||
<div>
|
||||
<p class="mb-2 text-center text-sm font-medium text-charcoal/70">{month.label}</p>
|
||||
<div class="grid grid-cols-7 gap-1 text-center">
|
||||
{#each weekdayLetters as letter, i (i)}
|
||||
<span class="py-1 text-xs text-charcoal/40">{letter}</span>
|
||||
{/each}
|
||||
{#each month.days as day (day.dateKey)}
|
||||
{@const selectable = day.inMonth && itemSlotsByDay.has(day.dateKey)}
|
||||
{@const selected = selectable && ui.selectedDayKey === day.dateKey}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!selectable}
|
||||
aria-pressed={selected}
|
||||
onclick={() => (ui.selectedDayKey = day.dateKey)}
|
||||
class="aspect-square rounded-full text-sm transition {selected
|
||||
? 'bg-sage font-semibold text-white'
|
||||
: selectable
|
||||
? 'cursor-pointer bg-sage/15 font-medium text-charcoal hover:bg-sage/35'
|
||||
: 'cursor-default text-charcoal/25'} {!day.inMonth ? 'opacity-40' : ''} {day.isToday &&
|
||||
!selected
|
||||
? 'ring-1 ring-sage/60'
|
||||
: ''}"
|
||||
>
|
||||
{day.dayNumber}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if ui.selectedDayKey}
|
||||
{@const daySlots = itemSlotsByDay.get(ui.selectedDayKey) ?? []}
|
||||
<p class="mt-4 mb-2 text-sm font-medium text-charcoal/70">Available times</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each daySlots as slot (slot.id)}
|
||||
{@const slotInBasket = basket.lines.some((l) => l.slot === slot.id)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={slotInBasket || ui.adding}
|
||||
onclick={() => addSlot(item.id, slot.id)}
|
||||
class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {slotInBasket
|
||||
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
|
||||
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
|
||||
!slotInBasket
|
||||
? 'cursor-wait'
|
||||
: ''}"
|
||||
>
|
||||
{#if ui.pendingSlotId === slot.id}
|
||||
<span class="loading loading-spinner loading-xs"></span>
|
||||
{/if}
|
||||
{formatTime(slot.start)}{item.duration != null ? ` · ${item.duration} min` : ''}{slotInBasket
|
||||
? ' · In basket'
|
||||
: ''}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="mt-4 text-sm text-charcoal/60">
|
||||
Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if ui.justAdded}
|
||||
<p class="mt-3 text-sm font-medium text-sage-dark">
|
||||
Added ✓ — <a href="/book" class="underline underline-offset-2 hover:no-underline">view basket</a>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const height = $derived(data.height ?? 64);
|
||||
</script>
|
||||
|
||||
<div style="height: {height}px;" class="w-full"></div>
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props<{ data: Record<string, any> }>();
|
||||
|
||||
const testimonials = data.items || [
|
||||
{ text: 'Recently I started to experience incredible whole-body orgasms. And now I know how it works. My awareness around sexuality changed for good and I feel like a boss of my own life. What a joy to have this freedom of choice.', title: 'Anne' },
|
||||
{ text: 'I never thought it was possible to sense so much pleasure in my body without intense stimulations I got used to. After the series of sessions, I could feel something like a trance state by receiving only a gentle touch. That was a totally new experience for me.', title: 'Espen' },
|
||||
{ text: "Eva's sexual healing methods should be accessible to everyone. I am amazed by the depth and integrity of the message she conveys through her work. I was meeting Eva for healing my body and, as a result, I reconnected with my heart and soul too.", title: 'Marie' },
|
||||
{ text: "It is hard to surprise me with any sexual activity since I had many exciting experiments in my life. But I always suspected that there might be something more I have not yet felt and tried. Thanks to Eva I realised how much power I've got. Under her guidance, I have learnt to maximise my orgasmic potential and consciously play with arousal. By the way, my wife is also happy that I became enthusiastic about new sexual practices.", title: 'Jan' }
|
||||
];
|
||||
|
||||
const title = data.title || 'What They Say About Me';
|
||||
|
||||
// Simple state for carousel
|
||||
let currentIndex = $state(0);
|
||||
const totalSlides = testimonials.length;
|
||||
|
||||
function next() {
|
||||
currentIndex = (currentIndex + 1) % totalSlides;
|
||||
}
|
||||
|
||||
function prev() {
|
||||
currentIndex = (currentIndex - 1 + totalSlides) % totalSlides;
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="relative min-h-[400px]">
|
||||
<div class="flex flex-col items-center px-4 py-12 min-h-[400px]">
|
||||
<!-- Title -->
|
||||
<h2 class="text-fg-heading text-2xl md:text-3xl font-light tracking-wide">
|
||||
{title}
|
||||
</h2>
|
||||
|
||||
<!-- Testimonial carousel - fills remaining space and centers content vertically -->
|
||||
<div class="w-full max-w-3xl flex-1 flex items-center justify-center">
|
||||
<!-- Slides are stacked in a grid so the carousel keeps the height of the tallest testimonial. -->
|
||||
<div class="grid px-8 text-center w-full pt-4 md:pt-8">
|
||||
{#each testimonials as testimonial, i}
|
||||
<div class="col-start-1 row-start-1 transition-opacity duration-300 {i === currentIndex ? 'opacity-100' : 'pointer-events-none opacity-0'}" aria-hidden={i !== currentIndex}>
|
||||
<p class="text-fg-body/85 text-lg md:text-xl font-light leading-relaxed mb-8">
|
||||
"{testimonial.text}"
|
||||
</p>
|
||||
<p class="text-fg-subheading font-medium tracking-wider">
|
||||
— {testimonial.title}
|
||||
</p>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Navigation arrows -->
|
||||
<div class="flex justify-center items-center gap-8">
|
||||
<button
|
||||
type="button"
|
||||
onclick={prev}
|
||||
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
|
||||
aria-label="Previous slide"
|
||||
>
|
||||
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
<polyline points="6.5,0.5 1.5,6.5 6.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<!-- Dots/bullets -->
|
||||
<div class="flex text-fg-heading gap-3">
|
||||
{#each testimonials as _, i}
|
||||
<button
|
||||
type="button"
|
||||
class="w-2.5 h-2.5 rounded-full border-2 transition-colors {i === currentIndex ? 'bg-current' : 'border-current'}"
|
||||
aria-label="Go to slide {i + 1}"
|
||||
onclick={() => (currentIndex = i)}
|
||||
></button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onclick={next}
|
||||
class="w-10 h-10 rounded-full flex items-center justify-center transition-colors hover:bg-[rgba(255,236,224,1)] hover:text-[#93384a] bg-[rgba(255,219,197,0.8)]"
|
||||
aria-label="Next slide"
|
||||
>
|
||||
<svg viewBox="0 0 7.3 13" class="w-2 h-3" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||
<polyline points="0.5,0.5 5.5,6.5 0.5,12.5" stroke-linecap="butt" stroke-linejoin="miter"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
let { data } = $props<{ data: { content?: string } }>();
|
||||
</script>
|
||||
|
||||
<section use:scrollReveal class="reveal mx-auto max-w-3xl px-6 py-12 md:py-16">
|
||||
<div class="prose-wellness text-lg text-fg-body/85">
|
||||
{@html data.content || '<h2>Welcome</h2><p>Add warm, inviting copy in the CMS.</p>'}
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { scrollReveal } from '$lib/scrollReveal';
|
||||
|
||||
type TimelineItem = { title: string; description: string };
|
||||
let { data } = $props<{ data: { items?: TimelineItem[] } }>();
|
||||
let items = $derived(data.items?.length ? data.items : [
|
||||
{ title: 'Your story here', description: 'Add milestones, training, or the journey behind the practice.' }
|
||||
]);
|
||||
let widths = $derived(items.map((_: TimelineItem, i: number) => {
|
||||
const opts = ['w-[78%]', 'w-[85%]', 'w-[90%]', 'w-[95%]', 'w-[98%]'];
|
||||
return opts[(i * 7 + 3) % opts.length];
|
||||
}));
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-7xl px-6 py-12">
|
||||
<div class="mb-8 text-center">
|
||||
<p class="mb-2 text-xs font-semibold uppercase tracking-[0.25em] text-sage-dark">Journey</p>
|
||||
<h2 class="text-3xl md:text-4xl" use:scrollReveal>A practice shaped over time</h2>
|
||||
</div>
|
||||
<div class="relative md:before:absolute md:before:left-1/2 md:before:top-0 md:before:h-full md:before:w-px md:before:bg-sage/30">
|
||||
{#each items as item, index}
|
||||
<div use:scrollReveal class="reveal relative mb-[-1rem] grid gap-4 md:grid-cols-2 md:gap-8">
|
||||
<div class="hidden md:block" class:md:order-2={index % 2 === 0}></div>
|
||||
<article class="rounded-2xl bg-white/75 p-5 shadow-sm ring-1 ring-charcoal/5 -mt-4 {widths[index]} {index % 2 === 0 ? 'md:ml-auto md:text-right' : ''}">
|
||||
<h3 class="text-xl">{item.title}</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-fg-body/70">{item.description}</p>
|
||||
</article>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</section>
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
<script lang="ts">
|
||||
import type { CalendarEventRecord, UpcomingCalendarBlockData } from '$lib/types';
|
||||
import {
|
||||
dateKey,
|
||||
eventMatchesCategories,
|
||||
eventOverlapsDay,
|
||||
eventRange,
|
||||
formatEventDateRange,
|
||||
getCurrentAndNextMonths,
|
||||
isExternalLink,
|
||||
normalizeLink,
|
||||
sortEvents
|
||||
} from '$lib/calendar';
|
||||
|
||||
let { data = {}, events = [] } = $props<{
|
||||
data: UpcomingCalendarBlockData;
|
||||
events?: CalendarEventRecord[];
|
||||
}>();
|
||||
|
||||
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
let months = $derived(getCurrentAndNextMonths());
|
||||
let selectedCategories = $derived(data.categories || []);
|
||||
let visibleEvents = $derived(sortEvents(events.filter((event: CalendarEventRecord) => event.published && eventMatchesCategories(event, selectedCategories))));
|
||||
|
||||
function eventsForDay(date: Date) {
|
||||
return visibleEvents.filter((event) => eventOverlapsDay(event, date));
|
||||
}
|
||||
|
||||
function eventStyle(event: CalendarEventRecord) {
|
||||
return `--event-color: ${event.color || '#8a9a7b'};`;
|
||||
}
|
||||
|
||||
function segmentMeta(event: CalendarEventRecord, date: Date) {
|
||||
const { start, end } = eventRange(event);
|
||||
const isStart = dateKey(start) === dateKey(date);
|
||||
const isEnd = dateKey(end) === dateKey(date);
|
||||
const startsWeek = date.getDay() === 0;
|
||||
const endsWeek = date.getDay() === 6;
|
||||
const visualStart = isStart || startsWeek;
|
||||
const visualEnd = isEnd || endsWeek;
|
||||
|
||||
return {
|
||||
showLabel: visualStart,
|
||||
classes: [
|
||||
visualStart ? 'rounded-l-xl' : 'rounded-l-none -ml-3',
|
||||
visualEnd ? 'rounded-r-xl' : 'rounded-r-none -mr-3',
|
||||
visualStart && visualEnd ? 'mx-0' : '',
|
||||
!visualStart && !visualEnd ? '-mx-3' : ''
|
||||
].filter(Boolean).join(' ')
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="mx-auto max-w-7xl px-6 py-16">
|
||||
<div class="mb-10 text-center">
|
||||
<h2 class="font-display mt-2 text-4xl text-charcoal md:text-5xl">{data.title}</h2>
|
||||
</div>
|
||||
|
||||
{#if visibleEvents.length === 0}
|
||||
<div class="mx-auto max-w-2xl rounded-[2rem] border border-sage/20 bg-white/70 p-8 text-center shadow-sm">
|
||||
<p class="text-charcoal/70">No upcoming events are available for the selected categories.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="isolate grid gap-8 lg:grid-cols-2">
|
||||
{#each months as month}
|
||||
<div class="relative z-0 overflow-visible rounded-[2rem] border border-sage/15 bg-white/80 p-5 shadow-sm backdrop-blur hover:z-[9000] focus-within:z-[9000]">
|
||||
<h3 class="font-display mb-5 text-center text-3xl text-charcoal">{month.label}</h3>
|
||||
<div class="mb-2 grid grid-cols-7 gap-1 text-center text-xs font-semibold uppercase tracking-wide text-charcoal/45">
|
||||
{#each weekdays as weekday}<div>{weekday}</div>{/each}
|
||||
</div>
|
||||
<div class="grid grid-cols-7 gap-1 overflow-visible">
|
||||
{#each month.days as day}
|
||||
<div class="relative min-h-28 overflow-visible rounded-2xl border p-2 {day.inMonth ? 'border-sage/10 bg-warm/60' : 'border-sage/5 bg-warm/25'}" class:ring-2={day.isToday} class:ring-sage={day.isToday}>
|
||||
<div class="mb-1 flex items-center justify-between">
|
||||
<span class="text-sm font-semibold {day.inMonth ? 'text-charcoal/70' : 'text-charcoal/30'}">{day.dayNumber}</span>
|
||||
</div>
|
||||
<div class="space-y-1">
|
||||
{#each eventsForDay(day.date) as event}
|
||||
{@const href = normalizeLink(event.link)}
|
||||
{@const label = `${event.name}${event.description ? `: ${event.description}` : ''}`}
|
||||
{@const segment = segmentMeta(event, day.date)}
|
||||
{#if href}
|
||||
<a
|
||||
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] hover:shadow-md focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
|
||||
href={href}
|
||||
target={isExternalLink(href) ? '_blank' : undefined}
|
||||
rel={isExternalLink(href) ? 'noreferrer' : undefined}
|
||||
style={eventStyle(event)}
|
||||
aria-label={label}
|
||||
>
|
||||
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
|
||||
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
|
||||
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
|
||||
<strong class="block">{event.name}</strong>
|
||||
<span class="block opacity-80">{formatEventDateRange(event)}</span>
|
||||
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
|
||||
</span>
|
||||
</a>
|
||||
{:else}
|
||||
<span
|
||||
class="group/event relative z-10 block px-2 py-1 text-left text-[0.7rem] font-semibold leading-tight text-white shadow-sm hover:z-[9999] focus:z-[9999] focus:outline-none focus:ring-2 focus:ring-charcoal/30 {segment.classes}"
|
||||
style={eventStyle(event)}
|
||||
tabindex="0"
|
||||
role="button"
|
||||
aria-label={label}
|
||||
>
|
||||
<span class="absolute inset-0 bg-[var(--event-color)] {segment.classes}"></span>
|
||||
<span class="relative block truncate">{segment.showLabel ? event.name : '\u00a0'}</span>
|
||||
<span class="pointer-events-none absolute bottom-full left-0 z-[10000] mb-2 hidden w-64 rounded-xl bg-charcoal p-3 text-xs font-normal leading-relaxed text-white shadow-xl group-hover/event:block group-focus/event:block">
|
||||
<strong class="block">{event.name}</strong>
|
||||
<span class="block opacity-80">{formatEventDateRange(event)}</span>
|
||||
{#if event.description}<span class="mt-1 block">{event.description}</span>{/if}
|
||||
</span>
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
|
@ -1,37 +1 @@
|
|||
import PocketBase from 'pocketbase';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
export const pbUrl = env.PUBLIC_POCKETBASE_URL;
|
||||
|
||||
export function createPocketBase(authCookie?: string, url = pbUrl) {
|
||||
const pb = new PocketBase(url);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
if (authCookie) {
|
||||
pb.authStore.loadFromCookie(authCookie, 'pb_auth');
|
||||
} else if (browser) {
|
||||
pb.authStore.loadFromCookie(document.cookie, 'pb_auth');
|
||||
}
|
||||
|
||||
return pb;
|
||||
}
|
||||
|
||||
export const pb = createPocketBase();
|
||||
|
||||
export function getFileUrl(collectionIdOrName: string, recordId: string, filename: string) {
|
||||
return `${pbUrl}/api/files/${collectionIdOrName}/${recordId}/${filename}`;
|
||||
}
|
||||
|
||||
export async function uploadMedia(file: File) {
|
||||
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) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Upload failed (${res.status})`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
export { pbUrl, createPocketBase, getFileUrl } from '$shared/pb';
|
||||
|
|
|
|||
|
|
@ -1,30 +1 @@
|
|||
/**
|
||||
* Scroll reveal Svelte action — applies a CSS class when the element enters the viewport.
|
||||
* Usage: <div use:scrollReveal class="reveal">...</div>
|
||||
* The `reveal` class is hidden initially; `reveal-visible` is added on intersection.
|
||||
*/
|
||||
|
||||
export function scrollReveal(node: HTMLElement, delay: number = 0) {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
if (delay > 0) {
|
||||
node.style.transitionDelay = `${delay}s`;
|
||||
}
|
||||
node.classList.add('reveal-visible');
|
||||
observer.unobserve(node);
|
||||
}
|
||||
}
|
||||
},
|
||||
{ threshold: 0.1, rootMargin: '0px 0px -40px 0px' }
|
||||
);
|
||||
|
||||
observer.observe(node);
|
||||
|
||||
return {
|
||||
destroy() {
|
||||
observer.disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
export * from '$shared/scrollReveal';
|
||||
|
|
|
|||
|
|
@ -1,187 +1 @@
|
|||
import type PocketBase from 'pocketbase';
|
||||
import type { Basket, BasketLine } from '$lib/types';
|
||||
import { getFileUrl } from '$lib/pb';
|
||||
|
||||
export const BASKET_COOKIE = 'basket_id';
|
||||
/** Basket lifetime — refreshed on every basket API call. */
|
||||
export const BASKET_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
/** How long a slot stays held once added to a basket / after a failed payment. */
|
||||
export const SLOT_HOLD_MS = 10 * 60 * 1000; // 10 min
|
||||
/** Hold extended to this once a payment is in progress, so the slot survives
|
||||
* the customer entering card details / retrying a declined card. */
|
||||
export const SLOT_CHECKOUT_HOLD_MS = 30 * 60 * 1000; // 30 min
|
||||
|
||||
function now() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
function iso(date: Date) {
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release any slots whose hold has expired, removing their basket lines
|
||||
* and flipping them back to `available`. Also marks expired active
|
||||
* baskets as `abandoned`. Runs lazily on basket reads / checkout.
|
||||
*
|
||||
* The expiry check is done in JS (parsing `heldUntil` as a UTC date) rather
|
||||
* than via a PocketBase date-string filter, so a slot is never released
|
||||
* *before* its hold genuinely lapses — regardless of how PocketBase stores /
|
||||
* compares the date field. A slot is held for the full SLOT_HOLD_MS (or
|
||||
* SLOT_CHECKOUT_HOLD_MS during payment).
|
||||
*/
|
||||
export async function sweepExpiredHolds(pb: PocketBase) {
|
||||
const nowMs = Date.now();
|
||||
|
||||
// 1. Release expired slot holds (and drop the lines holding them)
|
||||
const heldSlots = await pb
|
||||
.collection('slots')
|
||||
.getFullList({ filter: `status = 'held'` })
|
||||
.catch(() => []);
|
||||
for (const slot of heldSlots) {
|
||||
const heldUntilMs = slot.heldUntil ? Date.parse(slot.heldUntil) : NaN;
|
||||
// Still valid, or no parseable hold to judge by — leave it alone.
|
||||
if (Number.isNaN(heldUntilMs) || heldUntilMs > nowMs) continue;
|
||||
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `slot = "${slot.id}"` })
|
||||
.catch(() => []);
|
||||
for (const line of lines) {
|
||||
await pb.collection('basket_lines').delete(line.id).catch(() => {});
|
||||
}
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(slot.id, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
// 2. Abandon expired active baskets (their slot holds were already
|
||||
// covered by heldUntil above — same 10-min window < 24h basket TTL)
|
||||
const nowIso = iso(now());
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.getFullList({ filter: `status = 'active' && expiresAt < "${nowIso}"` })
|
||||
.then(async (expired) => {
|
||||
for (const basket of expired) {
|
||||
await pb.collection('baskets').update(basket.id, { status: 'abandoned' }).catch(() => {});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Map raw PB records (with expand) to our Basket type. */
|
||||
function mapBasket(record: Record<string, any>, lines: Record<string, any>[]): Basket {
|
||||
const mappedLines: BasketLine[] = lines.map((line) => {
|
||||
const item = line.expand?.item;
|
||||
const slot = line.expand?.slot;
|
||||
const media = item?.expand?.image;
|
||||
return {
|
||||
id: line.id,
|
||||
basket: line.basket,
|
||||
item: line.item,
|
||||
slot: line.slot || null,
|
||||
quantity: line.quantity,
|
||||
lineType: line.lineType,
|
||||
itemName: item?.name,
|
||||
itemPrice: item?.price,
|
||||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||
slotStart: slot?.start,
|
||||
slotEnd: slot?.end
|
||||
};
|
||||
});
|
||||
return {
|
||||
id: record.id,
|
||||
status: record.status,
|
||||
expiresAt: record.expiresAt,
|
||||
email: record.email || null,
|
||||
customerDetails: record.customerDetails || null,
|
||||
stripePaymentIntentId: record.stripePaymentIntentId || null,
|
||||
lines: mappedLines
|
||||
};
|
||||
}
|
||||
|
||||
/** Load a basket + its lines (with item/slot expand) by basket id. */
|
||||
export async function loadBasket(pb: PocketBase, basketId: string): Promise<Basket | null> {
|
||||
try {
|
||||
const record = await pb.collection('baskets').getOne(basketId);
|
||||
if (record.status !== 'active') return null;
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}"`, expand: 'item,slot,item.image' });
|
||||
return mapBasket(record, lines);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a fresh active basket. */
|
||||
export async function createBasket(pb: PocketBase): Promise<Basket> {
|
||||
const record = await pb.collection('baskets').create({
|
||||
status: 'active',
|
||||
expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS))
|
||||
});
|
||||
return {
|
||||
id: record.id,
|
||||
status: 'active',
|
||||
expiresAt: record.expiresAt,
|
||||
email: null,
|
||||
customerDetails: null,
|
||||
stripePaymentIntentId: null,
|
||||
lines: []
|
||||
};
|
||||
}
|
||||
|
||||
/** Touch the basket expiry (rolling TTL). */
|
||||
export async function touchBasket(pb: PocketBase, basketId: string) {
|
||||
await pb
|
||||
.collection('baskets')
|
||||
.update(basketId, { expiresAt: iso(new Date(Date.now() + BASKET_TTL_MS)) })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Release a slot hold for a basket line (slot back to available). */
|
||||
export async function releaseLineHold(pb: PocketBase, line: { slot?: string | null }) {
|
||||
if (!line.slot) return;
|
||||
await pb
|
||||
.collection('slots')
|
||||
.update(line.slot, { status: 'available', heldUntil: null })
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-reserve (extend) the hold on every slot line in a basket, as long as
|
||||
* the slot is still in `held` status. Used:
|
||||
* - at checkout start (create-intent) with SLOT_CHECKOUT_HOLD_MS, so a
|
||||
* service survives the customer entering card details / retrying a
|
||||
* declined card;
|
||||
* - after a failed payment (webhook) with SLOT_HOLD_MS, so the customer
|
||||
* can retry within a fresh 10-minute window.
|
||||
* The slot is genuinely still the customer's (nobody else could grab it
|
||||
* while `held`), so renewing is safe. Slots whose status is no longer
|
||||
* `held` (e.g. released and re-booked by someone else) are returned so the
|
||||
* caller can inform the user.
|
||||
*/
|
||||
export async function extendBasketHolds(
|
||||
pb: PocketBase,
|
||||
basketId: string,
|
||||
durationMs = SLOT_HOLD_MS
|
||||
): Promise<string[]> {
|
||||
const unheld: string[] = [];
|
||||
const lines = await pb
|
||||
.collection('basket_lines')
|
||||
.getFullList({ filter: `basket = "${basketId}" && lineType = "slot"` })
|
||||
.catch(() => []);
|
||||
const until = iso(new Date(Date.now() + durationMs));
|
||||
for (const line of lines) {
|
||||
const slotId = line.slot;
|
||||
if (!slotId) continue;
|
||||
const slot = await pb.collection('slots').getOne(slotId).catch(() => null);
|
||||
if (slot && slot.status === 'held') {
|
||||
await pb.collection('slots').update(slotId, { heldUntil: until }).catch(() => {});
|
||||
} else {
|
||||
unheld.push(line.id);
|
||||
}
|
||||
}
|
||||
return unheld;
|
||||
}
|
||||
export * from '$shared/server/basket';
|
||||
|
|
|
|||
|
|
@ -1,53 +1 @@
|
|||
import PocketBase, { ClientResponseError } from 'pocketbase';
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
let adminPb: PocketBase | null = null;
|
||||
let authPromise: Promise<PocketBase> | null = null;
|
||||
|
||||
async function authenticate(): Promise<PocketBase> {
|
||||
const url = env.POCKETBASE_INTERNAL_URL;
|
||||
const pb = new PocketBase(url);
|
||||
pb.autoCancellation(false);
|
||||
|
||||
const email = env.POCKETBASE_ADMIN_EMAIL;
|
||||
const password = env.POCKETBASE_ADMIN_PASSWORD;
|
||||
if (!email || !password) throw new Error('POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD must be set');
|
||||
|
||||
await pb.collection('_superusers').authWithPassword(email, password);
|
||||
adminPb = pb;
|
||||
return pb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-only PocketBase client authenticated as admin.
|
||||
* Used by basket/checkout/webhook API routes that need to bypass
|
||||
* collection-level API rules (create baskets, hold slots, create orders).
|
||||
*
|
||||
* Concurrent callers share one in-flight auth attempt; if the cached token
|
||||
* has since been invalidated (401 on first use), we re-authenticate once.
|
||||
*/
|
||||
export async function getAdminPb(): Promise<PocketBase> {
|
||||
if (adminPb?.authStore.isValid) return adminPb;
|
||||
authPromise ??= authenticate().finally(() => {
|
||||
authPromise = null;
|
||||
});
|
||||
return authPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `fn` with the admin client; on a 401 (stale/invalidated token),
|
||||
* re-authenticate and retry exactly once.
|
||||
*/
|
||||
export async function withAdminPb<T>(fn: (pb: PocketBase) => Promise<T>): Promise<T> {
|
||||
const pb = await getAdminPb();
|
||||
try {
|
||||
return await fn(pb);
|
||||
} catch (e) {
|
||||
if (e instanceof ClientResponseError && e.status === 401) {
|
||||
pb.authStore.clear();
|
||||
adminPb = null;
|
||||
return fn(await getAdminPb());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
export * from '$shared/server/pb-admin';
|
||||
|
|
|
|||
|
|
@ -1,15 +1 @@
|
|||
import { loadStripe as _loadStripe } from '@stripe/stripe-js';
|
||||
import { env } from '$env/dynamic/public';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
let stripePromise: ReturnType<typeof _loadStripe> | null = null;
|
||||
|
||||
export function loadStripe() {
|
||||
if (!browser) return null;
|
||||
if (!stripePromise) {
|
||||
const key = env.PUBLIC_STRIPE_PUBLISHABLE_KEY;
|
||||
if (!key) throw new Error('PUBLIC_STRIPE_PUBLISHABLE_KEY is not set');
|
||||
stripePromise = _loadStripe(key);
|
||||
}
|
||||
return stripePromise;
|
||||
}
|
||||
export * from '$shared/stripe-client';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
<script lang="ts">
|
||||
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
|
||||
import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
<script lang="ts">
|
||||
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
|
||||
import BlockRenderer from '$shared/blocks/BlockRenderer.svelte';
|
||||
let { data } = $props();
|
||||
</script>
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue