Admin polish: stability fixes, schema security, consistent UI + sidebar #1

Merged
reudy merged 21 commits from session/polish into main 2026-10-07 16:30:40 +02:00
11 changed files with 451 additions and 195 deletions
Showing only changes of commit ff54adb00c - Show all commits

View file

@ -0,0 +1,32 @@
import { fail } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
/**
* Human-readable message for a failed PocketBase call, including per-field
* validation errors (e.g. "slug: Must be unique.").
*/
export function pbErrorMessage(e: unknown, fallback: string): string {
if (e instanceof ClientResponseError) {
const fields = Object.entries((e.response?.data ?? {}) as Record<string, { message?: string }>)
.map(([field, detail]) => `${field}: ${detail?.message ?? 'invalid'}`)
.join('; ');
if (e.status === 404) return `${fallback} (not found — it may have been deleted).`;
if (fields) return `${fallback} ${fields}`;
if (e.status === 0) return `${fallback} The database is unreachable.`;
}
return fallback;
}
/**
* Run a PocketBase mutation inside a form action. On failure, log it and
* return `fail(400, { message })` so the page shows an error banner instead
* of SvelteKit's generic 500 page.
*/
export async function attempt<T>(fallback: string, fn: () => Promise<T>) {
try {
return { ok: true as const, value: await fn() };
} catch (e) {
console.error(`[action] ${fallback}`, e);
return { ok: false as const, failure: fail(400, { message: pbErrorMessage(e, fallback) }) };
}
}

View file

@ -0,0 +1,23 @@
import type PocketBase from 'pocketbase';
/** Lowercase, URL-safe slug: anything outside a-z, 0-9 and "-" becomes "-". */
export function normalizeSlug(value: FormDataEntryValue | null): string {
return String(value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '');
}
/**
* Whether another page already uses `slug`. The `pages` collection has no
* unique index on slug, so this is checked here; a duplicate would make one
* of the two pages unreachable.
*/
export async function slugTaken(pb: PocketBase, slug: string, exceptId = ''): Promise<boolean> {
const filter = exceptId
? pb.filter('slug = {:slug} && id != {:id}', { slug, id: exceptId })
: pb.filter('slug = {:slug}', { slug });
const existing = await pb.collection('pages').getList(1, 1, { filter, fields: 'id' });
return existing.totalItems > 0;
}

View file

@ -1,9 +1,10 @@
import { env } from '$env/dynamic/private';
import { defaultColors } from '$lib/types'; import { defaultColors } from '$lib/types';
import type { LayoutServerLoad } from './$types'; import type { LayoutServerLoad } from './$types';
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try { try {
const record = await pb.collection('globals').getFirstListItem(`key = "${key}"`); const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
return record.data || fallback; return record.data || fallback;
} catch { } catch {
return fallback; return fallback;
@ -12,5 +13,12 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
export const load: LayoutServerLoad = async ({ locals }) => { export const load: LayoutServerLoad = async ({ locals }) => {
const colors = await getGlobal(locals.pb, 'colors', defaultColors); const colors = await getGlobal(locals.pb, 'colors', defaultColors);
return { user: locals.user, colors }; return {
user: locals.user,
colors,
// Admin dates/times are entered and shown in the site's timezone, and
// prices in the shop currency — same settings the booking emails use.
timezone: env.SITE_TIMEZONE || 'Europe/Oslo',
currency: (env.STRIPE_CURRENCY || 'eur').toUpperCase()
};
}; };

View file

@ -1,5 +1,7 @@
import { env } from '$env/dynamic/private';
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar'; import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import { attempt } from '$lib/server/actions';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
function eventPayload(data: FormData) { function eventPayload(data: FormData) {
@ -7,11 +9,12 @@ function eventPayload(data: FormData) {
const start = String(data.get('start') || '').trim(); const start = String(data.get('start') || '').trim();
const end = String(data.get('end') || '').trim(); const end = String(data.get('end') || '').trim();
const name = String(data.get('name') || '').trim(); const name = String(data.get('name') || '').trim();
const timeZone = env.SITE_TIMEZONE || 'Europe/Oslo';
return { return {
name, name,
start: dateInputToPocketBase(start, allDay), start: dateInputToPocketBase(start, allDay, timeZone),
end: end ? dateInputToPocketBase(end, allDay) : null, end: end ? dateInputToPocketBase(end, allDay, timeZone) : null,
description: String(data.get('description') || '').trim(), description: String(data.get('description') || '').trim(),
color: String(data.get('color') || '#8a9a7b').trim(), color: String(data.get('color') || '#8a9a7b').trim(),
link: String(data.get('link') || '').trim(), link: String(data.get('link') || '').trim(),
@ -32,7 +35,9 @@ export const actions: Actions = {
const data = await request.formData(); const data = await request.formData();
const payload = eventPayload(data); const payload = eventPayload(data);
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').create(payload); if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' });
const result = await attempt('Could not create the event.', () => locals.pb.collection('events').create(payload));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
@ -41,14 +46,17 @@ export const actions: Actions = {
const payload = eventPayload(data); const payload = eventPayload(data);
if (!id) return fail(400, { message: 'Event id is required.' }); if (!id) return fail(400, { message: 'Event id is required.' });
if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' }); if (!payload.name || !payload.start) return fail(400, { message: 'Name and start are required.' });
await locals.pb.collection('events').update(id, payload); if (payload.end && payload.end < payload.start) return fail(400, { message: 'The end must be after the start.' });
const result = await attempt('Could not save the event.', () => locals.pb.collection('events').update(id, payload));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Event id is required.' }); if (!id) return fail(400, { message: 'Event id is required.' });
await locals.pb.collection('events').delete(id); const result = await attempt('Could not delete the event.', () => locals.pb.collection('events').delete(id));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -1,11 +1,21 @@
import { fail } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
import { attempt } from '$lib/server/actions';
import { defaultColors, defaultFooter, defaultHeader } from '$lib/types'; import { defaultColors, defaultFooter, defaultHeader } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
const SECTIONS = ['header', 'footer', 'colors'] as const;
async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) { async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
try { try {
return await pb.collection('globals').getFirstListItem(`key = "${key}"`); return await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
} catch { } catch (e) {
return await pb.collection('globals').create({ key, data: fallback }); // Only create the record when it genuinely doesn't exist — any other
// error (PocketBase down, auth) must not create duplicates.
if (e instanceof ClientResponseError && e.status === 404) {
return await pb.collection('globals').create({ key, data: fallback });
}
throw e;
} }
} }
@ -17,7 +27,7 @@ export const load: PageServerLoad = async ({ locals }) => {
]); ]);
// Fetch all pages for the home page selector // Fetch all pages for the home page selector
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' }); const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug', fields: 'id,slug,title' });
return { header, footer, colors, pages }; return { header, footer, colors, pages };
}; };
@ -25,7 +35,21 @@ export const load: PageServerLoad = async ({ locals }) => {
export const actions: Actions = { export const actions: Actions = {
save: async ({ request, locals }) => { save: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id')); const id = String(data.get('id') || '');
await locals.pb.collection('globals').update(id, { data: JSON.parse(String(data.get('data'))) }); const section = String(data.get('section') || '');
if (!id || !SECTIONS.includes(section as (typeof SECTIONS)[number])) {
return fail(400, { section, ok: false, message: 'Invalid request.' });
}
let value: unknown;
try {
value = JSON.parse(String(data.get('data') || ''));
} catch {
return fail(400, { section, ok: false, message: 'The settings could not be read. Nothing was saved.' });
}
const result = await attempt('Could not save.', () => locals.pb.collection('globals').update(id, { data: value }));
if (!result.ok) return fail(400, { section, ok: false, message: result.failure.data.message });
return { section, ok: true, message: 'Saved.' };
} }
}; };

View file

@ -1,5 +1,6 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb'; import { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
@ -51,8 +52,9 @@ export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const payload = itemPayload(data); const payload = itemPayload(data);
if (!payload.name || Number.isNaN(payload.price)) return fail(400, { message: 'Name and price are required.' }); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
await locals.pb.collection('items').create(payload); const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
@ -60,15 +62,17 @@ export const actions: Actions = {
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
const payload = itemPayload(data); const payload = itemPayload(data);
if (!id) return fail(400, { message: 'Item id is required.' }); 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.' }); if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
await locals.pb.collection('items').update(id, payload); const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Item id is required.' }); if (!id) return fail(400, { message: 'Item id is required.' });
await locals.pb.collection('items').delete(id); const result = await attempt('Could not delete the item — if it has slots or past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -3,38 +3,45 @@ import { sendOrderEmails, type EmailKind } from '$lib/server/email';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
// Sort by id, not 'created' — commerce collections were imported without // NOTE: there is no `created` field on orders (commerce collections were
// autodate fields. PocketBase ids are time-sortable ULIDs. // imported without autodate fields) and PocketBase ids are random, so
// '-id' is NOT chronological. See the polish report for the schema fix.
const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []); const records = await locals.pb.collection('orders').getFullList({ sort: '-id' }).catch(() => []);
const orders = []; // All lines in one request (previously one request per order).
for (const record of records) { const lineRecords = records.length
const lineRecords = await locals.pb ? await locals.pb
.collection('order_lines') .collection('order_lines')
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: record.id }) }) .getFullList({ sort: 'start' })
.catch(() => []); .catch(() => [])
: [];
orders.push({ const linesByOrder = new Map<string, typeof lineRecords>();
id: record.id, for (const line of lineRecords) {
email: String(record.email || ''), const list = linesByOrder.get(line.order) ?? [];
customerDetails: record.customerDetails || {}, list.push(line);
total: Number(record.total) || 0, linesByOrder.set(line.order, list);
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
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) : ''
}))
});
} }
const orders = records.map((record) => ({
id: record.id,
email: String(record.email || ''),
customerDetails: record.customerDetails || {},
total: Number(record.total) || 0,
status: String(record.status || 'pending'),
created: String(record.created || ''),
customerEmailSentAt: String(record.customerEmailSentAt || ''),
clientEmailSentAt: String(record.clientEmailSentAt || ''),
emailError: String(record.emailError || ''),
lines: (linesByOrder.get(record.id) ?? []).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 }; return { orders };
}; };

View file

@ -1,4 +1,6 @@
import { fail, redirect } from '@sveltejs/kit'; import { fail, redirect } from '@sveltejs/kit';
import { attempt } from '$lib/server/actions';
import { normalizeSlug, slugTaken } from '$lib/server/pages';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
@ -9,21 +11,29 @@ export const load: PageServerLoad = async ({ locals }) => {
export const actions: Actions = { export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-'); const slug = normalizeSlug(data.get('slug'));
const title = String(data.get('title') || '').trim(); const title = String(data.get('title') || '').trim();
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
if (await slugTaken(locals.pb, slug)) return fail(400, { message: `A page with the slug "${slug}" already exists.` });
await locals.pb.collection('pages').create({ slug, title, blocks: [], published: false }); const result = await attempt('Could not create the page.', () =>
locals.pb.collection('pages').create({ slug, title, blocks: [], published: false })
);
if (!result.ok) return result.failure;
throw redirect(303, `/pages/${slug}`); throw redirect(303, `/pages/${slug}`);
}, },
toggle: async ({ request, locals }) => { toggle: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
await locals.pb.collection('pages').update(String(data.get('id')), { const result = await attempt('Could not change the publish status.', () =>
published: String(data.get('published')) !== 'true' locals.pb.collection('pages').update(String(data.get('id')), {
}); published: String(data.get('published')) !== 'true'
})
);
if (!result.ok) return result.failure;
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
await locals.pb.collection('pages').delete(String(data.get('id'))); const result = await attempt('Could not delete the page.', () => locals.pb.collection('pages').delete(String(data.get('id'))));
if (!result.ok) return result.failure;
} }
}; };

View file

@ -1,9 +1,18 @@
import { fail, redirect } from '@sveltejs/kit'; import { error, fail, redirect } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
import { extractCategories, normalizeEvent } from '$lib/calendar'; import { extractCategories, normalizeEvent } from '$lib/calendar';
import { attempt } from '$lib/server/actions';
import { normalizeSlug, slugTaken } from '$lib/server/pages';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params, locals }) => { export const load: PageServerLoad = async ({ params, locals }) => {
const page = await locals.pb.collection('pages').getFirstListItem(`slug = "${params.slug}"`); const page = await locals.pb
.collection('pages')
.getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: params.slug }))
.catch((e) => {
if (e instanceof ClientResponseError && e.status === 404) throw error(404, `No page with the slug "${params.slug}".`);
throw e;
});
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []); const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
const eventCategories = extractCategories(events.map((event) => normalizeEvent(event))); const eventCategories = extractCategories(events.map((event) => normalizeEvent(event)));
const items = await locals.pb const items = await locals.pb
@ -15,16 +24,33 @@ export const load: PageServerLoad = async ({ params, locals }) => {
}; };
export const actions: Actions = { export const actions: Actions = {
save: async ({ request, locals }) => { save: async ({ params, request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id')); const id = String(data.get('id'));
const slug = String(data.get('slug') || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '-'); const slug = normalizeSlug(data.get('slug'));
const title = String(data.get('title') || '').trim(); const title = String(data.get('title') || '').trim();
const blocks = JSON.parse(String(data.get('blocks') || '[]')); const publish = data.get('intent') === 'publish';
const publish = String(data.get('publish')) === 'true';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' }); 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 } : {}) }); let blocks: unknown;
throw redirect(303, `/pages/${slug}`); try {
blocks = JSON.parse(String(data.get('blocks') || '[]'));
} catch {
return fail(400, { message: 'The block data could not be read. Nothing was saved.' });
}
if (!Array.isArray(blocks)) return fail(400, { message: 'The block data could not be read. Nothing was saved.' });
if (slug !== params.slug && (await slugTaken(locals.pb, slug, id))) {
return fail(400, { message: `A page with the slug "${slug}" already exists.` });
}
const result = await attempt('Could not save the page.', () =>
locals.pb.collection('pages').update(id, { slug, title, blocks, ...(publish ? { published: true } : {}) })
);
if (!result.ok) return result.failure;
// The URL contains the slug, so a rename has to navigate.
if (slug !== params.slug) throw redirect(303, `/pages/${slug}`);
return { ok: true, message: publish ? 'Saved and published.' : 'Draft saved.' };
} }
}; };

View file

@ -1,24 +1,37 @@
import { env } from '$env/dynamic/private';
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb'; import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import type { SlotStatus } from '$lib/types'; import type { SlotStatus } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
type SlotPayload = type SlotPayload =
| { payload: { item: string; start: string; end: string; status: string; notes: string } } | { payload: { item: string; start: string; end: string; notes: string } }
| { error: string }; | { error: string };
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */
function isHoldActive(slot: Record<string, any> | null) {
if (slot?.status !== 'held') return false;
const until = Date.parse(String(slot.heldUntil || '').replace(' ', 'T'));
return Number.isNaN(until) || until > Date.now();
}
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> { async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const itemId = String(data.get('item') || '').trim(); const itemId = String(data.get('item') || '').trim();
const startValue = String(data.get('start') || '').trim(); const startValue = String(data.get('start') || '').trim();
const status = String(data.get('status') || 'available').trim();
const notes = String(data.get('notes') || '').trim(); const notes = String(data.get('notes') || '').trim();
if (!itemId || !startValue) return { error: 'Service and start are required.' }; if (!itemId || !startValue) return { error: 'Service and start are required.' };
const start = new Date(startValue); // The form sends a wall-clock time in the site's timezone.
if (Number.isNaN(start.getTime())) return { error: 'Invalid start time.' }; const startIso = zonedInputToIso(startValue, siteTimezone());
if (!startIso) return { error: 'Invalid start time.' };
const start = new Date(startIso);
let item: Record<string, any>; let item: Record<string, any>;
try { try {
@ -31,9 +44,9 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const duration = Number(item.duration) || 0; const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000); const end = new Date(start.getTime() + duration * 60_000);
return { // Status is never taken from the form: it is owned by the booking flow
payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), status, notes } // (held by a basket, booked by a paid order). New slots start available.
}; return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } };
} }
export const load: PageServerLoad = async ({ locals }) => { export const load: PageServerLoad = async ({ locals }) => {
@ -49,7 +62,7 @@ export const load: PageServerLoad = async ({ locals }) => {
const slotRecords = await locals.pb const slotRecords = await locals.pb
.collection('slots') .collection('slots')
.getFullList({ sort: '-start', expand: 'item' }) .getFullList({ sort: 'start', expand: 'item' })
.catch(() => []); .catch(() => []);
const slots = slotRecords.map((record) => ({ const slots = slotRecords.map((record) => ({
id: record.id, id: record.id,
@ -72,16 +85,33 @@ export const actions: Actions = {
const data = await request.formData(); const data = await request.formData();
const result = await slotPayload(data, locals.pb); const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error }); if ('error' in result) return fail(400, { message: result.error });
await locals.pb.collection('slots').create(result.payload); const created = await attempt('Could not create the slot.', () =>
locals.pb.collection('slots').create({ ...result.payload, status: 'available' })
);
if (!created.ok) return created.failure;
return { ok: true }; return { ok: true };
}, },
update: async ({ request, locals }) => { update: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' }); 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 }); // Re-read the slot: the page may be stale, and a customer may have
await locals.pb.collection('slots').update(id, result.payload); // held or booked it since. Only notes can change while it's held.
const current = await locals.pb.collection('slots').getOne(id).catch(() => null);
if (!current) return fail(404, { message: 'This slot no longer exists.' });
if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' });
let patch: Record<string, string>;
if (isHoldActive(current)) {
patch = { notes: String(data.get('notes') || '').trim() };
} else {
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
patch = result.payload;
}
const updated = await attempt('Could not save the slot.', () => locals.pb.collection('slots').update(id, patch));
if (!updated.ok) return updated.failure;
return { ok: true }; return { ok: true };
}, },
delete: async ({ request, locals }) => { delete: async ({ request, locals }) => {
@ -89,8 +119,10 @@ export const actions: Actions = {
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' }); if (!id) return fail(400, { message: 'Slot id is required.' });
const record = await locals.pb.collection('slots').getOne(id).catch(() => null); 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' }); if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' });
await locals.pb.collection('slots').delete(id); if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' });
const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
if (!deleted.ok) return deleted.failure;
return { ok: true }; return { ok: true };
} }
}; };

View file

@ -34,14 +34,96 @@ export function toDatetimeInput(value?: string | null) {
return local.toISOString().slice(0, 16); return local.toISOString().slice(0, 16);
} }
export function dateInputToPocketBase(value: string, allDay = true) { /**
* Convert a form date value to PocketBase format. All-day dates are stored as
* UTC midnight of that calendar date. Timed values (`YYYY-MM-DDTHH:mm` from a
* datetime-local input) are wall-clock times in `timeZone` — NOT the server's
* zone, which is UTC in the container and silently shifted every save.
*/
export function dateInputToPocketBase(value: string, allDay = true, timeZone = 'UTC') {
if (!value) return ''; if (!value) return '';
if (!allDay && value.includes('T')) { if (!allDay && value.includes('T')) {
return new Date(value).toISOString(); return zonedInputToIso(value, timeZone);
} }
return `${value.slice(0, 10)} 00:00:00.000Z`; return `${value.slice(0, 10)} 00:00:00.000Z`;
} }
// ── Site-timezone helpers ──────────────────────────────────────────────
// Admin forms and listings work in the site's timezone (SITE_TIMEZONE), so
// what the admin types is what customers book, and the server render (UTC
// container) matches the browser render.
const LOCAL_INPUT_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/;
function zonedParts(date: Date, timeZone: string) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).formatToParts(date);
const get = (type: string) => parts.find((part) => part.type === type)?.value ?? '00';
return { year: get('year'), month: get('month'), day: get('day'), hour: get('hour'), minute: get('minute'), second: get('second') };
}
/** Milliseconds `timeZone` is ahead of UTC at instant `date`. */
function zoneOffsetMs(date: Date, timeZone: string) {
const p = zonedParts(date, timeZone);
const asUtc = Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour, +p.minute, +p.second);
return asUtc - Math.floor(date.getTime() / 1000) * 1000;
}
function parseInstant(value?: string | null) {
if (!value) return null;
const date = new Date(value.replace(' ', 'T'));
return Number.isNaN(date.getTime()) ? null : date;
}
/** `2026-10-08T10:00` as a wall-clock time in `timeZone` → ISO UTC string ('' if invalid). */
export function zonedInputToIso(value: string, timeZone: string) {
const m = LOCAL_INPUT_RE.exec(value);
if (!m) return '';
const wallClockAsUtc = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]);
let instant = wallClockAsUtc - zoneOffsetMs(new Date(wallClockAsUtc), timeZone);
// Re-check at the candidate instant in case a DST change lies in between.
const corrected = wallClockAsUtc - zoneOffsetMs(new Date(instant), timeZone);
if (corrected !== instant) instant = corrected;
return new Date(instant).toISOString();
}
/**
* A stored instant → `YYYY-MM-DDTHH:mm` in `timeZone`, for datetime-local
* inputs. Values that are already wall-clock input strings pass through; a
* bare date becomes midnight.
*/
export function toZonedDatetimeInput(value: string | null | undefined, timeZone: string) {
if (!value) return '';
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value)) return value;
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return `${value}T00:00`;
const date = parseInstant(value);
if (!date) return '';
const p = zonedParts(date, timeZone);
return `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}`;
}
/** "8 Oct 2026, 10:00" in `timeZone`. Fixed locale so SSR and browser agree. */
export function formatDateTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, dateStyle: 'medium', timeStyle: 'short' }).format(date);
}
/** "10:00" in `timeZone`. */
export function formatTime(value: string | null | undefined, timeZone: string) {
const date = parseInstant(value);
if (!date) return '';
return new Intl.DateTimeFormat('en-GB', { timeZone, timeStyle: 'short' }).format(date);
}
export function parseEventDate(value?: string | null) { export function parseEventDate(value?: string | null) {
if (!value) return null; if (!value) return null;
const datePart = value.slice(0, 10); const datePart = value.slice(0, 10);