Admin server actions: handled errors, timezone-correct times, safer writes

- Slot and timed-event times were parsed in the server's zone (UTC in the
  container) while the form sent the admin's local wall-clock time, so every
  save shifted them by the UTC offset (10:00 → 12:00 in Oslo, again on each
  save). Inputs are now interpreted in SITE_TIMEZONE (shared helpers with
  DST handling), the same setting the booking emails use.
- PocketBase failures in actions (duplicate, validation, relation in use,
  DB down) now return a readable `fail()` instead of a 500 page.
- Pages: 404 for unknown slugs, slug filters built with pb.filter (quotes
  broke them), duplicate-slug check on create/rename (no unique index),
  invalid block JSON rejected instead of throwing; save returns a result so
  the editor can stay on the page.
- Globals: only create a missing record on 404 — any other error (DB
  hiccup) used to create duplicates; save reports success/failure.
- Slots: status is never taken from the form; re-read before update so a
  slot booked or held since the page loaded isn't overwritten; don't delete
  actively held slots.
- Orders: load all order lines in one request instead of one per order.
- Layout exposes site timezone and shop currency for display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 10:46:24 +00:00
parent 52d7a5e3e2
commit ff54adb00c
11 changed files with 451 additions and 195 deletions

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 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}"`);
const record = await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
return record.data || fallback;
} catch {
return fallback;
@ -12,5 +13,12 @@ async function getGlobal(pb: App.Locals['pb'], key: string, fallback: unknown) {
export const load: LayoutServerLoad = async ({ locals }) => {
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,54 +1,62 @@
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 };
}
};
import { env } from '$env/dynamic/private';
import { fail } from '@sveltejs/kit';
import { dateInputToPocketBase, normalizeCategories, normalizeEvent } from '$lib/calendar';
import { attempt } from '$lib/server/actions';
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();
const timeZone = env.SITE_TIMEZONE || 'Europe/Oslo';
return {
name,
start: dateInputToPocketBase(start, allDay, timeZone),
end: end ? dateInputToPocketBase(end, allDay, timeZone) : 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.' });
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 };
},
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.' });
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 };
},
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.' });
const result = await attempt('Could not delete the event.', () => locals.pb.collection('events').delete(id));
if (!result.ok) return result.failure;
return { ok: true };
}
};

View file

@ -1,31 +1,55 @@
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'))) });
}
};
import { fail } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
import { attempt } from '$lib/server/actions';
import { defaultColors, defaultFooter, defaultHeader } from '$lib/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) {
try {
return await pb.collection('globals').getFirstListItem(pb.filter('key = {:key}', { key }));
} catch (e) {
// 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;
}
}
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', fields: 'id,slug,title' });
return { header, footer, colors, pages };
};
export const actions: Actions = {
save: async ({ request, locals }) => {
const data = await request.formData();
const id = String(data.get('id') || '');
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 { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import type { ItemRecord, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
@ -51,8 +52,9 @@ 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);
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload));
if (!result.ok) return result.failure;
return { ok: true };
},
update: async ({ request, locals }) => {
@ -60,15 +62,17 @@ export const actions: Actions = {
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);
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' });
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 };
},
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);
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 };
}
};

View file

@ -3,38 +3,45 @@ import { sendOrderEmails, type EmailKind } from '$lib/server/email';
import type { Actions, 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.
// NOTE: there is no `created` field on orders (commerce collections were
// 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 orders = [];
for (const record of records) {
const lineRecords = await locals.pb
.collection('order_lines')
.getFullList({ filter: locals.pb.filter('order = {:id}', { id: 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 || ''),
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) : ''
}))
});
// All lines in one request (previously one request per order).
const lineRecords = records.length
? await locals.pb
.collection('order_lines')
.getFullList({ sort: 'start' })
.catch(() => [])
: [];
const linesByOrder = new Map<string, typeof lineRecords>();
for (const line of lineRecords) {
const list = linesByOrder.get(line.order) ?? [];
list.push(line);
linesByOrder.set(line.order, list);
}
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 };
};

View file

@ -1,29 +1,39 @@
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')));
}
};
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';
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 = normalizeSlug(data.get('slug'));
const title = String(data.get('title') || '').trim();
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.` });
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}`);
},
toggle: async ({ request, locals }) => {
const data = await request.formData();
const result = await attempt('Could not change the publish status.', () =>
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 }) => {
const data = await request.formData();
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,30 +1,56 @@
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}`);
}
};
import { error, fail, redirect } from '@sveltejs/kit';
import { ClientResponseError } from 'pocketbase';
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';
export const load: PageServerLoad = async ({ params, locals }) => {
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 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 ({ params, request, locals }) => {
const data = await request.formData();
const id = String(data.get('id'));
const slug = normalizeSlug(data.get('slug'));
const title = String(data.get('title') || '').trim();
const publish = data.get('intent') === 'publish';
if (!slug || !title) return fail(400, { message: 'Slug and title are required.' });
let blocks: unknown;
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 { zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
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 } }
| { payload: { item: string; start: string; end: string; notes: 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> {
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.' };
// The form sends a wall-clock time in the site's timezone.
const startIso = zonedInputToIso(startValue, siteTimezone());
if (!startIso) return { error: 'Invalid start time.' };
const start = new Date(startIso);
let item: Record<string, any>;
try {
@ -31,9 +44,9 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
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 }
};
// Status is never taken from the form: it is owned by the booking flow
// (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 }) => {
@ -49,7 +62,7 @@ export const load: PageServerLoad = async ({ locals }) => {
const slotRecords = await locals.pb
.collection('slots')
.getFullList({ sort: '-start', expand: 'item' })
.getFullList({ sort: 'start', expand: 'item' })
.catch(() => []);
const slots = slotRecords.map((record) => ({
id: record.id,
@ -72,16 +85,33 @@ export const actions: Actions = {
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);
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 };
},
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);
// Re-read the slot: the page may be stale, and a customer may have
// 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 };
},
delete: async ({ request, locals }) => {
@ -89,8 +119,10 @@ export const actions: Actions = {
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);
if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' });
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 };
}
};