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
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