diff --git a/app-admin/src/lib/server/actions.ts b/app-admin/src/lib/server/actions.ts new file mode 100644 index 0000000..7138907 --- /dev/null +++ b/app-admin/src/lib/server/actions.ts @@ -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) + .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(fallback: string, fn: () => Promise) { + 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) }) }; + } +} diff --git a/app-admin/src/lib/server/pages.ts b/app-admin/src/lib/server/pages.ts new file mode 100644 index 0000000..ac3b082 --- /dev/null +++ b/app-admin/src/lib/server/pages.ts @@ -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 { + 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; +} diff --git a/app-admin/src/routes/+layout.server.ts b/app-admin/src/routes/+layout.server.ts index 0bbf0b3..09856fa 100644 --- a/app-admin/src/routes/+layout.server.ts +++ b/app-admin/src/routes/+layout.server.ts @@ -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() + }; }; diff --git a/app-admin/src/routes/calendar/+page.server.ts b/app-admin/src/routes/calendar/+page.server.ts index fa5644a..308f6a4 100644 --- a/app-admin/src/routes/calendar/+page.server.ts +++ b/app-admin/src/routes/calendar/+page.server.ts @@ -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 }; + } +}; diff --git a/app-admin/src/routes/globals/+page.server.ts b/app-admin/src/routes/globals/+page.server.ts index 3a2349f..957aa84 100644 --- a/app-admin/src/routes/globals/+page.server.ts +++ b/app-admin/src/routes/globals/+page.server.ts @@ -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.' }; + } +}; diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts index c5f09be..0de226c 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -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 }; } }; diff --git a/app-admin/src/routes/orders/+page.server.ts b/app-admin/src/routes/orders/+page.server.ts index 91b97fa..27c8c0e 100644 --- a/app-admin/src/routes/orders/+page.server.ts +++ b/app-admin/src/routes/orders/+page.server.ts @@ -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(); + 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 }; }; diff --git a/app-admin/src/routes/pages/+page.server.ts b/app-admin/src/routes/pages/+page.server.ts index 43eb7b0..e503d6d 100644 --- a/app-admin/src/routes/pages/+page.server.ts +++ b/app-admin/src/routes/pages/+page.server.ts @@ -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; + } +}; diff --git a/app-admin/src/routes/pages/[slug]/+page.server.ts b/app-admin/src/routes/pages/[slug]/+page.server.ts index 6b4cb0a..2880646 100644 --- a/app-admin/src/routes/pages/[slug]/+page.server.ts +++ b/app-admin/src/routes/pages/[slug]/+page.server.ts @@ -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.' }; + } +}; diff --git a/app-admin/src/routes/slots/+page.server.ts b/app-admin/src/routes/slots/+page.server.ts index ee3e90c..d617cfb 100644 --- a/app-admin/src/routes/slots/+page.server.ts +++ b/app-admin/src/routes/slots/+page.server.ts @@ -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; 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 | 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 { 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; try { @@ -31,9 +44,9 @@ async function slotPayload(data: FormData, pb: Pb): Promise { 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; + 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 }; } }; diff --git a/packages/shared/src/calendar.ts b/packages/shared/src/calendar.ts index 6041972..ab32bd2 100644 --- a/packages/shared/src/calendar.ts +++ b/packages/shared/src/calendar.ts @@ -34,14 +34,96 @@ export function toDatetimeInput(value?: string | null) { 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 (!allDay && value.includes('T')) { - return new Date(value).toISOString(); + return zonedInputToIso(value, timeZone); } 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) { if (!value) return null; const datePart = value.slice(0, 10);