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:
parent
52d7a5e3e2
commit
ff54adb00c
11 changed files with 451 additions and 195 deletions
|
|
@ -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 };
|
||||
}
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue