moved page rendering to a different service and access is now behind
admin.DOMAIN www.DOMAIN db.DOMAIN
This commit is contained in:
parent
c7f6b30b87
commit
1027da989e
126 changed files with 6356 additions and 1516 deletions
140
app-admin/src/app.css
Normal file
140
app-admin/src/app.css
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Playfair+Display:wght@600;700&display=swap');
|
||||
@import 'tailwindcss';
|
||||
@plugin 'daisyui' {
|
||||
themes: light --default;
|
||||
}
|
||||
|
||||
@theme {
|
||||
--font-sans: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
--font-serif: 'Playfair Display', Georgia, serif;
|
||||
--color-warm: var(--color-bg, #faf8f5);
|
||||
--color-charcoal: var(--color-heading, #2c2c2c);
|
||||
--color-sage: var(--color-primary, #8a9a7b);
|
||||
--color-sage-dark: color-mix(in srgb, var(--color-primary, #8a9a7b) 80%, #000);
|
||||
--color-terracotta: var(--color-accent, #c9825f);
|
||||
}
|
||||
|
||||
@keyframes shrink {
|
||||
from { scale: 0 1; }
|
||||
to { scale: 1 1; }
|
||||
}
|
||||
|
||||
.delete-fill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: transparent;
|
||||
transform-origin: left;
|
||||
}
|
||||
|
||||
.delete-fill.animating {
|
||||
animation: shrink 1s ease-in-out forwards;
|
||||
background: var(--error, #f43f5e);
|
||||
}
|
||||
|
||||
.btn.delete-holding {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.btn.delete-holding .text-error {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
:root {
|
||||
--fg-heading: var(--color-heading, #2c2c2c);
|
||||
--fg-subheading: var(--color-subheading, #4a4a4a);
|
||||
--fg-body: var(--color-text, #2c2c2c);
|
||||
background: var(--color-bg, #faf8f5);
|
||||
color: var(--fg-body);
|
||||
font-family: 'DM Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* ── Foreground colour utilities (set per-block via BackgroundWrapper) ── */
|
||||
.text-fg-body { color: var(--fg-body, #2c2c2c); }
|
||||
.text-fg-body\/85 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 85%, transparent); }
|
||||
.text-fg-body\/80 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 80%, transparent); }
|
||||
.text-fg-body\/75 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 75%, transparent); }
|
||||
.text-fg-body\/70 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 70%, transparent); }
|
||||
.text-fg-body\/60 { color: color-mix(in srgb, var(--fg-body, #2c2c2c) 60%, transparent); }
|
||||
.text-fg-heading { color: var(--fg-heading, #2c2c2c); }
|
||||
.text-fg-subheading { color: var(--fg-subheading, #4a4a4a); }
|
||||
.text-fg-subheading\/85 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 85%, transparent); }
|
||||
.text-fg-subheading\/80 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 80%, transparent); }
|
||||
.text-fg-subheading\/75 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 75%, transparent); }
|
||||
.text-fg-subheading\/70 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 70%, transparent); }
|
||||
.text-fg-subheading\/60 { color: color-mix(in srgb, var(--fg-subheading, #4a4a4a) 60%, transparent); }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
background:
|
||||
radial-gradient(circle at top left, rgba(var(--color-accent-rgb, 201, 130, 95), 0.1), transparent 36rem),
|
||||
var(--color-bg, #faf8f5);
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4 {
|
||||
font-family: 'Playfair Display', Georgia, serif;
|
||||
color: var(--fg-heading, #2c2c2c);
|
||||
}
|
||||
|
||||
.prose-wellness p {
|
||||
margin: 0.75rem 0;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.prose-wellness h2 {
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
font-size: clamp(2rem, 4vw, 3.25rem);
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.prose-wellness h3 {
|
||||
margin: 1rem 0 0.5rem;
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.prose-wellness ul {
|
||||
list-style: disc;
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
|
||||
.prose-wellness a {
|
||||
color: color-mix(in srgb, var(--color-primary, #8a9a7b) 90%, #000);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
/* ── Scroll-reveal animations ── */
|
||||
.reveal {
|
||||
opacity: 0;
|
||||
transform: translateY(30px);
|
||||
transition:
|
||||
opacity 0.7s cubic-bezier(0.25, 0.1, 0.25, 1),
|
||||
transform 0.7s cubic-bezier(0.25, 0.1, 0.25, 1);
|
||||
}
|
||||
|
||||
.reveal-visible {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
/* ── Hero fade-in stagger ── */
|
||||
.animate-fade-in {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
animation: fadeInUp 0.8s cubic-bezier(0.25, 0.1, 0.25, 1) forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeInUp {
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Smooth scroll ── */
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
18
app-admin/src/app.d.ts
vendored
Normal file
18
app-admin/src/app.d.ts
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
import type PocketBase from 'pocketbase';
|
||||
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
interface Locals {
|
||||
pb: PocketBase;
|
||||
user: import('pocketbase').AuthRecord | null;
|
||||
}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
12
app-admin/src/app.html
Normal file
12
app-admin/src/app.html
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="text-scale" content="scale" />
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
27
app-admin/src/hooks.server.ts
Normal file
27
app-admin/src/hooks.server.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { redirect, type Handle } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { createPocketBase } from '$lib/pb';
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
event.locals.pb = createPocketBase(
|
||||
event.request.headers.get('cookie') ?? '',
|
||||
env.POCKETBASE_INTERNAL_URL
|
||||
);
|
||||
event.locals.user = event.locals.pb.authStore.record;
|
||||
|
||||
const path = event.url.pathname;
|
||||
const isLoginRoute = path === '/login';
|
||||
const isAuthed = event.locals.pb.authStore.isValid;
|
||||
|
||||
if (!isLoginRoute && !isAuthed) {
|
||||
throw redirect(303, '/login');
|
||||
}
|
||||
|
||||
if (isLoginRoute && isAuthed) {
|
||||
throw redirect(303, '/pages');
|
||||
}
|
||||
|
||||
const response = await resolve(event);
|
||||
response.headers.append('set-cookie', event.locals.pb.authStore.exportToCookie({ sameSite: 'lax' }, 'pb_auth'));
|
||||
return response;
|
||||
};
|
||||
63
app-admin/src/lib/admin/BlockList.svelte
Normal file
63
app-admin/src/lib/admin/BlockList.svelte
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
<script lang="ts">
|
||||
import type { BlockType, ContentBlock } from '$lib/types';
|
||||
import { blockLabels } from '$lib/admin/blockDefaults';
|
||||
|
||||
let { blocks = [], selectedId = '', onSelect = (id: string) => {}, onDelete = (id: string) => {}, onMove = (from: number, to: number) => {} } = $props<{
|
||||
blocks: ContentBlock[];
|
||||
selectedId?: string;
|
||||
onSelect?: (id: string) => void;
|
||||
onDelete?: (id: string) => void;
|
||||
onMove?: (from: number, to: number) => void;
|
||||
}>();
|
||||
|
||||
let dragIndex = $state<number | null>(null);
|
||||
let holdingId = $state('');
|
||||
let holdTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function startHold(id: string) {
|
||||
holdingId = id;
|
||||
holdTimer = setTimeout(() => {
|
||||
const idx = blocks.findIndex((b: ContentBlock) => b.id === id);
|
||||
onDelete(id);
|
||||
onSelect(blocks[idx + 1]?.id || blocks[idx - 1]?.id || '');
|
||||
holdingId = '';
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function endHold() {
|
||||
if (holdTimer) clearTimeout(holdTimer);
|
||||
holdingId = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-3">
|
||||
{#each blocks as block, i (block.id)}
|
||||
<div
|
||||
role="listitem"
|
||||
class="rounded-box border bg-base-100 p-3 shadow-sm cursor-pointer"
|
||||
class:border-primary={selectedId === block.id}
|
||||
draggable="true"
|
||||
onclick={() => onSelect(block.id)}
|
||||
ondragstart={() => (dragIndex = i)}
|
||||
ondragover={(e) => e.preventDefault()}
|
||||
ondrop={() => { if (dragIndex !== null && dragIndex !== i) onMove(dragIndex, i); dragIndex = null; }}
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="cursor-grab text-xl text-base-content/40">☰</span>
|
||||
<div class="flex-1 font-semibold">{blockLabels[block.type as BlockType]}</div>
|
||||
<button
|
||||
class="btn btn-xs btn-error btn-outline relative overflow-hidden"
|
||||
class:btn-disabled={holdingId && holdingId !== block.id}
|
||||
class:delete-holding={holdingId === block.id}
|
||||
type="button"
|
||||
onpointerdown={() => startHold(block.id)}
|
||||
onpointerup={endHold}
|
||||
onpointerleave={endHold}
|
||||
>
|
||||
<span class="delete-fill" class:animating={holdingId === block.id}></span>
|
||||
<span class="relative z-10 text-error">Delete</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
86
app-admin/src/lib/admin/blockDefaults.ts
Normal file
86
app-admin/src/lib/admin/blockDefaults.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import { v4 as uuid } from 'uuid';
|
||||
import type { BlockType, ContentBlock } from '$lib/types';
|
||||
|
||||
export const blockLabels: Record<BlockType, string> = {
|
||||
text: 'Text',
|
||||
image_text: 'Image + Text',
|
||||
timeline: 'Timeline',
|
||||
hero: 'Hero',
|
||||
button: 'Button',
|
||||
spacer: 'Spacer',
|
||||
testimonials: 'Testimonials',
|
||||
upcoming_calendar: 'Upcoming Calendar',
|
||||
shop: 'Shop',
|
||||
checkout: 'Checkout'
|
||||
};
|
||||
|
||||
export const blockTypes = Object.keys(blockLabels) as BlockType[];
|
||||
|
||||
export function createBlock(type: BlockType): ContentBlock {
|
||||
const base = { id: uuid(), type, data: {} as Record<string, any> };
|
||||
switch (type) {
|
||||
case 'text':
|
||||
base.data = { content: '<h2>New text block</h2><p>Add your copy here.</p>' };
|
||||
break;
|
||||
case 'image_text':
|
||||
base.data = { url: '', alt: '', content: '<h2>Image and text</h2><p>Add content here.</p>', imagePosition: 'left' };
|
||||
break;
|
||||
case 'timeline':
|
||||
base.data = { items: [{ title: 'Milestone', description: 'Describe this moment.' }] };
|
||||
break;
|
||||
case 'hero':
|
||||
base.data = {
|
||||
heading: 'Holistic and Experiential Learning about Happiness',
|
||||
subheading: 'Individual sessions, workshops and events in Oslo',
|
||||
buttonLabel: 'BOOK NOW',
|
||||
buttonUrl: '/book'
|
||||
};
|
||||
break;
|
||||
case 'button':
|
||||
base.data = {
|
||||
label: 'Learn More',
|
||||
href: '/',
|
||||
variant: 'primary',
|
||||
size: 'md',
|
||||
alignment: 'center'
|
||||
};
|
||||
break;
|
||||
case 'spacer':
|
||||
base.data = { height: 64 };
|
||||
break;
|
||||
case 'testimonials':
|
||||
base.data = {
|
||||
title: 'What They Say About Me',
|
||||
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' }
|
||||
]
|
||||
};
|
||||
break;
|
||||
case 'upcoming_calendar':
|
||||
base.data = {
|
||||
title: 'Upcoming Events',
|
||||
categories: []
|
||||
};
|
||||
break;
|
||||
case 'shop':
|
||||
base.data = {
|
||||
title: 'Our Services',
|
||||
itemTypeFilter: 'all',
|
||||
itemIds: [],
|
||||
layout: 'grid'
|
||||
};
|
||||
break;
|
||||
case 'checkout':
|
||||
base.data = {
|
||||
title: 'Checkout',
|
||||
heading: 'Complete your booking',
|
||||
notesLabel: 'Notes or special requests'
|
||||
};
|
||||
break;
|
||||
}
|
||||
base.data._background = { type: 'none', color: '', attachment: 'scroll', overlay: false, overlayOpacity: 40 };
|
||||
return base;
|
||||
}
|
||||
301
app-admin/src/lib/admin/editors/BlockEditor.svelte
Normal file
301
app-admin/src/lib/admin/editors/BlockEditor.svelte
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
<script lang="ts">
|
||||
import type { BlockType, ContentBlock } from '$lib/types';
|
||||
import { blockLabels } from '$lib/admin/blockDefaults';
|
||||
import RichTextEditor from './RichTextEditor.svelte';
|
||||
import ImageUploader from './ImageUploader.svelte';
|
||||
import SegmentedControl from './SegmentedControl.svelte';
|
||||
import ShopBlockEditor from './ShopBlockEditor.svelte';
|
||||
import CheckoutBlockEditor from './CheckoutBlockEditor.svelte';
|
||||
|
||||
let { block, eventCategories = [], items = [], onChange = (block: ContentBlock) => {} } = $props<{
|
||||
block: ContentBlock | null;
|
||||
eventCategories?: string[];
|
||||
items?: { id: string; name: string; type: string }[];
|
||||
onChange?: (block: ContentBlock) => void;
|
||||
}>();
|
||||
|
||||
function updateData(patch: Record<string, any>) {
|
||||
if (!block) return;
|
||||
block = { ...block, data: { ...block.data, ...patch } };
|
||||
onChange(block);
|
||||
}
|
||||
|
||||
function updateArray(key: string, index: number, patch: Record<string, any>) {
|
||||
if (!block) return;
|
||||
const items = [...(block.data[key] || [])];
|
||||
items[index] = { ...items[index], ...patch };
|
||||
updateData({ [key]: items });
|
||||
}
|
||||
|
||||
function addArrayItem(key: string, item: Record<string, any>) {
|
||||
if (!block) return;
|
||||
updateData({ [key]: [...(block.data[key] || []), item] });
|
||||
}
|
||||
|
||||
function removeArrayItem(key: string, index: number) {
|
||||
if (!block) return;
|
||||
updateData({ [key]: (block.data[key] || []).filter((_: unknown, i: number) => i !== index) });
|
||||
}
|
||||
|
||||
function toggleCategory(category: string) {
|
||||
if (!block) return;
|
||||
const categories = block.data.categories || [];
|
||||
updateData({
|
||||
categories: categories.includes(category)
|
||||
? categories.filter((item: string) => item !== category)
|
||||
: [...categories, category]
|
||||
});
|
||||
}
|
||||
|
||||
function titleCase(value: string | number) {
|
||||
const text = String(value);
|
||||
return text.charAt(0).toUpperCase() + text.slice(1);
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if !block}
|
||||
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">Select a block to edit.</div>
|
||||
{:else}
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<h2 class="mb-4 text-2xl font-bold">{blockLabels[block.type as BlockType]}</h2>
|
||||
|
||||
{#if block.type === 'text'}
|
||||
<RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} />
|
||||
{:else if block.type === 'image_text'}
|
||||
<ImageUploader url={block.data.url} alt={block.data.alt} onChange={(image) => updateData(image)} />
|
||||
<div class="form-control mt-3">
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<span class="label-text">Image position</span>
|
||||
<input type="checkbox" class="toggle toggle-primary" checked={block.data.imagePosition === 'right'} onchange={(e) => updateData({ imagePosition: e.currentTarget.checked ? 'right' : 'left' })} />
|
||||
<span class="text-sm text-base-content/60">{block.data.imagePosition === 'right' ? 'Right' : 'Left'}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="mt-3"><RichTextEditor value={block.data.content} onChange={(content) => updateData({ content })} /></div>
|
||||
{:else if block.type === 'timeline'}
|
||||
{#each block.data.items || [] as item, i}
|
||||
<div class="rounded-box mb-3 border border-base-300 p-3">
|
||||
<input class="input input-bordered mb-2 w-full" placeholder="Title" value={item.title} oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })} />
|
||||
<textarea class="textarea textarea-bordered w-full" placeholder="Description" value={item.description} oninput={(e) => updateArray('items', i, { description: e.currentTarget.value })}></textarea>
|
||||
<button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn" type="button" onclick={() => addArrayItem('items', { title: '', description: '' })}>Add item</button>
|
||||
{:else if block.type === 'hero'}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Heading</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full mt-3">
|
||||
<div class="label"><span class="label-text">Subheading</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.subheading || ''} oninput={(e) => updateData({ subheading: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full mt-3">
|
||||
<div class="label"><span class="label-text">Button label</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.buttonLabel || ''} oninput={(e) => updateData({ buttonLabel: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full mt-3">
|
||||
<div class="label"><span class="label-text">Button URL</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.buttonUrl || ''} oninput={(e) => updateData({ buttonUrl: e.currentTarget.value })} />
|
||||
</label>
|
||||
{:else if block.type === 'button'}
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Button label</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.label || ''} oninput={(e) => updateData({ label: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">URL</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.href || ''} oninput={(e) => updateData({ href: e.currentTarget.value })} />
|
||||
</label>
|
||||
<div class="form-control mt-5">
|
||||
<SegmentedControl
|
||||
label="Variant"
|
||||
options={['primary', 'secondary']}
|
||||
value={block.data.variant || 'primary'}
|
||||
onChange={(v) => updateData({ variant: v })}
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<SegmentedControl
|
||||
label="Alignment"
|
||||
options={['left', 'center', 'right']}
|
||||
value={block.data.alignment || 'left'}
|
||||
onChange={(v) => updateData({ alignment: v })}
|
||||
formatLabel={titleCase}
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<SegmentedControl
|
||||
label="Size"
|
||||
options={['xs', 'sm', 'md', 'lg']}
|
||||
value={block.data.size || 'md'}
|
||||
onChange={(v) => updateData({ size: v })}
|
||||
formatLabel={(v) => String({ xs: 'Extra Small', sm: 'Small', md: 'Medium', lg: 'Large' }[String(v)] || v)}
|
||||
/>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="label-text w-24">Color</span>
|
||||
<div class="flex flex-1 items-center gap-2">
|
||||
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data.color || 'var(--color-primary)'} oninput={(e) => updateData({ color: e.currentTarget.value })} />
|
||||
<input class="input input-bordered flex-1" placeholder="Leave empty to use global primary" value={block.data.color || ''} oninput={(e) => updateData({ color: e.currentTarget.value })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if block.type === 'spacer'}
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Height (px)</span></div>
|
||||
<input type="number" class="input input-bordered w-full" value={block.data.height || 64} oninput={(e) => updateData({ height: parseInt(e.currentTarget.value) || 64 })} />
|
||||
</label>
|
||||
</div>
|
||||
{:else if block.type === 'testimonials'}
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Section Title</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
|
||||
</label>
|
||||
|
||||
{#each block.data.items || [] as item, i}
|
||||
<div class="rounded-box mb-3 border border-base-300 p-4">
|
||||
<textarea
|
||||
class="textarea textarea-bordered w-full mb-2"
|
||||
placeholder="Testimonial text"
|
||||
rows="3"
|
||||
value={item.text}
|
||||
oninput={(e) => updateArray('items', i, { text: e.currentTarget.value })}
|
||||
></textarea>
|
||||
<input
|
||||
class="input input-bordered w-full"
|
||||
placeholder="Author name"
|
||||
value={item.title}
|
||||
oninput={(e) => updateArray('items', i, { title: e.currentTarget.value })}
|
||||
/>
|
||||
<button class="btn btn-error btn-sm mt-2" type="button" onclick={() => removeArrayItem('items', i)}>Remove</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn" type="button" onclick={() => addArrayItem('items', { text: '', title: '' })}>Add testimonial</button>
|
||||
</div>
|
||||
{:else if block.type === 'upcoming_calendar'}
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Section title</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
|
||||
</label>
|
||||
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<div class="mb-3">
|
||||
<h3 class="font-semibold">Category filters</h3>
|
||||
<p class="text-sm text-base-content/60">Choose categories to show in this block. Leave all unchecked to show every published event.</p>
|
||||
</div>
|
||||
{#if eventCategories?.length}
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each eventCategories as category}
|
||||
<label class="btn btn-sm" class:btn-primary={(block.data.categories || []).includes(category)}>
|
||||
<input class="hidden" type="checkbox" checked={(block.data.categories || []).includes(category)} onchange={() => toggleCategory(category)} />
|
||||
{category}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-sm text-base-content/60">No event categories exist yet. Create events in the Calendar admin page first.</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{:else if block.type === 'shop'}
|
||||
<ShopBlockEditor {block} {items} {onChange} />
|
||||
{:else if block.type === 'checkout'}
|
||||
<CheckoutBlockEditor {block} {onChange} />
|
||||
{/if}
|
||||
|
||||
<div class="rounded-box border border-base-300 p-4 mt-4">
|
||||
|
||||
<!-- Background Type Selector -->
|
||||
<div class="mb-4">
|
||||
<SegmentedControl
|
||||
label="Background"
|
||||
labelStyle="font-weight: 1000;"
|
||||
options={['none', 'color', 'image']}
|
||||
value={block.data._background?.type || 'none'}
|
||||
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), type: v } })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if block.data._background?.type === 'color'}
|
||||
<div class="space-y-3">
|
||||
<label class="form-control">
|
||||
<span class="label-text text-sm">Color</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<input class="input input-bordered w-12 h-10 p-1 cursor-pointer" type="color" value={block.data._background?.color || '#66755d'} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
|
||||
<input class="input input-bordered flex-1" placeholder="#66755d or sage" value={block.data._background?.color || ''} oninput={(e) => updateData({ _background: { ...(block.data._background || {}), color: e.currentTarget.value } })} />
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if block.data._background?.type === 'image'}
|
||||
<div class="space-y-4">
|
||||
<ImageUploader url={block.data._background?.imageUrl || ''} alt={block.data._background?.imageAlt || ''} onChange={(image) => updateData({ _background: { ...(block.data._background || {}), imageUrl: image.url, imageAlt: image.alt } })} />
|
||||
|
||||
<SegmentedControl
|
||||
label="Attachment"
|
||||
options={['scroll', 'fixed']}
|
||||
value={block.data._background?.attachment || 'scroll'}
|
||||
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), attachment: v } })}
|
||||
/>
|
||||
|
||||
<SegmentedControl
|
||||
label="Overlay"
|
||||
options={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]}
|
||||
value={block.data._background?.overlayOpacity ?? 0}
|
||||
onChange={(v) => updateData({ _background: { ...(block.data._background || {}), overlay: true, overlayOpacity: v } })}
|
||||
formatLabel={(v) => `${v}%`}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<hr class="border-base-content/10 my-4" />
|
||||
|
||||
<SegmentedControl
|
||||
label="Foreground"
|
||||
labelStyle="font-weight: 1000;"
|
||||
options={['default', 'custom']}
|
||||
value={block.data._foreground?.mode || 'default'}
|
||||
onChange={(v) => updateData({ _foreground: { ...(block.data._foreground || {}), mode: v } })}
|
||||
/>
|
||||
|
||||
{#if block.data._foreground?.mode === 'custom'}
|
||||
<div class="mt-4 space-y-3">
|
||||
<div class="form-control">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="label-text w-24">Heading</span>
|
||||
<div class="flex flex-1 items-center gap-2">
|
||||
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.headingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
|
||||
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.headingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), headingColor: e.currentTarget.value } })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="label-text w-24">Sub heading</span>
|
||||
<div class="flex flex-1 items-center gap-2">
|
||||
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.subheadingColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
|
||||
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.subheadingColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), subheadingColor: e.currentTarget.value } })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-control">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="label-text w-24">Text</span>
|
||||
<div class="flex flex-1 items-center gap-2">
|
||||
<input class="input input-bordered w-10 h-10 p-1 cursor-pointer" type="color" value={block.data._foreground?.textColor || '#2c2c2c'} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
|
||||
<input class="input input-bordered flex-1" placeholder="#2c2c2c" value={block.data._foreground?.textColor || ''} oninput={(e) => updateData({ _foreground: { ...(block.data._foreground || {}), textColor: e.currentTarget.value } })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
31
app-admin/src/lib/admin/editors/CheckoutBlockEditor.svelte
Normal file
31
app-admin/src/lib/admin/editors/CheckoutBlockEditor.svelte
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<script lang="ts">
|
||||
import type { ContentBlock, CheckoutBlockData } from '$lib/types';
|
||||
|
||||
let {
|
||||
block,
|
||||
onChange = (b: ContentBlock) => {}
|
||||
} = $props<{
|
||||
block: ContentBlock;
|
||||
onChange?: (b: ContentBlock) => void;
|
||||
}>();
|
||||
|
||||
function updateData(patch: Partial<CheckoutBlockData>) {
|
||||
onChange({ ...block, data: { ...block.data, ...patch } });
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Title</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Heading</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.heading || ''} oninput={(e) => updateData({ heading: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Notes label</span></div>
|
||||
<input class="input input-bordered w-full" placeholder="Notes or special requests" value={block.data.notesLabel || ''} oninput={(e) => updateData({ notesLabel: e.currentTarget.value })} />
|
||||
</label>
|
||||
<p class="text-sm text-base-content/60">Customer fields (name, email, phone, notes) and the payment flow are fixed and cannot be changed here.</p>
|
||||
</div>
|
||||
105
app-admin/src/lib/admin/editors/ImageUploader.svelte
Normal file
105
app-admin/src/lib/admin/editors/ImageUploader.svelte
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script lang="ts">
|
||||
import { uploadMedia } from '$lib/pb';
|
||||
|
||||
let { url: urlProp = '', alt: altProp = '', onChange = (value: { url: string; alt: string }) => {} } = $props<{
|
||||
url?: string;
|
||||
alt?: string;
|
||||
onChange?: (value: { url: string; alt: string }) => void;
|
||||
}>();
|
||||
|
||||
let uploading = $state(false);
|
||||
let error = $state('');
|
||||
let fileInput = $state<HTMLInputElement>();
|
||||
|
||||
// Local state synced from props so reactivity works reliably in Svelte 5
|
||||
let localUrl = $state(urlProp);
|
||||
let localAlt = $state(altProp);
|
||||
|
||||
$effect(() => { localUrl = urlProp; });
|
||||
$effect(() => { localAlt = altProp; });
|
||||
|
||||
function emitChange() {
|
||||
onChange({ url: localUrl, alt: localAlt });
|
||||
}
|
||||
|
||||
async function handleFile(event: Event) {
|
||||
const file = (event.currentTarget as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
uploading = true;
|
||||
error = '';
|
||||
try {
|
||||
const result = await uploadMedia(file);
|
||||
localUrl = result.url;
|
||||
emitChange();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : 'Upload failed';
|
||||
console.error('Image upload error:', e);
|
||||
} finally {
|
||||
uploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeImage() {
|
||||
localUrl = '';
|
||||
localAlt = '';
|
||||
emitChange();
|
||||
if (fileInput) fileInput.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="grid grid-cols-[1fr_1.5fr] gap-4">
|
||||
<!-- Drop zone / upload area -->
|
||||
<div
|
||||
class="flex h-32 cursor-pointer flex-col items-center justify-center rounded-box border-2 border-dashed p-3 transition-colors hover:border-primary {localUrl ? 'border-success/40' : 'border-base-300'}"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
onclick={() => fileInput?.click()}
|
||||
onkeydown={(e) => e.key === 'Enter' && fileInput?.click()}
|
||||
>
|
||||
{#if uploading}
|
||||
<span class="loading loading-spinner loading-lg text-primary"></span>
|
||||
<p class="mt-3 text-sm text-base-content/60">Uploading…</p>
|
||||
{:else if localUrl}
|
||||
<div class="relative w-full">
|
||||
<img class="max-h-28 w-full rounded-box object-cover shadow" src={localUrl} alt={localAlt} />
|
||||
<button
|
||||
class="btn btn-circle btn-error btn-outline btn-xs absolute right-1 top-1"
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); removeImage(); }}
|
||||
title="Remove image"
|
||||
>✕</button>
|
||||
</div>
|
||||
{:else}
|
||||
<svg class="mb-2 size-8 text-base-content/40" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
|
||||
</svg>
|
||||
<p class="text-center text-sm font-medium text-base-content/70">Upload image</p>
|
||||
<p class="text-xs text-base-content/40">PNG, JPG, WebP</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<div class="alert alert-error col-span-full text-sm">{error}</div>
|
||||
{/if}
|
||||
|
||||
<input
|
||||
class="hidden"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onchange={handleFile}
|
||||
disabled={uploading}
|
||||
bind:this={fileInput}
|
||||
/>
|
||||
|
||||
<!-- URL & Alt fields -->
|
||||
<div class="space-y-3">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Image URL</span></div>
|
||||
<input class="input input-bordered w-full" bind:value={localUrl} oninput={() => emitChange()} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Alt text</span></div>
|
||||
<input class="input input-bordered w-full" bind:value={localAlt} oninput={() => emitChange()} />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
78
app-admin/src/lib/admin/editors/RichTextEditor.svelte
Normal file
78
app-admin/src/lib/admin/editors/RichTextEditor.svelte
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
<script lang="ts">
|
||||
import { browser } from '$app/environment';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let { value = '', onChange = (html: string) => {} } = $props<{ value?: string; onChange?: (html: string) => void }>();
|
||||
let editorEl: HTMLDivElement | undefined = $state();
|
||||
let mounted = $state(false);
|
||||
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
if (editorEl) {
|
||||
editorEl.innerHTML = value || '';
|
||||
}
|
||||
});
|
||||
|
||||
// Sync content from props when a different block is selected,
|
||||
// without overwriting content while the user is actively editing.
|
||||
$effect(() => {
|
||||
if (mounted && editorEl && value !== undefined) {
|
||||
if (editorEl.innerHTML !== value) {
|
||||
editorEl.innerHTML = value || '';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function exec(cmd: string, val?: string) {
|
||||
if (!browser) return;
|
||||
editorEl?.focus();
|
||||
document.execCommand(cmd, false, val);
|
||||
emit();
|
||||
}
|
||||
|
||||
function emit() {
|
||||
if (editorEl) onChange(editorEl.innerHTML);
|
||||
}
|
||||
|
||||
function setLink() {
|
||||
const url = prompt('Link URL', 'https://');
|
||||
if (url) exec('createLink', url);
|
||||
}
|
||||
|
||||
function clearFormatting() {
|
||||
if (!browser) return;
|
||||
editorEl?.focus();
|
||||
document.execCommand('formatBlock', false, '<p>');
|
||||
document.execCommand('removeFormat');
|
||||
emit();
|
||||
}
|
||||
|
||||
function handleInput() {
|
||||
emit();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if mounted}
|
||||
<div class="rounded-box border border-base-300 bg-base-100">
|
||||
<div class="flex flex-wrap gap-2 border-b border-base-300 p-2">
|
||||
<button class="btn btn-xs" onclick={() => exec('bold')} type="button"><b>B</b></button>
|
||||
<button class="btn btn-xs" onclick={() => exec('italic')} type="button"><i>I</i></button>
|
||||
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h2>')} type="button">H2</button>
|
||||
<button class="btn btn-xs" onclick={() => exec('formatBlock', '<h3>')} type="button">H3</button>
|
||||
<button class="btn btn-xs" onclick={() => exec('insertUnorderedList')} type="button">List</button>
|
||||
<button class="btn btn-xs" onclick={setLink} type="button">Link</button>
|
||||
<button class="btn btn-xs" onclick={clearFormatting} type="button">Clear</button>
|
||||
</div>
|
||||
<div
|
||||
bind:this={editorEl}
|
||||
contenteditable
|
||||
role="textbox"
|
||||
aria-multiline="true"
|
||||
class="min-h-40 p-4 outline-none"
|
||||
oninput={handleInput}
|
||||
onkeydown={(e) => { if (e.key === 'Tab') { e.preventDefault(); exec('insertHTML', ' '); } }}
|
||||
></div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="rounded-box border border-base-300 bg-base-100 p-4 text-base-content/50">Loading editor…</div>
|
||||
{/if}
|
||||
38
app-admin/src/lib/admin/editors/SegmentedControl.svelte
Normal file
38
app-admin/src/lib/admin/editors/SegmentedControl.svelte
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<script lang="ts">
|
||||
let {
|
||||
label,
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
formatLabel = (v: string | number) => String(v),
|
||||
labelStyle = '',
|
||||
class: className = ''
|
||||
}: {
|
||||
label?: string;
|
||||
options: (string | number)[];
|
||||
value: string | number;
|
||||
onChange: (value: string | number) => void;
|
||||
formatLabel?: (value: string | number) => string;
|
||||
labelStyle?: string;
|
||||
class?: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div class="form-control {className}">
|
||||
<div class="flex items-center justify-between">
|
||||
{#if label}
|
||||
<span class="label-text w-24" style={labelStyle}>{label}</span>
|
||||
{/if}
|
||||
<div class="grid flex-1" style="grid-template-columns: repeat({options.length}, 1fr)">
|
||||
{#each options as option, i}
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm {i === 0 ? 'rounded-r-none' : ''} {i === options.length - 1 ? 'rounded-l-none' : ''} {value === option ? 'btn-active' : ''}"
|
||||
onclick={() => onChange(option)}
|
||||
>
|
||||
{formatLabel(option)}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
79
app-admin/src/lib/admin/editors/ShopBlockEditor.svelte
Normal file
79
app-admin/src/lib/admin/editors/ShopBlockEditor.svelte
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
<script lang="ts">
|
||||
import type { ContentBlock, ShopBlockData } from '$lib/types';
|
||||
import SegmentedControl from './SegmentedControl.svelte';
|
||||
|
||||
let {
|
||||
block,
|
||||
items = [],
|
||||
onChange = (b: ContentBlock) => {}
|
||||
} = $props<{
|
||||
block: ContentBlock;
|
||||
items?: { id: string; name: string; type: string }[];
|
||||
onChange?: (b: ContentBlock) => void;
|
||||
}>();
|
||||
|
||||
function updateData(patch: Partial<ShopBlockData>) {
|
||||
onChange({ ...block, data: { ...block.data, ...patch } });
|
||||
}
|
||||
|
||||
function toggleItem(id: string) {
|
||||
const current: string[] = block.data.itemIds || [];
|
||||
updateData({
|
||||
itemIds: current.includes(id)
|
||||
? current.filter((itemId) => itemId !== id)
|
||||
: [...current, id]
|
||||
});
|
||||
}
|
||||
|
||||
const typeFilterLabels: Record<string, string> = {
|
||||
all: 'All',
|
||||
item: 'Products',
|
||||
item_with_time: 'Services'
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Title</span></div>
|
||||
<input class="input input-bordered w-full" value={block.data.title || ''} oninput={(e) => updateData({ title: e.currentTarget.value })} />
|
||||
</label>
|
||||
|
||||
<SegmentedControl
|
||||
label="Layout"
|
||||
options={['grid', 'list']}
|
||||
value={block.data.layout || 'grid'}
|
||||
onChange={(v) => updateData({ layout: v as 'grid' | 'list' })}
|
||||
formatLabel={(v) => String(v).charAt(0).toUpperCase() + String(v).slice(1)}
|
||||
/>
|
||||
|
||||
<SegmentedControl
|
||||
label="Item type"
|
||||
options={['all', 'item', 'item_with_time']}
|
||||
value={block.data.itemTypeFilter || 'all'}
|
||||
onChange={(v) => updateData({ itemTypeFilter: v as ShopBlockData['itemTypeFilter'] })}
|
||||
formatLabel={(v) => typeFilterLabels[String(v)] || String(v)}
|
||||
/>
|
||||
|
||||
{#if items.length}
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<div class="mb-3">
|
||||
<h3 class="font-semibold">Items</h3>
|
||||
<p class="text-sm text-base-content/60">Leave empty to show all items of the selected type.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
{#each items as item}
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-xs"
|
||||
class:btn-primary={(block.data.itemIds || []).includes(item.id)}
|
||||
onclick={() => toggleItem(item.id)}
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="text-sm text-base-content/60">No items yet — create some under Items in the admin.</p>
|
||||
{/if}
|
||||
</div>
|
||||
1
app-admin/src/lib/assets/favicon.svg
Normal file
1
app-admin/src/lib/assets/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="107" height="128" viewBox="0 0 107 128"><title>svelte-logo</title><path d="M94.157 22.819c-10.4-14.885-30.94-19.297-45.792-9.835L22.282 29.608A29.92 29.92 0 0 0 8.764 49.65a31.5 31.5 0 0 0 3.108 20.231 30 30 0 0 0-4.477 11.183 31.9 31.9 0 0 0 5.448 24.116c10.402 14.887 30.942 19.297 45.791 9.835l26.083-16.624A29.92 29.92 0 0 0 98.235 78.35a31.53 31.53 0 0 0-3.105-20.232 30 30 0 0 0 4.474-11.182 31.88 31.88 0 0 0-5.447-24.116" style="fill:#ff3e00"/><path d="M45.817 106.582a20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.503 18 18 0 0 1 .624-2.435l.49-1.498 1.337.981a33.6 33.6 0 0 0 10.203 5.098l.97.294-.09.968a5.85 5.85 0 0 0 1.052 3.878 6.24 6.24 0 0 0 6.695 2.485 5.8 5.8 0 0 0 1.603-.704L69.27 76.28a5.43 5.43 0 0 0 2.45-3.631 5.8 5.8 0 0 0-.987-4.371 6.24 6.24 0 0 0-6.698-2.487 5.7 5.7 0 0 0-1.6.704l-9.953 6.345a19 19 0 0 1-5.296 2.326 20.72 20.72 0 0 1-22.237-8.243 19.17 19.17 0 0 1-3.277-14.502 17.99 17.99 0 0 1 8.13-12.052l26.081-16.623a19 19 0 0 1 5.3-2.329 20.72 20.72 0 0 1 22.237 8.243 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-.624 2.435l-.49 1.498-1.337-.98a33.6 33.6 0 0 0-10.203-5.1l-.97-.294.09-.968a5.86 5.86 0 0 0-1.052-3.878 6.24 6.24 0 0 0-6.696-2.485 5.8 5.8 0 0 0-1.602.704L37.73 51.72a5.42 5.42 0 0 0-2.449 3.63 5.79 5.79 0 0 0 .986 4.372 6.24 6.24 0 0 0 6.698 2.486 5.8 5.8 0 0 0 1.602-.704l9.952-6.342a19 19 0 0 1 5.295-2.328 20.72 20.72 0 0 1 22.237 8.242 19.17 19.17 0 0 1 3.277 14.503 18 18 0 0 1-8.13 12.053l-26.081 16.622a19 19 0 0 1-5.3 2.328" style="fill:#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
94
app-admin/src/lib/basket.svelte.ts
Normal file
94
app-admin/src/lib/basket.svelte.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
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;
|
||||
}
|
||||
54
app-admin/src/lib/blocks/BackgroundWrapper.svelte
Normal file
54
app-admin/src/lib/blocks/BackgroundWrapper.svelte
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
<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>
|
||||
55
app-admin/src/lib/blocks/BlockRenderer.svelte
Normal file
55
app-admin/src/lib/blocks/BlockRenderer.svelte
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<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}
|
||||
26
app-admin/src/lib/blocks/ButtonBlock.svelte
Normal file
26
app-admin/src/lib/blocks/ButtonBlock.svelte
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<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>
|
||||
402
app-admin/src/lib/blocks/CheckoutBlock.svelte
Normal file
402
app-admin/src/lib/blocks/CheckoutBlock.svelte
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
<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>
|
||||
30
app-admin/src/lib/blocks/HeroBlock.svelte
Normal file
30
app-admin/src/lib/blocks/HeroBlock.svelte
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
<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>
|
||||
22
app-admin/src/lib/blocks/ImageTextBlock.svelte
Normal file
22
app-admin/src/lib/blocks/ImageTextBlock.svelte
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
<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>
|
||||
313
app-admin/src/lib/blocks/ShopBlock.svelte
Normal file
313
app-admin/src/lib/blocks/ShopBlock.svelte
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
<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>
|
||||
7
app-admin/src/lib/blocks/SpacerBlock.svelte
Normal file
7
app-admin/src/lib/blocks/SpacerBlock.svelte
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
<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>
|
||||
87
app-admin/src/lib/blocks/TestimonialsBlock.svelte
Normal file
87
app-admin/src/lib/blocks/TestimonialsBlock.svelte
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
<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>
|
||||
11
app-admin/src/lib/blocks/TextBlock.svelte
Normal file
11
app-admin/src/lib/blocks/TextBlock.svelte
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<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>
|
||||
31
app-admin/src/lib/blocks/TimelineBlock.svelte
Normal file
31
app-admin/src/lib/blocks/TimelineBlock.svelte
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<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>
|
||||
125
app-admin/src/lib/blocks/UpcomingCalendarBlock.svelte
Normal file
125
app-admin/src/lib/blocks/UpcomingCalendarBlock.svelte
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
<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
app-admin/src/lib/calendar.ts
Normal file
1
app-admin/src/lib/calendar.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/calendar';
|
||||
139
app-admin/src/lib/exportImport.ts
Normal file
139
app-admin/src/lib/exportImport.ts
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
|
||||
|
||||
/**
|
||||
* The portable export format.
|
||||
* Images are stored as base64 data-URIs so the file is fully self-contained.
|
||||
*/
|
||||
export type SiteExport = {
|
||||
version: 1;
|
||||
exportedAt: string;
|
||||
pages: {
|
||||
slug: string;
|
||||
title: string;
|
||||
blocks: ContentBlock[];
|
||||
published: boolean;
|
||||
}[];
|
||||
globals: {
|
||||
key: string;
|
||||
data: Record<string, unknown>;
|
||||
}[];
|
||||
events?: Omit<CalendarEventRecord, 'id'>[];
|
||||
/** Maps original PocketBase file URLs → base64 data-URI */
|
||||
images: Record<string, string>;
|
||||
};
|
||||
|
||||
/** Regex to match PocketBase file URLs */
|
||||
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
|
||||
|
||||
/**
|
||||
* Extract all PocketBase image URLs from a value (recursive).
|
||||
*/
|
||||
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
|
||||
if (typeof value === 'string') {
|
||||
let match: RegExpExecArray | null;
|
||||
const re = new RegExp(PB_FILE_RE.source, 'g');
|
||||
while ((match = re.exec(value)) !== null) {
|
||||
urls.add(match[0]);
|
||||
}
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const item of value) extractImageUrls(item, urls);
|
||||
} else if (value && typeof value === 'object') {
|
||||
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace all PocketBase URLs in a value with a placeholder key.
|
||||
*/
|
||||
export function replaceUrlsWithKeys(
|
||||
value: unknown,
|
||||
urlToKey: Map<string, string>
|
||||
): unknown {
|
||||
if (typeof value === 'string') {
|
||||
let result = value;
|
||||
for (const [url, key] of urlToKey) {
|
||||
result = result.replace(url, `__IMG__${key}__`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const obj: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
obj[k] = replaceUrlsWithKeys(v, urlToKey);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore image placeholders back to real URLs after import.
|
||||
*/
|
||||
export function restorePlaceholders(
|
||||
value: unknown,
|
||||
keyToUrl: Map<string, string>
|
||||
): unknown {
|
||||
if (typeof value === 'string') {
|
||||
let result = value;
|
||||
for (const [key, url] of keyToUrl) {
|
||||
result = result.replace(`__IMG__${key}__`, url);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => restorePlaceholders(item, keyToUrl));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const obj: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
|
||||
obj[k] = restorePlaceholders(v, keyToUrl);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a short unique key for an image URL.
|
||||
*/
|
||||
export function urlToKey(url: string): string {
|
||||
const parts = url.split('/');
|
||||
const filename = parts[parts.length - 1] || 'img';
|
||||
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
|
||||
return `${id}_${filename}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch an image and return it as a base64 data-URI string.
|
||||
*/
|
||||
export async function fetchImageAsBase64(url: string): Promise<string> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
|
||||
const blob = await response.blob();
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
const base64 = btoa(binary);
|
||||
return `data:${blob.type};base64,${base64}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a base64 data-URI back to a File object for upload.
|
||||
*/
|
||||
export function dataUriToFile(dataUri: string, filename: string): File {
|
||||
const [header, base64] = dataUri.split(',');
|
||||
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return new File([bytes], filename, { type: mime });
|
||||
}
|
||||
37
app-admin/src/lib/pb.ts
Normal file
37
app-admin/src/lib/pb.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
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('/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();
|
||||
}
|
||||
30
app-admin/src/lib/scrollReveal.ts
Normal file
30
app-admin/src/lib/scrollReveal.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
* 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();
|
||||
}
|
||||
};
|
||||
}
|
||||
187
app-admin/src/lib/server/basket.ts
Normal file
187
app-admin/src/lib/server/basket.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
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;
|
||||
}
|
||||
53
app-admin/src/lib/server/pb-admin.ts
Normal file
53
app-admin/src/lib/server/pb-admin.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
15
app-admin/src/lib/stripe-client.ts
Normal file
15
app-admin/src/lib/stripe-client.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
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;
|
||||
}
|
||||
1
app-admin/src/lib/types.ts
Normal file
1
app-admin/src/lib/types.ts
Normal file
|
|
@ -0,0 +1 @@
|
|||
export * from '$shared/types';
|
||||
16
app-admin/src/routes/+layout.server.ts
Normal file
16
app-admin/src/routes/+layout.server.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { defaultColors } from '$lib/types';
|
||||
import type { LayoutServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
try {
|
||||
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
return record.data || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export const load: LayoutServerLoad = async ({ locals }) => {
|
||||
const colors = await getGlobal(locals.pb, 'colors', defaultColors);
|
||||
return { user: locals.user, colors };
|
||||
};
|
||||
126
app-admin/src/routes/+layout.svelte
Normal file
126
app-admin/src/routes/+layout.svelte
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
<script lang="ts">
|
||||
import '../app.css';
|
||||
import favicon from '$lib/assets/favicon.svg';
|
||||
import { createBasketStore, setBasketContext } from '$lib/basket.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let { children, data } = $props();
|
||||
let importStatus = $state<{ ok: boolean; message: string } | null>(null);
|
||||
let importing = $state(false);
|
||||
|
||||
// One basket store per layout instance — provided to all children
|
||||
// (preview iframe block renderers). Never module-level state.
|
||||
// Admin doesn't have a real basket; pass null so the store starts empty.
|
||||
const basketStore = createBasketStore(null);
|
||||
setBasketContext(basketStore);
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const res = await fetch('/api/export');
|
||||
if (!res.ok) throw new Error(`Export failed (${res.status})`);
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `cms-export-${new Date().toISOString().slice(0, 10)}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Export error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
importing = true;
|
||||
importStatus = null;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const json = JSON.parse(text);
|
||||
const res = await fetch('/api/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(json)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.message || `Import failed (${res.status})`);
|
||||
}
|
||||
const result = await res.json();
|
||||
const msg = `Imported ${result.pagesImported} page(s), ${result.globalsImported} global(s), ${result.eventsImported || 0} event(s), ${result.imagesUploaded} image(s).`;
|
||||
importStatus = { ok: true, message: result.errors?.length ? msg + ` ${result.errors.length} error(s).` : msg };
|
||||
setTimeout(() => location.reload(), 1500);
|
||||
} catch (e) {
|
||||
importStatus = { ok: false, message: `Import error: ${e instanceof Error ? e.message : String(e)}` };
|
||||
} finally {
|
||||
importing = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// Apply saved colors so the preview iframe matches the public site.
|
||||
if (data.colors) {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--color-bg', data.colors.background);
|
||||
root.style.setProperty('--color-heading', data.colors.heading);
|
||||
root.style.setProperty('--color-subheading', data.colors.subheading);
|
||||
root.style.setProperty('--color-text', data.colors.text);
|
||||
root.style.setProperty('--color-primary', data.colors.primary);
|
||||
root.style.setProperty('--color-accent', data.colors.accent);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<link rel="icon" href={favicon} />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
</svelte:head>
|
||||
|
||||
<div class="min-h-screen bg-base-200">
|
||||
<div class="navbar bg-base-100 shadow-sm">
|
||||
<div class="flex-1">
|
||||
<a class="btn btn-ghost text-xl" href="/pages">Massage CMS</a>
|
||||
</div>
|
||||
<div class="flex-none gap-2">
|
||||
<a class="btn btn-ghost" href="/pages">Pages</a>
|
||||
<a class="btn btn-ghost" href="/calendar">Calendar</a>
|
||||
<a class="btn btn-ghost" href="/items">Items</a>
|
||||
<a class="btn btn-ghost" href="/slots">Slots</a>
|
||||
<a class="btn btn-ghost" href="/orders">Orders</a>
|
||||
<a class="btn btn-ghost" href="/globals">Globals</a>
|
||||
<div class="dropdown dropdown-end">
|
||||
<button class="btn btn-ghost btn-sm" type="button" tabindex="0">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M7 11l5 5 5-5M12 4v12" /></svg>
|
||||
Export/Import
|
||||
</button>
|
||||
<ul class="menu dropdown-content z-20 mt-2 w-48 rounded-box bg-base-100 p-2 shadow">
|
||||
<li><button type="button" onclick={handleExport}>Export all</button></li>
|
||||
<li>
|
||||
<button type="button" onclick={() => (document.getElementById('admin-import-file') as HTMLInputElement)?.click()} disabled={importing}>
|
||||
{importing ? 'Importing…' : 'Import'}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<input id="admin-import-file" type="file" accept=".json" class="hidden" onchange={handleImport} />
|
||||
<form class="inline" method="POST" action="/login?/logout">
|
||||
<button class="btn btn-outline btn-sm" type="submit">Logout</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{#if importStatus}
|
||||
<div class="mx-auto max-w-7xl px-4 pt-2">
|
||||
<div class="alert" class:alert-success={importStatus.ok} class:alert-error={!importStatus.ok}>
|
||||
{importStatus.message}
|
||||
<button class="btn btn-ghost btn-xs" onclick={() => (importStatus = null)}>×</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<main class="mx-auto max-w-7xl p-4 md:p-8">
|
||||
{@render children()}
|
||||
</main>
|
||||
</div>
|
||||
98
app-admin/src/routes/api/export/+server.ts
Normal file
98
app-admin/src/routes/api/export/+server.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { env } from '$env/dynamic/private';
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
extractImageUrls,
|
||||
fetchImageAsBase64,
|
||||
replaceUrlsWithKeys,
|
||||
urlToKey,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
import { normalizeEvent } from '$lib/calendar';
|
||||
|
||||
export const GET: RequestHandler = async ({ locals }) => {
|
||||
// Fetch all pages
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
// Fetch all globals
|
||||
const globals = await locals.pb.collection('globals').getFullList();
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
|
||||
// Collect all image URLs from pages and globals
|
||||
const allUrls = new Set<string>();
|
||||
for (const page of pages) {
|
||||
for (const url of extractImageUrls(page)) allUrls.add(url);
|
||||
}
|
||||
for (const g of globals) {
|
||||
for (const url of extractImageUrls(g)) allUrls.add(url);
|
||||
}
|
||||
|
||||
// Fetch each image as base64. Stored image URLs may use any public host
|
||||
// (e.g. http://localhost:8080 from before a domain migration, or
|
||||
// http://db.localhost:8080 after). The app container can only reach
|
||||
// PocketBase via the internal Docker network URL, so rewrite the host
|
||||
// of every matched URL to the internal base.
|
||||
const internalBase = env.POCKETBASE_INTERNAL_URL!;
|
||||
|
||||
const images: Record<string, string> = {};
|
||||
for (const url of allUrls) {
|
||||
try {
|
||||
// Replace the host (and optional port) with the internal base.
|
||||
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
|
||||
const key = urlToKey(url);
|
||||
images[key] = await fetchImageAsBase64(fetchUrl);
|
||||
} catch (e) {
|
||||
console.warn(`Could not fetch image: ${url}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// Build URL → key mapping
|
||||
const urlToKeyMap = new Map<string, string>();
|
||||
for (const url of allUrls) {
|
||||
urlToKeyMap.set(url, urlToKey(url));
|
||||
}
|
||||
|
||||
// Replace URLs with placeholders in pages
|
||||
const exportPages = pages.map((p) => ({
|
||||
slug: p.slug,
|
||||
title: p.title,
|
||||
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
|
||||
published: p.published
|
||||
}));
|
||||
|
||||
// Replace URLs with placeholders in globals
|
||||
const exportGlobals = globals.map((g) => ({
|
||||
key: g.key,
|
||||
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
|
||||
}));
|
||||
|
||||
const exportEvents = events.map((record) => {
|
||||
const event = normalizeEvent(record);
|
||||
return {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end,
|
||||
description: event.description,
|
||||
color: event.color,
|
||||
link: event.link,
|
||||
categories: event.categories,
|
||||
published: event.published,
|
||||
allDay: event.allDay
|
||||
};
|
||||
});
|
||||
|
||||
const exportData: SiteExport = {
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
pages: exportPages,
|
||||
globals: exportGlobals,
|
||||
events: exportEvents,
|
||||
images
|
||||
};
|
||||
|
||||
return json(exportData, {
|
||||
headers: {
|
||||
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
|
||||
}
|
||||
});
|
||||
};
|
||||
140
app-admin/src/routes/api/import/+server.ts
Normal file
140
app-admin/src/routes/api/import/+server.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import {
|
||||
dataUriToFile,
|
||||
restorePlaceholders,
|
||||
type SiteExport
|
||||
} from '$lib/exportImport';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const body = (await request.json()) as SiteExport;
|
||||
|
||||
if (!body || body.version !== 1) {
|
||||
throw error(400, 'Invalid or unsupported export file.');
|
||||
}
|
||||
|
||||
const results = {
|
||||
imagesUploaded: 0,
|
||||
pagesImported: 0,
|
||||
globalsImported: 0,
|
||||
eventsImported: 0,
|
||||
errors: [] as string[]
|
||||
};
|
||||
|
||||
// 1. Upload images to PocketBase media collection
|
||||
// Build a map: placeholder key → new PocketBase URL
|
||||
const keyToUrl = new Map<string, string>();
|
||||
|
||||
for (const [key, dataUri] of Object.entries(body.images)) {
|
||||
try {
|
||||
// Derive a filename from the key (e.g. "abc12345_logo.png")
|
||||
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
|
||||
const file = dataUriToFile(dataUri, filename);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
|
||||
const record = await locals.pb.collection('media').create(formData);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL;
|
||||
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
|
||||
keyToUrl.set(key, newUrl);
|
||||
results.imagesUploaded++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Import pages
|
||||
for (const page of body.pages) {
|
||||
try {
|
||||
const blocks = restorePlaceholders(page.blocks, keyToUrl);
|
||||
|
||||
// Try to find existing page by slug
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('pages').update(existing.id, {
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
} else {
|
||||
await locals.pb.collection('pages').create({
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
blocks,
|
||||
published: page.published
|
||||
});
|
||||
}
|
||||
results.pagesImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Import globals
|
||||
for (const g of body.globals) {
|
||||
try {
|
||||
const data = restorePlaceholders(g.data, keyToUrl);
|
||||
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('globals').update(existing.id, { data });
|
||||
} else {
|
||||
await locals.pb.collection('globals').create({ key: g.key, data });
|
||||
}
|
||||
results.globalsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Import events
|
||||
for (const event of body.events || []) {
|
||||
try {
|
||||
let existing;
|
||||
try {
|
||||
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
|
||||
} catch {
|
||||
existing = null;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: event.name,
|
||||
start: event.start,
|
||||
end: event.end || null,
|
||||
description: event.description || '',
|
||||
color: event.color || '#8a9a7b',
|
||||
link: event.link || '',
|
||||
categories: event.categories || [],
|
||||
published: Boolean(event.published),
|
||||
allDay: event.allDay !== false
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await locals.pb.collection('events').update(existing.id, payload);
|
||||
} else {
|
||||
await locals.pb.collection('events').create(payload);
|
||||
}
|
||||
results.eventsImported++;
|
||||
} catch (e) {
|
||||
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return json(results);
|
||||
};
|
||||
27
app-admin/src/routes/api/upload/+server.ts
Normal file
27
app-admin/src/routes/api/upload/+server.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { env } from '$env/dynamic/public';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
const alt = formData.get('alt') as string | null;
|
||||
|
||||
if (!file) {
|
||||
throw error(400, 'No file provided');
|
||||
}
|
||||
|
||||
const uploadForm = new FormData();
|
||||
uploadForm.append('file', file);
|
||||
if (alt) uploadForm.append('alt', alt);
|
||||
|
||||
try {
|
||||
const record = await locals.pb.collection('media').create(uploadForm);
|
||||
const publicUrl = env.PUBLIC_POCKETBASE_URL;
|
||||
const url = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
|
||||
return json({ record, url });
|
||||
} catch (e) {
|
||||
console.error('Media upload error:', e);
|
||||
throw error(500, 'Upload failed');
|
||||
}
|
||||
};
|
||||
54
app-admin/src/routes/calendar/+page.server.ts
Normal file
54
app-admin/src/routes/calendar/+page.server.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { fail } from '@sveltejs/kit';
|
||||
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
function eventPayload(data: FormData) {
|
||||
const allDay = String(data.get('allDay')) === 'true';
|
||||
const start = String(data.get('start') || '').trim();
|
||||
const end = String(data.get('end') || '').trim();
|
||||
const name = String(data.get('name') || '').trim();
|
||||
|
||||
return {
|
||||
name,
|
||||
start: dateInputToPocketBase(start, allDay),
|
||||
end: end ? dateInputToPocketBase(end, allDay) : null,
|
||||
description: String(data.get('description') || '').trim(),
|
||||
color: String(data.get('color') || '#8a9a7b').trim(),
|
||||
link: String(data.get('link') || '').trim(),
|
||||
categories: normalizeCategories(String(data.get('categories') || '')),
|
||||
published: String(data.get('published')) === 'true',
|
||||
allDay
|
||||
};
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const records = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const events = records.map((record) => normalizeEvent(record));
|
||||
return { events };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const payload = eventPayload(data);
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').create(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
update: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
const payload = eventPayload(data);
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
|
||||
await locals.pb.collection('events').update(id, payload);
|
||||
return { ok: true };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Event id is required.' });
|
||||
await locals.pb.collection('events').delete(id);
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
236
app-admin/src/routes/calendar/+page.svelte
Normal file
236
app-admin/src/routes/calendar/+page.svelte
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
<script lang="ts">
|
||||
import { addMonths, createCalendarMonth, eventOverlapsDay, formatEventDateRange, sortEvents, toDateInput, toDatetimeInput } from '$lib/calendar';
|
||||
import type { CalendarEventRecord } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let events = $derived(sortEvents(data.events || []));
|
||||
let viewDate = $state(new Date(new Date().getFullYear(), new Date().getMonth(), 1));
|
||||
let showEditor = $state(false);
|
||||
let draft = $state<CalendarEventRecord>({
|
||||
id: '',
|
||||
name: '',
|
||||
start: toDateInput(new Date().toISOString()),
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
});
|
||||
let categoryText = $state('');
|
||||
|
||||
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
||||
let month = $derived(createCalendarMonth(viewDate));
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let dateInputType = $derived(draft.allDay ? 'date' : 'datetime-local');
|
||||
let startValue = $derived(draft.allDay ? toDateInput(draft.start) : toDatetimeInput(draft.start));
|
||||
let endValue = $derived(draft.allDay ? toDateInput(draft.end) : toDatetimeInput(draft.end));
|
||||
let allCategories = $derived([...new Set(events.flatMap((event) => event.categories || []))].sort((a, b) => a.localeCompare(b)));
|
||||
|
||||
function eventsForDay(date: Date) {
|
||||
return events.filter((event) => eventOverlapsDay(event, date));
|
||||
}
|
||||
|
||||
function emptyDraft(start = toDateInput(new Date().toISOString())): CalendarEventRecord {
|
||||
return {
|
||||
id: '',
|
||||
name: '',
|
||||
start,
|
||||
end: '',
|
||||
description: '',
|
||||
color: '#8a9a7b',
|
||||
link: '',
|
||||
categories: [],
|
||||
published: false,
|
||||
allDay: true
|
||||
};
|
||||
}
|
||||
|
||||
function createEvent(start?: string) {
|
||||
draft = emptyDraft(start);
|
||||
categoryText = '';
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editEvent(event: CalendarEventRecord) {
|
||||
draft = structuredClone(event);
|
||||
categoryText = event.categories.join(', ');
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function previousMonth() {
|
||||
viewDate = addMonths(viewDate, -1);
|
||||
}
|
||||
|
||||
function nextMonth() {
|
||||
viewDate = addMonths(viewDate, 1);
|
||||
}
|
||||
|
||||
function addCategory(category: string) {
|
||||
if (!category || draft.categories.includes(category)) return;
|
||||
draft = { ...draft, categories: [...draft.categories, category] };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function removeCategory(category: string) {
|
||||
draft = { ...draft, categories: draft.categories.filter((item) => item !== category) };
|
||||
categoryText = draft.categories.join(', ');
|
||||
}
|
||||
|
||||
function syncCategoryText(value: string) {
|
||||
categoryText = value;
|
||||
draft = { ...draft, categories: value.split(',').map((item) => item.trim()).filter(Boolean) };
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Calendar | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Calendar</h1>
|
||||
<p class="text-base-content/60">Create and manage events used by Upcoming Calendar blocks.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createEvent()}>Create event</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={previousMonth}>← Previous</button>
|
||||
<h2 class="text-2xl font-bold">{month.label}</h2>
|
||||
<button class="btn btn-outline btn-sm" type="button" onclick={nextMonth}>Next →</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-7 gap-2 text-center text-xs font-semibold uppercase text-base-content/50">
|
||||
{#each weekdays as weekday}<div>{weekday}</div>{/each}
|
||||
</div>
|
||||
<div class="mt-2 grid grid-cols-7 gap-2">
|
||||
{#each month.days as day}
|
||||
<div class="min-h-32 rounded-box border border-base-300 bg-base-200/60 p-2" class:opacity-40={!day.inMonth}>
|
||||
<button class="btn btn-ghost btn-xs mb-1" class:btn-primary={day.isToday} type="button" onclick={() => createEvent(day.dateKey)}>{day.dayNumber}</button>
|
||||
<div class="space-y-1">
|
||||
{#each eventsForDay(day.date) as event}
|
||||
<button class="w-full rounded-lg px-2 py-1 text-left text-xs font-semibold text-white shadow" style={`background:${event.color || '#8a9a7b'}`} type="button" onclick={() => editEvent(event)}>
|
||||
<span class="block truncate">{event.name}</span>
|
||||
<span class="block truncate text-[0.65rem] opacity-80">{formatEventDateRange(event)}</span>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<h2 class="mb-4 text-xl font-bold">All events</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Name</th><th>Date</th><th>Categories</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each events as event}
|
||||
<tr>
|
||||
<td><span class="mr-2 inline-block h-3 w-3 rounded-full" style={`background:${event.color}`}></span>{event.name}</td>
|
||||
<td>{formatEventDateRange(event)}</td>
|
||||
<td>{event.categories.join(', ')}</td>
|
||||
<td><span class="badge" class:badge-success={event.published}>{event.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editEvent(event)}>Edit</button></td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showEditor}
|
||||
<div class="fixed inset-0 z-50 bg-black/50 p-4">
|
||||
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 class="text-2xl font-bold">{draft.id ? 'Edit event' : 'Create event'}</h2>
|
||||
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action={action} class="space-y-4">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
<input type="hidden" name="allDay" value={draft.allDay ? 'true' : 'false'} />
|
||||
<input type="hidden" name="published" value={draft.published ? 'true' : 'false'} />
|
||||
<input type="hidden" name="categories" value={categoryText} />
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Name</span></div>
|
||||
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Start</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="start" required value={startValue} oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">End optional</span></div>
|
||||
<input class="input input-bordered w-full" type={dateInputType} name="end" value={endValue} oninput={(e) => (draft = { ...draft, end: e.currentTarget.value })} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-primary" type="checkbox" bind:checked={draft.allDay} />
|
||||
<span class="label-text">All-day event</span>
|
||||
</label>
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.published} />
|
||||
<span class="label-text">Published</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Description</span></div>
|
||||
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Color</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input class="input input-bordered h-12 w-14 p-1" type="color" bind:value={draft.color} />
|
||||
<input class="input input-bordered flex-1" name="color" bind:value={draft.color} />
|
||||
</div>
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Link optional</span></div>
|
||||
<input class="input input-bordered w-full" name="link" placeholder="/page or https://..." bind:value={draft.link} />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="rounded-box border border-base-300 p-4">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Categories comma-separated</span></div>
|
||||
<input class="input input-bordered w-full" value={categoryText} oninput={(e) => syncCategoryText(e.currentTarget.value)} />
|
||||
</label>
|
||||
{#if allCategories.length}
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
{#each allCategories as category}
|
||||
<button class="btn btn-xs" class:btn-primary={draft.categories.includes(category)} type="button" onclick={() => draft.categories.includes(category) ? removeCategory(category) : addCategory(category)}>{category}</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="flex justify-between gap-2 pt-2">
|
||||
{#if draft.id}
|
||||
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Save event</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
31
app-admin/src/routes/globals/+page.server.ts
Normal file
31
app-admin/src/routes/globals/+page.server.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
|
||||
try {
|
||||
return await pb.collection('globals').getFirstListItem(`key = "${key}"`);
|
||||
} catch {
|
||||
return await pb.collection('globals').create({ key, data: fallback });
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const [header, footer, colors] = await Promise.all([
|
||||
getGlobal(locals.pb, 'header', defaultHeader),
|
||||
getGlobal(locals.pb, 'footer', defaultFooter),
|
||||
getGlobal(locals.pb, 'colors', defaultColors)
|
||||
]);
|
||||
|
||||
// Fetch all pages for the home page selector
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
|
||||
return { header, footer, colors, pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) });
|
||||
}
|
||||
};
|
||||
96
app-admin/src/routes/globals/+page.svelte
Normal file
96
app-admin/src/routes/globals/+page.svelte
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
<script lang="ts">
|
||||
import ImageUploader from '$lib/admin/editors/ImageUploader.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
let header = $state(structuredClone(data.header.data));
|
||||
let footer = $state(structuredClone(data.footer.data));
|
||||
let colors = $state(structuredClone(data.colors.data));
|
||||
function addHeaderLink() { header.navLinks = [...(header.navLinks || []), { label: '', href: '' }]; }
|
||||
function addSocial() { footer.socialLinks = [...(footer.socialLinks || []), { platform: '', url: '' }]; }
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Globals | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6">
|
||||
<h1 class="text-3xl font-bold">Global sections</h1>
|
||||
<p class="text-base-content/60">Edit the site header, footer, and global color settings.</p>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 xl:grid-cols-3">
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.header.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(header)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Header</h2>
|
||||
<ImageUploader url={header.logo?.url} alt={header.logo?.alt} onChange={(image) => (header.logo = image)} />
|
||||
<h3 class="mt-6 font-bold">Navigation</h3>
|
||||
{#each header.navLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.label} placeholder="Label" />
|
||||
<input class="input input-bordered" bind:value={link.href} placeholder="Href" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (header.navLinks = header.navLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addHeaderLink}>Add link</button>
|
||||
<h3 class="mt-6 font-bold">CTA button</h3>
|
||||
<input class="input input-bordered mb-2 w-full" bind:value={header.ctaButton.label} placeholder="Label" />
|
||||
<input class="input input-bordered w-full" bind:value={header.ctaButton.href} placeholder="Href" />
|
||||
<h3 class="mt-6 font-bold">Home page</h3>
|
||||
<select class="select select-bordered w-full" bind:value={header.homePage}>
|
||||
<option value="">— Select a page —</option>
|
||||
{#each data.pages as page}
|
||||
<option value={page.slug}>{page.title} [{page.slug}]</option>
|
||||
{/each}
|
||||
</select>
|
||||
<p class="text-sm text-base-content/60 mt-1">The page that "/" will redirect to.</p>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save header</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.footer.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(footer)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Footer</h2>
|
||||
{#each ['businessName', 'tagline', 'address', 'phone', 'email', 'copyrightText'] as field}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">{field}</span></div>
|
||||
<input class="input input-bordered w-full" bind:value={footer[field]} />
|
||||
</label>
|
||||
{/each}
|
||||
<h3 class="mt-6 font-bold">Social links</h3>
|
||||
{#each footer.socialLinks || [] as link, i}
|
||||
<div class="my-2 grid grid-cols-[1fr_1fr_auto] gap-2">
|
||||
<input class="input input-bordered" bind:value={link.platform} placeholder="Platform" />
|
||||
<input class="input input-bordered" bind:value={link.url} placeholder="URL" />
|
||||
<button class="btn btn-error btn-outline" type="button" onclick={() => (footer.socialLinks = footer.socialLinks.filter((_: unknown, index: number) => index !== i))}>×</button>
|
||||
</div>
|
||||
{/each}
|
||||
<button class="btn btn-sm" type="button" onclick={addSocial}>Add social link</button>
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save footer</button>
|
||||
</form>
|
||||
|
||||
<form class="rounded-box bg-base-100 p-5 shadow flex flex-col" method="POST" action="?/save">
|
||||
<input type="hidden" name="id" value={data.colors.id} />
|
||||
<input type="hidden" name="data" value={JSON.stringify(colors)} />
|
||||
<h2 class="mb-4 text-2xl font-bold">Colors</h2>
|
||||
<p class="text-sm text-base-content/60 mb-4">These colors are applied across the site as defaults.</p>
|
||||
{#each [
|
||||
{ key: 'background', label: 'Background color' },
|
||||
{ key: 'heading', label: 'Heading color' },
|
||||
{ key: 'subheading', label: 'Subheading color' },
|
||||
{ key: 'text', label: 'Text color' },
|
||||
{ key: 'primary', label: 'Primary color (buttons, links)' },
|
||||
{ key: 'accent', label: 'Accent color (highlights)' }
|
||||
] as { key, label }}
|
||||
<label class="form-control w-full mb-3">
|
||||
<div class="label"><span class="label-text">{label}</span></div>
|
||||
<div class="flex gap-2">
|
||||
<input type="color" class="cursor-pointer" bind:value={colors[key]} />
|
||||
<input type="text" class="input input-bordered flex-1 font-mono text-sm" bind:value={colors[key]} />
|
||||
</div>
|
||||
</label>
|
||||
{/each}
|
||||
<div class="flex-grow"></div>
|
||||
<button class="btn btn-primary mt-6 block w-full" type="submit">Save colors</button>
|
||||
</form>
|
||||
</div>
|
||||
74
app-admin/src/routes/items/+page.server.ts
Normal file
74
app-admin/src/routes/items/+page.server.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { fail } from '@sveltejs/kit';
|
||||
import { getFileUrl } from '$lib/pb';
|
||||
import type { ItemRecord, ItemType } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
function itemPayload(data: FormData) {
|
||||
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
|
||||
const rawStock = String(data.get('stock') ?? '').trim();
|
||||
const rawDuration = String(data.get('duration') ?? '').trim();
|
||||
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
|
||||
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
|
||||
|
||||
return {
|
||||
name: String(data.get('name') || '').trim(),
|
||||
description: String(data.get('description') || '').trim(),
|
||||
price: parseFloat(String(data.get('price') || '')),
|
||||
image: String(data.get('image') || '').trim(),
|
||||
type,
|
||||
stock: Number.isNaN(stock) ? null : stock,
|
||||
duration: Number.isNaN(duration) ? null : duration,
|
||||
active: String(data.get('active')) === 'true'
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeItem(record: Record<string, any>): ItemRecord {
|
||||
const media = record.expand?.image;
|
||||
return {
|
||||
id: record.id,
|
||||
name: String(record.name || ''),
|
||||
description: String(record.description || ''),
|
||||
price: Number(record.price) || 0,
|
||||
image: String(record.image || ''),
|
||||
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
|
||||
type: record.type === 'item_with_time' ? 'item_with_time' : 'item',
|
||||
stock: record.stock ?? null,
|
||||
duration: record.duration ?? null,
|
||||
active: record.active !== false
|
||||
};
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const records = await locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ sort: 'name', expand: 'image' })
|
||||
.catch(() => []);
|
||||
const items = records.map((record) => normalizeItem(record));
|
||||
return { items };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const payload = itemPayload(data);
|
||||
if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
|
||||
await locals.pb.collection('items').create(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
update: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
const payload = itemPayload(data);
|
||||
if (!id) return fail(400, { message: 'Item id is required.' });
|
||||
if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' });
|
||||
await locals.pb.collection('items').update(id, payload);
|
||||
return { ok: true };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Item id is required.' });
|
||||
await locals.pb.collection('items').delete(id);
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
199
app-admin/src/routes/items/+page.svelte
Normal file
199
app-admin/src/routes/items/+page.svelte
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
<script lang="ts">
|
||||
import type { ItemRecord, ItemType } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let items = $derived(data.items || []);
|
||||
let showEditor = $state(false);
|
||||
let uploading = $state(false);
|
||||
|
||||
type ItemDraft = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
image: string;
|
||||
imageUrl: string;
|
||||
type: ItemType;
|
||||
stock: string;
|
||||
duration: string;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
let draft = $state<ItemDraft>(emptyDraft());
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
|
||||
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
|
||||
function emptyDraft(): ItemDraft {
|
||||
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', active: true };
|
||||
}
|
||||
|
||||
function createItem() {
|
||||
draft = emptyDraft();
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editItem(item: ItemRecord) {
|
||||
draft = {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
price: item.price,
|
||||
image: item.image,
|
||||
imageUrl: item.imageUrl,
|
||||
type: item.type,
|
||||
stock: item.stock == null ? '' : String(item.stock),
|
||||
duration: item.duration == null ? '' : String(item.duration),
|
||||
active: item.active
|
||||
};
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
async function onImageSelected(event: Event) {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
uploading = true;
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('alt', file.name.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
|
||||
const res = await fetch('/api/upload', { method: 'POST', body: formData });
|
||||
if (!res.ok) throw new Error(`Upload failed (${res.status})`);
|
||||
const result = await res.json();
|
||||
draft = { ...draft, image: result.record.id, imageUrl: result.url };
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
uploading = false;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Items | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Items</h1>
|
||||
<p class="text-base-content/60">Manage services and products shown in Shop blocks.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createItem()}>Create item</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Name</th><th>Type</th><th>Price</th><th>Stock</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each items as item}
|
||||
<tr>
|
||||
<td>
|
||||
<div class="flex items-center gap-3">
|
||||
{#if item.imageUrl}
|
||||
<img class="h-10 w-10 rounded-box object-cover" src={item.imageUrl} alt="" />
|
||||
{/if}
|
||||
<span class="font-semibold">{item.name}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
|
||||
<td>{eur.format(item.price)}</td>
|
||||
<td>{item.type === 'item' ? (item.stock ?? '—') : '—'}</td>
|
||||
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min` : '—'}</td>
|
||||
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showEditor}
|
||||
<div class="fixed inset-0 z-50 bg-black/50 p-4">
|
||||
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 class="text-2xl font-bold">{draft.id ? 'Edit item' : 'Create item'}</h2>
|
||||
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action={action} class="space-y-4">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
<input type="hidden" name="active" value={draft.active ? 'true' : 'false'} />
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Name</span></div>
|
||||
<input class="input input-bordered w-full" name="name" required bind:value={draft.name} />
|
||||
</label>
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Description</span></div>
|
||||
<textarea class="textarea textarea-bordered min-h-28" name="description" bind:value={draft.description}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Price</span></div>
|
||||
<input class="input input-bordered w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Type</span></div>
|
||||
<select class="select select-bordered w-full" name="type" bind:value={draft.type}>
|
||||
<option value="item">Product</option>
|
||||
<option value="item_with_time">Service</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if draft.type === 'item'}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Stock</span></div>
|
||||
<input class="input input-bordered w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
|
||||
</label>
|
||||
{:else}
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Duration minutes</span></div>
|
||||
<input class="input input-bordered w-full" type="number" min="0" step="1" name="duration" placeholder="60" bind:value={draft.duration} />
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<div class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Image</span></div>
|
||||
<div class="flex items-start gap-3">
|
||||
{#if draft.imageUrl}
|
||||
<img class="h-16 w-16 rounded-box object-cover" src={draft.imageUrl} alt="" />
|
||||
{/if}
|
||||
<div class="flex-1 space-y-2">
|
||||
<input class="input input-bordered w-full" name="image" placeholder="Media record id" bind:value={draft.image} />
|
||||
<input class="file-input file-input-bordered file-input-sm w-full" type="file" accept="image/*" disabled={uploading} onchange={onImageSelected} />
|
||||
<p class="text-xs text-base-content/60">
|
||||
{uploading ? 'Uploading…' : 'Upload a file or paste a media record id. A media picker will replace this in a later iteration.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="label cursor-pointer justify-start gap-3">
|
||||
<input class="toggle toggle-success" type="checkbox" bind:checked={draft.active} />
|
||||
<span class="label-text">Active</span>
|
||||
</label>
|
||||
|
||||
<div class="flex justify-between gap-2 pt-2">
|
||||
{#if draft.id}
|
||||
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Save item</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
27
app-admin/src/routes/login/+page.server.ts
Normal file
27
app-admin/src/routes/login/+page.server.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions } from './$types';
|
||||
|
||||
export const actions: Actions = {
|
||||
login: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const email = String(data.get('email') || '');
|
||||
const password = String(data.get('password') || '');
|
||||
|
||||
try {
|
||||
try {
|
||||
await locals.pb.admins.authWithPassword(email, password);
|
||||
} catch {
|
||||
await locals.pb.collection('users').authWithPassword(email, password);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login failed for', email, err);
|
||||
return fail(400, { message: 'Invalid email or password.' });
|
||||
}
|
||||
|
||||
throw redirect(303, '/pages');
|
||||
},
|
||||
logout: async ({ locals }) => {
|
||||
locals.pb.authStore.clear();
|
||||
throw redirect(303, '/login');
|
||||
}
|
||||
};
|
||||
26
app-admin/src/routes/login/+page.svelte
Normal file
26
app-admin/src/routes/login/+page.svelte
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<script lang="ts">
|
||||
let { form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Admin login</title></svelte:head>
|
||||
|
||||
<div class="grid min-h-screen place-items-center bg-base-200 p-6">
|
||||
<form class="card w-full max-w-md bg-base-100 shadow-xl" method="POST" action="?/login">
|
||||
<div class="card-body">
|
||||
<h1 class="card-title text-3xl">Sign in</h1>
|
||||
<p class="text-base-content/60">Use your PocketBase admin or CMS user credentials.</p>
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mt-4">{form.message}</div>
|
||||
{/if}
|
||||
<label class="form-control mt-4">
|
||||
<span class="label-text">Email</span>
|
||||
<input class="input input-bordered" name="email" type="email" required />
|
||||
</label>
|
||||
<label class="form-control">
|
||||
<span class="label-text">Password</span>
|
||||
<input class="input input-bordered" name="password" type="password" required />
|
||||
</label>
|
||||
<button class="btn btn-primary mt-4" type="submit">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
34
app-admin/src/routes/orders/+page.server.ts
Normal file
34
app-admin/src/routes/orders/+page.server.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import type { PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
// Sort by id, not 'created' — commerce collections were imported without
|
||||
// autodate fields. PocketBase ids are time-sortable ULIDs.
|
||||
const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []);
|
||||
|
||||
const orders = [];
|
||||
for (const record of records) {
|
||||
const lineRecords = await locals.pb
|
||||
.collection('order_lines')
|
||||
.getFullList({ filter: `order = "${record.id}"` })
|
||||
.catch(() => []);
|
||||
|
||||
orders.push({
|
||||
id: record.id,
|
||||
email: String(record.email || ''),
|
||||
customerDetails: record.customerDetails || {},
|
||||
total: Number(record.total) || 0,
|
||||
status: String(record.status || 'pending'),
|
||||
created: String(record.created || ''),
|
||||
lines: lineRecords.map((line) => ({
|
||||
id: line.id,
|
||||
name: String(line.name || ''),
|
||||
price: Number(line.price) || 0,
|
||||
quantity: Number(line.quantity) || 1,
|
||||
lineType: String(line.lineType || 'item'),
|
||||
start: line.start ? String(line.start) : ''
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
return { orders };
|
||||
};
|
||||
58
app-admin/src/routes/orders/+page.svelte
Normal file
58
app-admin/src/routes/orders/+page.svelte
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<script lang="ts">
|
||||
let { data } = $props();
|
||||
let orders = $derived(data.orders || []);
|
||||
|
||||
const eur = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' });
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Orders | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Orders</h1>
|
||||
<p class="text-base-content/60">Confirmed bookings and purchases.</p>
|
||||
</div>
|
||||
|
||||
{#if orders.length === 0}
|
||||
<div class="rounded-box bg-base-100 p-8 text-center text-base-content/60 shadow">No orders yet.</div>
|
||||
{/if}
|
||||
|
||||
{#each orders as order}
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="flex flex-col justify-between gap-3 md:flex-row md:items-center">
|
||||
<div>
|
||||
<h2 class="text-xl font-bold">{order.customerDetails?.name || order.email || 'Order'}</h2>
|
||||
<p class="text-sm text-base-content/60">
|
||||
{order.email}
|
||||
{#if order.customerDetails?.phone} · {order.customerDetails.phone}{/if}
|
||||
{#if order.created} · {new Date(order.created).toLocaleString()}{/if}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<span
|
||||
class="badge capitalize"
|
||||
class:badge-success={order.status === 'paid'}
|
||||
class:badge-warning={order.status === 'pending'}
|
||||
class:badge-error={order.status === 'refunded'}
|
||||
>{order.status}</span>
|
||||
<span class="text-lg font-bold">{eur.format(order.total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="mt-4 space-y-1 border-t border-base-300 pt-4">
|
||||
{#each order.lines as line}
|
||||
<li>
|
||||
{line.quantity}× {line.name} — {eur.format(line.price)}
|
||||
{#if line.lineType === 'slot' && line.start}
|
||||
<span class="block text-sm text-base-content/60">{new Date(line.start).toLocaleString()}</span>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if order.customerDetails?.notes}
|
||||
<p class="mt-3 text-sm italic text-base-content/60">"{order.customerDetails.notes}"</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
29
app-admin/src/routes/pages/+page.server.ts
Normal file
29
app-admin/src/routes/pages/+page.server.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
|
||||
return { pages };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false });
|
||||
throw redirect(303, `/pages/${slug}`);
|
||||
},
|
||||
toggle: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').update(String(data.get('id')), {
|
||||
published: String(data.get('published')) !== 'true'
|
||||
});
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
await locals.pb.collection('pages').delete(String(data.get('id')));
|
||||
}
|
||||
};
|
||||
65
app-admin/src/routes/pages/+page.svelte
Normal file
65
app-admin/src/routes/pages/+page.svelte
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
<script lang="ts">
|
||||
let { data, form } = $props();
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Pages | CMS</title></svelte:head>
|
||||
|
||||
<div class="mb-6 flex flex-col justify-between gap-4 md:flex-row md:items-center">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Pages</h1>
|
||||
<p class="text-base-content/60">Create, edit, preview, and publish website pages.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.showModal()}>New page</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}
|
||||
<div class="alert alert-error mb-4">{form.message}</div>
|
||||
{/if}
|
||||
|
||||
<div class="overflow-x-auto rounded-box bg-base-100 shadow">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Slug</th><th>Title</th><th>Status</th><th class="text-right">Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each data.pages as page}
|
||||
<tr>
|
||||
<td class="font-mono">{page.slug}</td>
|
||||
<td>{page.title}</td>
|
||||
<td><span class="badge" class:badge-success={page.published}>{page.published ? 'Published' : 'Draft'}</span></td>
|
||||
<td class="flex justify-end gap-2">
|
||||
<a class="btn btn-sm" href={`/pages/${page.slug}`}>Edit</a>
|
||||
<a class="btn btn-sm" href={`${import.meta.env.VITE_PUBLIC_SITE_URL}/${page.slug === 'home' ? '' : page.slug}`} target="_blank">Preview</a>
|
||||
<form method="POST" action="?/toggle">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="published" value={page.published} />
|
||||
<button class="btn btn-sm btn-outline" type="submit">{page.published ? 'Unpublish' : 'Publish'}</button>
|
||||
</form>
|
||||
<form method="POST" action="?/delete" onsubmit={() => confirm('Delete this page?')}>
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<button class="btn btn-sm btn-error btn-outline" type="submit">Delete</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<dialog id="new-page" class="modal">
|
||||
<form class="modal-box" method="POST" action="?/create">
|
||||
<h2 class="text-2xl font-bold">Create page</h2>
|
||||
<label class="form-control w-full mt-4">
|
||||
<div class="label"><span class="label-text">Slug</span></div>
|
||||
<input class="input input-bordered w-full" name="slug" placeholder="about" required />
|
||||
</label>
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Title</span></div>
|
||||
<input class="input input-bordered w-full" name="title" placeholder="About" required />
|
||||
</label>
|
||||
<div class="modal-action">
|
||||
<button class="btn" type="button" onclick={() => (document.getElementById('new-page') as HTMLDialogElement)?.close()}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Create</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
30
app-admin/src/routes/pages/[slug]/+page.server.ts
Normal file
30
app-admin/src/routes/pages/[slug]/+page.server.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { fail, redirect } from '@sveltejs/kit';
|
||||
import { extractCategories, normalizeEvent } from '$lib/calendar';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
export const load: PageServerLoad = async ({ params, locals }) => {
|
||||
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`);
|
||||
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
|
||||
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
|
||||
const items = await locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ sort: 'name' })
|
||||
.then((records) => records.map(({ id, name, type }) => ({ id, name, type })))
|
||||
.catch(() => []);
|
||||
return { page, eventCategories, items };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
save: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id'));
|
||||
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-');
|
||||
const title = String(data.get('title') || '').trim();
|
||||
const blocks = JSON.parse(String(data.get('blocks') || '[]'));
|
||||
const publish = String(data.get('publish')) === 'true';
|
||||
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
|
||||
|
||||
await locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) });
|
||||
throw redirect(303, `/pages/${slug}`);
|
||||
}
|
||||
};
|
||||
104
app-admin/src/routes/pages/[slug]/+page.svelte
Normal file
104
app-admin/src/routes/pages/[slug]/+page.svelte
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
<script lang="ts">
|
||||
import BlockList from '$lib/admin/BlockList.svelte';
|
||||
import { blockLabels, blockTypes, createBlock } from '$lib/admin/blockDefaults';
|
||||
import BlockEditor from '$lib/admin/editors/BlockEditor.svelte';
|
||||
import type { ContentBlock } from '$lib/types';
|
||||
|
||||
let { data, form } = $props();
|
||||
let page = $state(data.page);
|
||||
let blocks = $state<ContentBlock[]>(structuredClone(data.page.blocks || []));
|
||||
let selectedId = $state(blocks[0]?.id || '');
|
||||
let previewMode = $state<'desktop' | 'mobile'>('desktop');
|
||||
let showPreview = $state(false);
|
||||
|
||||
let selectedBlock = $derived(blocks.find((block) => block.id === selectedId) || null);
|
||||
|
||||
function addBlock(type: keyof typeof blockLabels) {
|
||||
const block = createBlock(type);
|
||||
blocks = [...blocks, block];
|
||||
selectedId = block.id;
|
||||
}
|
||||
|
||||
function updateBlock(updated: ContentBlock) {
|
||||
blocks = blocks.map((block) => (block.id === updated.id ? updated : block));
|
||||
}
|
||||
|
||||
function deleteBlock(id: string) {
|
||||
blocks = blocks.filter((block) => block.id !== id);
|
||||
if (selectedId === id) selectedId = blocks[0]?.id || '';
|
||||
}
|
||||
|
||||
function moveBlock(from: number, to: number) {
|
||||
const copy = [...blocks];
|
||||
const [item] = copy.splice(from, 1);
|
||||
copy.splice(to, 0, item);
|
||||
blocks = copy;
|
||||
}
|
||||
|
||||
function openPreview() {
|
||||
sessionStorage.setItem('cms-preview-blocks', JSON.stringify(blocks));
|
||||
showPreview = true;
|
||||
}
|
||||
|
||||
function markPublish(event: MouseEvent) {
|
||||
const form = (event.currentTarget as HTMLButtonElement).form;
|
||||
const input = form?.querySelector('[name=publish]') as HTMLInputElement | null;
|
||||
if (input) input.value = 'true';
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Edit {page.title} | CMS</title></svelte:head>
|
||||
|
||||
<form method="POST" action="?/save" class="space-y-6">
|
||||
<input type="hidden" name="id" value={page.id} />
|
||||
<input type="hidden" name="blocks" value={JSON.stringify(blocks)} />
|
||||
<input type="hidden" name="publish" value="false" />
|
||||
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Edit page</h1>
|
||||
<p class="text-base-content/60">Manage blocks, draft previews, and publishing.</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button class="btn" type="button" onclick={openPreview}>Preview</button>
|
||||
<button class="btn btn-outline" type="submit">Save draft</button>
|
||||
<button class="btn btn-primary" type="submit" onclick={markPublish}>Publish</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="form-control w-full"><div class="label"><span class="label-text">Slug</span></div><input class="input input-bordered w-full" name="slug" bind:value={page.slug} /></label>
|
||||
<label class="form-control w-full"><div class="label"><span class="label-text">Title</span></div><input class="input input-bordered w-full" name="title" bind:value={page.title} /></label>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-[22rem_1fr]">
|
||||
<aside class="space-y-4">
|
||||
<div class="rounded-box bg-base-100 p-4 shadow">
|
||||
<div class="dropdown w-full">
|
||||
<button class="btn btn-primary w-full" type="button" tabindex="0">Add block</button>
|
||||
<ul class="menu dropdown-content z-10 mt-2 w-full rounded-box bg-base-100 p-2 shadow">
|
||||
{#each blockTypes as type}
|
||||
<li><button type="button" onclick={() => addBlock(type)}>{blockLabels[type]}</button></li>
|
||||
{/each}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<BlockList {blocks} {selectedId} onSelect={(id) => (selectedId = id)} onDelete={deleteBlock} onMove={moveBlock} />
|
||||
</aside>
|
||||
<BlockEditor block={selectedBlock} eventCategories={data.eventCategories || []} items={data.items || []} onChange={updateBlock} />
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{#if showPreview}
|
||||
<div class="fixed inset-0 z-50 bg-black/60 p-4">
|
||||
<div class="mx-auto flex h-full max-w-7xl flex-col rounded-box bg-base-100 p-4 shadow-xl">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<div class="join"><button class="btn join-item" class:btn-active={previewMode === 'desktop'} onclick={() => (previewMode = 'desktop')}>Desktop</button><button class="btn join-item" class:btn-active={previewMode === 'mobile'} onclick={() => (previewMode = 'mobile')}>Mobile</button></div>
|
||||
<button class="btn" onclick={() => (showPreview = false)}>Close</button>
|
||||
</div>
|
||||
<iframe class="mx-auto h-full rounded-box border" class:w-full={previewMode === 'desktop'} style={previewMode === 'mobile' ? 'width: 390px;' : ''} src="/preview" title="Preview"></iframe>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
25
app-admin/src/routes/preview/+page.svelte
Normal file
25
app-admin/src/routes/preview/+page.svelte
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import BlockRenderer from '$lib/blocks/BlockRenderer.svelte';
|
||||
import type { ContentBlock } from '$lib/types';
|
||||
|
||||
let blocks = $state<ContentBlock[]>([]);
|
||||
|
||||
onMount(() => {
|
||||
const raw = sessionStorage.getItem('cms-preview-blocks');
|
||||
if (raw) blocks = JSON.parse(raw);
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Preview</title>
|
||||
</svelte:head>
|
||||
|
||||
{#if blocks.length}
|
||||
<BlockRenderer {blocks} />
|
||||
{:else}
|
||||
<section class="mx-auto max-w-3xl px-6 py-20 text-center">
|
||||
<h1 class="text-4xl">No preview content</h1>
|
||||
<p class="mt-4 text-charcoal/65">Open preview from the page editor to view the current draft.</p>
|
||||
</section>
|
||||
{/if}
|
||||
96
app-admin/src/routes/slots/+page.server.ts
Normal file
96
app-admin/src/routes/slots/+page.server.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { fail } from '@sveltejs/kit';
|
||||
import type { createPocketBase } from '$lib/pb';
|
||||
import type { SlotStatus } from '$lib/types';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
type Pb = ReturnType<typeof createPocketBase>;
|
||||
|
||||
type SlotPayload =
|
||||
| { payload: { item: string; start: string; end: string; status: string; notes: string } }
|
||||
| { error: string };
|
||||
|
||||
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
|
||||
const itemId = String(data.get('item') || '').trim();
|
||||
const startValue = String(data.get('start') || '').trim();
|
||||
const status = String(data.get('status') || 'available').trim();
|
||||
const notes = String(data.get('notes') || '').trim();
|
||||
|
||||
if (!itemId || !startValue) return { error: 'Service and start are required.' };
|
||||
|
||||
const start = new Date(startValue);
|
||||
if (Number.isNaN(start.getTime())) return { error: 'Invalid start time.' };
|
||||
|
||||
let item: Record<string, any>;
|
||||
try {
|
||||
item = await pb.collection('items').getOne(itemId);
|
||||
} catch {
|
||||
return { error: 'Selected service was not found.' };
|
||||
}
|
||||
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' };
|
||||
|
||||
const duration = Number(item.duration) || 0;
|
||||
const end = new Date(start.getTime() + duration * 60_000);
|
||||
|
||||
return {
|
||||
payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), status, notes }
|
||||
};
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const itemRecords = await locals.pb
|
||||
.collection('items')
|
||||
.getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' })
|
||||
.catch(() => []);
|
||||
const items = itemRecords.map((record) => ({
|
||||
id: record.id,
|
||||
name: String(record.name || ''),
|
||||
duration: record.duration ?? 0
|
||||
}));
|
||||
|
||||
const slotRecords = await locals.pb
|
||||
.collection('slots')
|
||||
.getFullList({ sort: '-start', expand: 'item' })
|
||||
.catch(() => []);
|
||||
const slots = slotRecords.map((record) => ({
|
||||
id: record.id,
|
||||
item: String(record.item || ''),
|
||||
itemName: String(record.expand?.item?.name || 'Unknown service'),
|
||||
itemDuration: record.expand?.item?.duration ?? null,
|
||||
start: String(record.start || ''),
|
||||
end: record.end ? String(record.end) : '',
|
||||
status: String(record.status || 'available') as SlotStatus,
|
||||
heldUntil: record.heldUntil ? String(record.heldUntil) : '',
|
||||
order: record.order ? String(record.order) : '',
|
||||
notes: String(record.notes || '')
|
||||
}));
|
||||
|
||||
return { items, slots };
|
||||
};
|
||||
|
||||
export const actions: Actions = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const result = await slotPayload(data, locals.pb);
|
||||
if ('error' in result) return fail(400, { message: result.error });
|
||||
await locals.pb.collection('slots').create(result.payload);
|
||||
return { ok: true };
|
||||
},
|
||||
update: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Slot id is required.' });
|
||||
const result = await slotPayload(data, locals.pb);
|
||||
if ('error' in result) return fail(400, { message: result.error });
|
||||
await locals.pb.collection('slots').update(id, result.payload);
|
||||
return { ok: true };
|
||||
},
|
||||
delete: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const id = String(data.get('id') || '');
|
||||
if (!id) return fail(400, { message: 'Slot id is required.' });
|
||||
const record = await locals.pb.collection('slots').getOne(id).catch(() => null);
|
||||
if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted' });
|
||||
await locals.pb.collection('slots').delete(id);
|
||||
return { ok: true };
|
||||
}
|
||||
};
|
||||
161
app-admin/src/routes/slots/+page.svelte
Normal file
161
app-admin/src/routes/slots/+page.svelte
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
<script lang="ts">
|
||||
import { toDatetimeInput } from '$lib/calendar';
|
||||
|
||||
let { data, form } = $props();
|
||||
let items = $derived(data.items || []);
|
||||
let slots = $derived(
|
||||
[...(data.slots || [])].sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
|
||||
);
|
||||
let showEditor = $state(false);
|
||||
|
||||
type SlotDraft = {
|
||||
id: string;
|
||||
item: string;
|
||||
start: string;
|
||||
status: string;
|
||||
heldUntil: string;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
let draft = $state<SlotDraft>(emptyDraft());
|
||||
let action = $derived(draft.id ? '?/update' : '?/create');
|
||||
let isHeld = $derived(draft.status === 'held');
|
||||
let selectedItem = $derived(items.find((item) => item.id === draft.item));
|
||||
let endLabel = $derived.by(() => {
|
||||
if (!selectedItem || !draft.start) return '';
|
||||
const start = new Date(draft.start);
|
||||
if (Number.isNaN(start.getTime())) return '';
|
||||
const end = new Date(start.getTime() + (Number(selectedItem.duration) || 0) * 60_000);
|
||||
return `Ends at ${end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
|
||||
});
|
||||
|
||||
function emptyDraft(): SlotDraft {
|
||||
return { id: '', item: '', start: toDatetimeInput(new Date().toISOString()), status: 'available', heldUntil: '', notes: '' };
|
||||
}
|
||||
|
||||
function createSlot() {
|
||||
draft = emptyDraft();
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editSlot(slot: (typeof slots)[number]) {
|
||||
draft = {
|
||||
id: slot.id,
|
||||
item: slot.item,
|
||||
start: toDatetimeInput(slot.start),
|
||||
status: slot.status,
|
||||
heldUntil: slot.heldUntil,
|
||||
notes: slot.notes
|
||||
};
|
||||
showEditor = true;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>Slots | CMS</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end">
|
||||
<div>
|
||||
<h1 class="text-3xl font-bold">Slots</h1>
|
||||
<p class="text-base-content/60">Create bookable time slots for your services.</p>
|
||||
</div>
|
||||
<button class="btn btn-primary" type="button" onclick={() => createSlot()}>Create slot</button>
|
||||
</div>
|
||||
|
||||
{#if form?.message}<div class="alert alert-error">{form.message}</div>{/if}
|
||||
|
||||
<div class="rounded-box bg-base-100 p-5 shadow">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Service</th><th>Date</th><th>Duration</th><th>Status</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{#each slots as slot}
|
||||
<tr>
|
||||
<td><span class="font-semibold">{slot.itemName}</span></td>
|
||||
<td>{new Date(slot.start).toLocaleString()}</td>
|
||||
<td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td>
|
||||
<td>
|
||||
<span
|
||||
class="badge capitalize"
|
||||
class:badge-success={slot.status === 'available'}
|
||||
class:badge-warning={slot.status === 'held'}
|
||||
class:badge-info={slot.status === 'booked'}
|
||||
>{slot.status}</span>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} onclick={() => editSlot(slot)}>Edit</button>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showEditor}
|
||||
<div class="fixed inset-0 z-50 bg-black/50 p-4">
|
||||
<div class="mx-auto max-h-full max-w-2xl overflow-auto rounded-box bg-base-100 p-6 shadow-xl">
|
||||
<div class="mb-4 flex items-center justify-between gap-3">
|
||||
<h2 class="text-2xl font-bold">{draft.id ? 'Edit slot' : 'Create slot'}</h2>
|
||||
<button class="btn btn-ghost btn-sm" type="button" onclick={() => (showEditor = false)}>Close</button>
|
||||
</div>
|
||||
|
||||
<form method="POST" action={action} class="space-y-4">
|
||||
<input type="hidden" name="id" value={draft.id} />
|
||||
<input type="hidden" name="status" value={draft.status} />
|
||||
{#if isHeld}
|
||||
<input type="hidden" name="item" value={draft.item} />
|
||||
<input type="hidden" name="start" value={draft.start} />
|
||||
{/if}
|
||||
|
||||
{#if isHeld}
|
||||
<div class="alert alert-warning">
|
||||
This slot is currently held by a basket{draft.heldUntil ? ` (until ${new Date(draft.heldUntil).toLocaleString()})` : ''} — editing start/end is disabled.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Service</span></div>
|
||||
<select class="select select-bordered w-full" name="item" required disabled={isHeld} bind:value={draft.item}>
|
||||
<option value="" disabled>Select a service…</option>
|
||||
{#each items as item}
|
||||
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Start</span></div>
|
||||
<input
|
||||
class="input input-bordered w-full"
|
||||
type="datetime-local"
|
||||
name="start"
|
||||
required
|
||||
disabled={isHeld}
|
||||
value={draft.start}
|
||||
oninput={(e) => (draft = { ...draft, start: e.currentTarget.value })}
|
||||
/>
|
||||
</label>
|
||||
{#if endLabel}<p class="text-sm text-base-content/60">{endLabel}</p>{/if}
|
||||
|
||||
<label class="form-control w-full">
|
||||
<div class="label"><span class="label-text">Notes</span></div>
|
||||
<textarea class="textarea textarea-bordered" name="notes" bind:value={draft.notes}></textarea>
|
||||
</label>
|
||||
|
||||
<div class="flex justify-between gap-2 pt-2">
|
||||
{#if draft.id}
|
||||
<button class="btn btn-error" type="submit" formaction="?/delete">Delete</button>
|
||||
{:else}
|
||||
<span></span>
|
||||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
|
||||
<button class="btn btn-primary" type="submit">Save slot</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
Loading…
Add table
Add a link
Reference in a new issue