domaino/app-admin/src/routes/pages/[slug]/+page.server.ts
agent ff54adb00c 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
2026-10-06 10:46:24 +00:00

56 lines
2.4 KiB
TypeScript

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.' };
}
};