Services with several lengths; slots become time windows #6

Merged
reudy merged 7 commits from session/change-slots-behavior into main 2026-10-25 22:16:35 +01:00
12 changed files with 667 additions and 329 deletions
Showing only changes of commit 636b59c706 - Show all commits

View file

@ -26,9 +26,9 @@
<p class="font-semibold">Nothing to {deleting ? 'delete' : 'create'}.</p> <p class="font-semibold">Nothing to {deleting ? 'delete' : 'create'}.</p>
{/if} {/if}
<ul class="mt-1 list-inside list-disc text-base-content/70 empty:hidden"> <ul class="mt-1 list-inside list-disc text-base-content/70 empty:hidden">
{#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap a slot of the same service.</li>{/if} {#if preview.skippedOverlap}<li>{plural(preview.skippedOverlap, 'slot')} skipped — it would overlap another window, or a session of the same service.</li>{/if}
{#if preview.skippedPast}<li>{plural(preview.skippedPast, 'slot')} skipped — in the past.</li>{/if} {#if preview.skippedPast}<li>{plural(preview.skippedPast, 'slot')} skipped — in the past.</li>{/if}
{#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — booked, or in a customer’s basket right now.</li>{/if} {#if preview.kept}<li>{plural(preview.kept, 'slot')} kept — something in it is booked, or in a customer’s basket right now.</li>{/if}
</ul> </ul>
</div> </div>
{/if} {/if}

View file

@ -33,7 +33,7 @@
<Modal bind:open title="Clear slots" wide> <Modal bind:open title="Clear slots" wide>
<form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1"> <form method="POST" action="?/clear" use:enhance={bulk.submit} class="space-y-1">
<p class="text-sm text-base-content/70">Delete the free slots in a date range. Booked slots, and slots in a customer’s basket right now, are always kept.</p> <p class="text-sm text-base-content/70">Delete the windows and group sessions in a date range that have nothing booked. Slots with a booking, or with a time in a customer’s basket right now, are always kept.</p>
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
@ -49,7 +49,7 @@
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Services</span> <span class="fieldset-legend">Services</span>
<select class="select w-full" name="item" bind:value={draft.item}> <select class="select w-full" name="item" bind:value={draft.item}>
<option value="">All services</option> <option value="">All slots</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each} {#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select> </select>
</label> </label>

View file

@ -58,7 +58,7 @@
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Services</span> <span class="fieldset-legend">Services</span>
<select class="select w-full" name="item" bind:value={draft.item}> <select class="select w-full" name="item" bind:value={draft.item}>
<option value="">All services</option> <option value="">All slots</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each} {#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select> </select>
</label> </label>

View file

@ -2,11 +2,14 @@
import { untrack } from 'svelte'; import { untrack } from 'svelte';
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import { WEEKDAYS, addDaysToKey, startTimesInWindows, type TimeWindow } from '$lib/slots'; import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import { START_TIMES_HINTS, START_TIMES_LABELS, WEEKDAYS, addDaysToKey, startTimesInWindows, timeToMinutes, type TimeWindow } from '$lib/slots';
import type { ItemDuration, SlotKind, StartTimesMode } from '$lib/types';
import { formatDuration } from '$shared/items';
import BulkActions from './BulkActions.svelte'; import BulkActions from './BulkActions.svelte';
import { bulkForm } from './bulkForm.svelte'; import { bulkForm } from './bulkForm.svelte';
type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number }; type Service = { id: string; name: string; durations: ItemDuration[]; bufferMinutes: number; capacity: number };
let { let {
open = $bindable(false), open = $bindable(false),
@ -17,14 +20,20 @@
// Kept between openings, so a second run starts from the last settings. // Kept between openings, so a second run starts from the last settings.
let draft = $state({ let draft = $state({
item: '', kind: 'window' as SlotKind,
fromDate: '', fromDate: '',
toDate: '', toDate: '',
weekdays: [1, 2, 3, 4, 5], weekdays: [1, 2, 3, 4, 5],
windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[], windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[],
notes: '',
// windows
items: [] as string[],
startTimes: 'grid' as StartTimesMode,
// group sessions
item: '',
minutes: '',
bufferMinutes: '', bufferMinutes: '',
capacity: '', capacity: ''
notes: ''
}); });
const bulk = bulkForm( const bulk = bulkForm(
@ -33,11 +42,14 @@
); );
let service = $derived(items.find((item) => item.id === draft.item)); let service = $derived(items.find((item) => item.id === draft.item));
let startTimes = $derived( let sessionTimes = $derived(
service ? startTimesInWindows(draft.windows, service.duration, Number(draft.bufferMinutes) || 0) : [] service && draft.minutes ? startTimesInWindows(draft.windows, Number(draft.minutes), Number(draft.bufferMinutes) || 0) : []
);
let windowHours = $derived(
draft.windows.reduce((sum, w) => sum + Math.max(0, (timeToMinutes(w.to) ?? 0) - (timeToMinutes(w.from) ?? 0)), 0) / 60
); );
// Each opening starts without a stale preview; the first one also fills in dates. // Each opening starts without a stale preview; the first one also fills in dates and services.
$effect(() => { $effect(() => {
if (!open) return; if (!open) return;
untrack(() => { untrack(() => {
@ -45,6 +57,9 @@
if (!draft.fromDate) { if (!draft.fromDate) {
draft.fromDate = today; draft.fromDate = today;
draft.toDate = addDaysToKey(today, 27); draft.toDate = addDaysToKey(today, 27);
// One-to-one services by default; group classes get sessions.
const oneToOne = items.filter((item) => item.capacity <= 1).map((item) => item.id);
draft.items = oneToOne.length ? oneToOne : items.map((item) => item.id);
} }
}); });
}); });
@ -53,6 +68,7 @@
draft.item = id; draft.item = id;
// The service's own get-ready time and places are the defaults; both can be overridden here. // The service's own get-ready time and places are the defaults; both can be overridden here.
const item = items.find((item) => item.id === id); const item = items.find((item) => item.id === id);
draft.minutes = item?.durations[0] ? String(item.durations[0].minutes) : '';
draft.bufferMinutes = String(item?.bufferMinutes ?? 0); draft.bufferMinutes = String(item?.bufferMinutes ?? 0);
draft.capacity = String(item?.capacity ?? 1); draft.capacity = String(item?.capacity ?? 1);
} }
@ -65,15 +81,15 @@
<Modal bind:open title="Generate slots" wide> <Modal bind:open title="Generate slots" wide>
<form method="POST" action="?/generate" use:enhance={bulk.submit} class="space-y-1"> <form method="POST" action="?/generate" use:enhance={bulk.submit} class="space-y-1">
<label class="fieldset"> <input type="hidden" name="kind" value={draft.kind} />
<span class="fieldset-legend">Service</span> <SegmentedControl
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}> label="Create"
<option value="" disabled>Select a service…</option> class="mb-2"
{#each items as item (item.id)} options={['window', 'session']}
<option value={item.id}>{item.name} ({item.duration} min)</option> value={draft.kind}
{/each} formatLabel={(v) => (v === 'window' ? 'Windows' : 'Group sessions')}
</select> onChange={(v) => (draft.kind = v as SlotKind)}
</label> />
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
@ -96,7 +112,7 @@
</div> </div>
<div class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Opening hours ({timezone})</span> <span class="fieldset-legend">{draft.kind === 'window' ? 'Windows each day' : 'Hours for sessions'} ({timezone})</span>
<div class="space-y-2"> <div class="space-y-2">
{#each draft.windows as window, i} {#each draft.windows as window, i}
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
@ -112,27 +128,70 @@
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addWindow}>+ Add hours (e.g. after a lunch break)</button> <button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addWindow}>+ Add hours (e.g. after a lunch break)</button>
</div> </div>
<div class="grid gap-x-4 md:grid-cols-2"> {#if draft.kind === 'window'}
<label class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span> <span class="fieldset-legend">Services that can be booked</span>
<input class="input w-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} /> <div class="grid gap-1 sm:grid-cols-2">
<span class="label">Gap after each appointment. Defaults to the service’s own.</span> {#each items as item (item.id)}
</label> <label class="label cursor-pointer gap-2 text-base-content">
<label class="fieldset"> <input class="checkbox checkbox-sm" type="checkbox" name="items" value={item.id} bind:group={draft.items} />
<span class="fieldset-legend">Places per slot</span> {item.name}
<input class="input w-32" type="number" min="1" max="500" step="1" name="capacity" bind:value={draft.capacity} /> </label>
<span class="label">More than 1 for a group session. Defaults to the service’s own.</span> {/each}
</label> </div>
</div> </div>
<div class="fieldset">
{#if service} <input type="hidden" name="startTimes" value={draft.startTimes} />
<SegmentedControl
label="Start times"
options={['grid', 'edges']}
value={draft.startTimes}
formatLabel={(v) => START_TIMES_LABELS[v as StartTimesMode]}
onChange={(v) => (draft.startTimes = v as StartTimesMode)}
/>
<span class="label whitespace-normal">{START_TIMES_HINTS[draft.startTimes]}</span>
</div>
<p class="rounded-box bg-base-200 px-4 py-2 text-sm"> <p class="rounded-box bg-base-200 px-4 py-2 text-sm">
{#if startTimes.length} {draft.windows.length} window{draft.windows.length === 1 ? '' : 's'} per chosen day, {windowHours} hours in total.
<span class="font-semibold">{startTimes.length} per day:</span> {startTimes.join(', ')}
{:else}
No {service.duration}-minute appointment fits in these hours.
{/if}
</p> </p>
{:else}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required value={draft.item} onchange={(e) => selectService(e.currentTarget.value)}>
<option value="" disabled>Select a service…</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Length</span>
<select class="select w-full" name="minutes" required disabled={!service} bind:value={draft.minutes}>
{#each service?.durations ?? [] as duration (duration.minutes)}
<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>
{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span>
<input class="input w-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each session. Defaults to the service’s own.</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Places per session</span>
<input class="input w-32" type="number" min="1" max="500" step="1" name="capacity" bind:value={draft.capacity} />
<span class="label">Defaults to the service’s own.</span>
</label>
</div>
{#if service && draft.minutes}
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
{#if sessionTimes.length}
<span class="font-semibold">{sessionTimes.length} per day:</span> {sessionTimes.join(', ')}
{:else}
No {formatDuration(Number(draft.minutes))} session fits in these hours.
{/if}
</p>
{/if}
{/if} {/if}
<label class="fieldset"> <label class="fieldset">

View file

@ -1,7 +1,7 @@
// Server helpers for the /slots page. Planning is pure and lives in // Server helpers for the /slots page. Planning is pure and lives in
// $shared/slots; this file does the PocketBase reads/writes around it. // $shared/slots; this file does the PocketBase reads/writes around it.
import type { SlotDetail } from '$lib/slots'; import type { SlotBooking, SlotDetail } from '$lib/slots';
import type { createPocketBase } from '$lib/pb'; import type { createPocketBase } from '$lib/pb';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
@ -10,21 +10,23 @@ type Pb = ReturnType<typeof createPocketBase>;
const WRITE_CONCURRENCY = 5; const WRITE_CONCURRENCY = 5;
/** /**
* Slots with their places and blocking, from the shop hook — the same * Slots with what's booked in them, from the shop hook — the same
* availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js). * availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js).
* Either slots starting in `[from, to)` (optionally one service) or one slot by id. * Either slots starting in `[from, to)` (optionally those offering one
* service) or one slot by id; `bookings` are all booked/held times starting
* in that range (for one slot: around its start).
*/ */
export async function loadSlotDetails(pb: Pb, query: { from: string; to: string; item?: string } | { id: string }) { export async function loadSlotDetails(pb: Pb, query: { from: string; to: string; item?: string } | { id: string }) {
const { slots } = await pb.send<{ slots: SlotDetail[] }>('/api/shop/slots', { return pb.send<{ slots: SlotDetail[]; bookings: SlotBooking[] }>('/api/shop/slots', {
query: { detail: 1, ...query }, query: { detail: 1, ...query },
requestKey: null requestKey: null
}); });
return slots;
} }
/** One slot's details, or null if it doesn't exist (any other failure throws). */ /** One slot's details and its own bookings, or null if it doesn't exist (any other failure throws). */
export async function loadSlotDetail(pb: Pb, id: string) { export async function loadSlotDetail(pb: Pb, id: string) {
return (await loadSlotDetails(pb, { id }))[0] ?? null; const { slots, bookings } = await loadSlotDetails(pb, { id });
return slots[0] ? { ...slots[0], bookings: bookings.filter((b) => b.slot === id) } : null;
} }
export const seatsTaken = (slot: Pick<SlotDetail, 'booked' | 'held'>) => slot.booked + slot.held; export const seatsTaken = (slot: Pick<SlotDetail, 'booked' | 'held'>) => slot.booked + slot.held;

View file

@ -1,5 +1,6 @@
import { error, fail, redirect } from '@sveltejs/kit'; import { error, fail, redirect } from '@sveltejs/kit';
import { emailTemplateMeta, isEmailTemplateKey } from '$lib/email'; import { emailTemplateMeta, isEmailTemplateKey } from '$lib/email';
import { parseDurations } from '$shared/items';
import { isEmailConfigured, loadEmailSettings, loadEmailTemplate, sendTestEmail } from '$lib/server/email'; import { isEmailConfigured, loadEmailSettings, loadEmailTemplate, sendTestEmail } from '$lib/server/email';
import type { EmailBlock } from '$lib/types'; import type { EmailBlock } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
@ -20,7 +21,10 @@ async function findSampleService(pb: App.Locals['pb']) {
return pb return pb
.collection('items') .collection('items')
.getFirstListItem("type = 'item_with_time' && active = true", { sort: 'name' }) .getFirstListItem("type = 'item_with_time' && active = true", { sort: 'name' })
.then((item) => ({ name: String(item.name), price: Number(item.price) || 0, duration: Number(item.duration) || null })) .then((item) => {
const duration = parseDurations(item.durations)[0];
return { name: String(item.name), price: duration?.price ?? (Number(item.price) || 0), duration: duration?.minutes ?? null };
})
.catch(() => undefined); .catch(() => undefined);
} }

View file

@ -1,49 +1,68 @@
import { fail } from '@sveltejs/kit'; import { fail } from '@sveltejs/kit';
import { getFileUrl } from '$lib/pb';
import { attempt } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import type { ItemRecord, ItemType } from '$lib/types'; import { mapItemRecord } from '$shared/server/shop';
import type { ItemDuration, ItemType } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
/** Longest bookable length, in minutes (a booking must fit in one day's window). */
const MAX_DURATION_MINUTES = 12 * 60;
/** A service's lengths and prices from the form's `durationMinutes`/`durationPrice` rows (empty rows are skipped). */
function parseDurationRows(data: FormData): ItemDuration[] | { error: string } {
const minutes = data.getAll('durationMinutes').map((v) => String(v).trim());
const prices = data.getAll('durationPrice').map((v) => String(v).trim());
const durations: ItemDuration[] = [];
for (let i = 0; i < minutes.length; i++) {
if (minutes[i] === '' && (prices[i] ?? '') === '') continue;
const length = Number(minutes[i]);
const price = Number(prices[i]);
if (!Number.isInteger(length) || length < 5 || length > MAX_DURATION_MINUTES) return { error: `Each length must be a whole number of minutes from 5 to ${MAX_DURATION_MINUTES}.` };
if (prices[i] === '' || !Number.isFinite(price) || price < 0) return { error: `Give the ${length}-minute length a price (0 or more).` };
if (durations.some((d) => d.minutes === length)) return { error: `${length} minutes is listed twice.` };
durations.push({ minutes: length, price });
}
if (!durations.length) return { error: 'Add at least one length with its price.' };
return durations.sort((a, b) => a.minutes - b.minutes);
}
function itemPayload(data: FormData) { function itemPayload(data: FormData) {
const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item'; const type: ItemType = String(data.get('type')) === 'item_with_time' ? 'item_with_time' : 'item';
const name = String(data.get('name') || '').trim();
if (!name) return { error: 'Name is required.' };
const rawStock = String(data.get('stock') ?? '').trim(); const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim(); const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const rawCapacity = String(data.get('capacity') ?? '').trim(); const rawCapacity = String(data.get('capacity') ?? '').trim();
let price: number;
let durations: ItemDuration[] = [];
if (type === 'item_with_time') {
const parsed = parseDurationRows(data);
if ('error' in parsed) return parsed;
durations = parsed;
// Kept as the lowest duration price: what "from …" and old readers show.
price = Math.min(...durations.map((d) => d.price));
} else {
price = parseFloat(String(data.get('price') || ''));
if (Number.isNaN(price) || price < 0) return { error: 'A valid price is required.' };
}
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null; const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null; const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null; const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null;
return { return {
name: String(data.get('name') || '').trim(), payload: {
description: String(data.get('description') || '').trim(), name,
price: parseFloat(String(data.get('price') || '')), description: String(data.get('description') || '').trim(),
image: String(data.get('image') || '').trim(), price,
type, image: String(data.get('image') || '').trim(),
stock: Number.isNaN(stock) ? null : stock, type,
duration: Number.isNaN(duration) ? null : duration, stock: Number.isNaN(stock) ? null : stock,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, durations,
capacity: Number.isNaN(capacity) ? null : capacity, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
active: String(data.get('active')) === 'true' capacity: Number.isNaN(capacity) ? null : capacity,
}; active: String(data.get('active')) === 'true'
} }
function normalizeItem(record: Record<string, any>): ItemRecord {
const media = record.expand?.image;
return {
id: record.id,
name: String(record.name || ''),
description: String(record.description || ''),
price: Number(record.price) || 0,
image: String(record.image || ''),
imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
type: record.type === 'item_with_time' ? 'item_with_time' : 'item',
stock: record.stock ?? null,
duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false
}; };
} }
@ -52,34 +71,32 @@ export const load: PageServerLoad = async ({ locals }) => {
.collection('items') .collection('items')
.getFullList({ sort: 'name', expand: 'image' }) .getFullList({ sort: 'name', expand: 'image' })
.catch(() => []); .catch(() => []);
const items = records.map((record) => normalizeItem(record)); return { items: records.map(mapItemRecord) };
return { items };
}; };
export const actions: Actions = { export const actions: Actions = {
create: async ({ request, locals }) => { create: async ({ request, locals }) => {
const data = await request.formData(); const result = itemPayload(await request.formData());
const payload = itemPayload(data); if ('error' in result) return fail(400, { message: result.error });
if (!payload.name || Number.isNaN(payload.price) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); const created = await attempt('Could not create the item.', () => locals.pb.collection('items').create(result.payload));
const result = await attempt('Could not create the item.', () => locals.pb.collection('items').create(payload)); if (!created.ok) return created.failure;
if (!result.ok) return result.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') || '');
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) || payload.price < 0) return fail(400, { message: 'Name and a valid price are required.' }); const result = itemPayload(data);
const result = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, payload)); if ('error' in result) return fail(400, { message: result.error });
if (!result.ok) return result.failure; const updated = await attempt('Could not save the item.', () => locals.pb.collection('items').update(id, result.payload));
if (!updated.ok) return updated.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.' });
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)); const result = await attempt('Could not delete the item — if it has past orders, switch it to inactive instead.', () => locals.pb.collection('items').delete(id));
if (!result.ok) return result.failure; if (!result.ok) return result.failure;
return { ok: true }; return { ok: true };
} }

View file

@ -3,6 +3,7 @@
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import type { ItemRecord, ItemType } from '$lib/types'; import type { ItemRecord, ItemType } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
@ -20,7 +21,8 @@
imageUrl: string; imageUrl: string;
type: ItemType; type: ItemType;
stock: string; stock: string;
duration: string; /** Service lengths and prices, as typed (one form row each). */
durations: { minutes: string; price: string }[];
bufferMinutes: string; bufferMinutes: string;
capacity: string; capacity: string;
active: boolean; active: boolean;
@ -32,7 +34,17 @@
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency })); let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft { function emptyDraft(): ItemDraft {
return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true }; return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', durations: [{ minutes: '60', price: '' }], bufferMinutes: '', capacity: '', active: true };
}
function addDuration() {
const last = Number(draft.durations.at(-1)?.minutes) || 0;
draft.durations.push({ minutes: last ? String(last + 30) : '60', price: '' });
}
/** "1 hour / 2 hours" for the table. */
function durationList(item: ItemRecord) {
return item.durations.map((d) => formatDuration(d.minutes)).join(' / ') || 'no lengths set';
} }
function createItem() { function createItem() {
@ -51,7 +63,7 @@
imageUrl: item.imageUrl, imageUrl: item.imageUrl,
type: item.type, type: item.type,
stock: item.stock == null ? '' : String(item.stock), stock: item.stock == null ? '' : String(item.stock),
duration: item.duration == null ? '' : String(item.duration), durations: item.durations.length ? item.durations.map((d) => ({ minutes: String(d.minutes), price: String(d.price) })) : [{ minutes: '60', price: '' }],
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity), capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active active: item.active
@ -109,9 +121,9 @@
</div> </div>
</td> </td>
<td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td> <td><span class="badge">{item.type === 'item_with_time' ? 'Service' : 'Product'}</span></td>
<td>{money.format(item.price)}</td> <td>{item.durations.length > 1 ? `from ${money.format(item.price)}` : money.format(item.price)}</td>
<td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td> <td>{item.type === 'item' ? (item.stock ?? '∞') : '—'}</td>
<td>{item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td> <td>{item.type === 'item_with_time' ? `${durationList(item)}${item.bufferMinutes ? ` + ${item.bufferMinutes} min get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'}</td>
<td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td> <td><span class="badge" class:badge-success={item.active}>{item.active ? 'Active' : 'Inactive'}</span></td>
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editItem(item)}>Edit</button></td>
</tr> </tr>
@ -140,40 +152,59 @@
<textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea> <textarea class="textarea min-h-28 w-full" name="description" bind:value={draft.description}></textarea>
</label> </label>
<div class="grid gap-x-4 md:grid-cols-2"> <label class="fieldset">
<label class="fieldset"> <span class="fieldset-legend">Type</span>
<span class="fieldset-legend">Price ({data.currency})</span> <select class="select w-full" name="type" bind:value={draft.type}>
<input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} /> <option value="item">Product</option>
</label> <option value="item_with_time">Service (bookable)</option>
<label class="fieldset"> </select>
<span class="fieldset-legend">Type</span> </label>
<select class="select w-full" name="type" bind:value={draft.type}>
<option value="item">Product</option>
<option value="item_with_time">Service (bookable)</option>
</select>
</label>
</div>
{#if draft.type === 'item'} {#if draft.type === 'item'}
<label class="fieldset">
<span class="fieldset-legend">Stock</span>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
{:else}
<div class="grid gap-x-4 md:grid-cols-2"> <div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Duration (minutes)</span> <span class="fieldset-legend">Price ({data.currency})</span>
<input class="input w-full" type="number" min="1" step="1" name="duration" placeholder="60" required bind:value={draft.duration} /> <input class="input w-full" type="number" step="0.01" min="0" name="price" required bind:value={draft.price} />
</label> </label>
<label class="fieldset">
<span class="fieldset-legend">Stock</span>
<input class="input w-full" type="number" min="0" step="1" name="stock" placeholder="Unlimited when empty" bind:value={draft.stock} />
</label>
</div>
{:else}
<div class="fieldset">
<span class="fieldset-legend">Lengths and prices</span>
<div class="space-y-2">
{#each draft.durations as row, i}
<div class="flex flex-wrap items-center gap-2">
<label class="input w-36">
<input type="number" min="5" max="720" step="5" name="durationMinutes" required aria-label="Length in minutes" bind:value={row.minutes} />
<span class="label">min</span>
</label>
<label class="input w-40">
<input type="number" min="0" step="0.01" name="durationPrice" required aria-label="Price for this length" bind:value={row.price} />
<span class="label">{data.currency}</span>
</label>
{#if Number(row.minutes) >= 5}<span class="text-sm text-base-content/60">{formatDuration(Number(row.minutes))}</span>{/if}
{#if draft.durations.length > 1}
<button class="btn btn-ghost btn-sm" type="button" aria-label="Remove this length" onclick={() => draft.durations.splice(i, 1)}>✕</button>
{/if}
</div>
{/each}
</div>
<button class="btn btn-ghost btn-sm mt-1 w-fit" type="button" onclick={addDuration}>+ Add a length</button>
<span class="label">Customers pick a length with a slider in the shop; the price follows it.</span>
</div>
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Get-ready time (minutes)</span> <span class="fieldset-legend">Get-ready time (minutes)</span>
<input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} /> <input class="input w-full" type="number" min="0" step="1" name="bufferMinutes" placeholder="0" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each appointment — between generated slots, and before another service can start</span> <span class="label">Gap after each appointment, before the next one can start</span>
</label> </label>
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Places per slot</span> <span class="fieldset-legend">Places in a group session</span>
<input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} /> <input class="input w-full" type="number" min="1" max="500" step="1" name="capacity" placeholder="1" bind:value={draft.capacity} />
<span class="label">1 for one-to-one; more for a group session. New slots start with this.</span> <span class="label">Only for group sessions (Slots → group session). New sessions start with this.</span>
</label> </label>
</div> </div>
{/if} {/if}

View file

@ -39,7 +39,8 @@ export const load: PageServerLoad = async ({ locals }) => {
price: Number(line.price) || 0, price: Number(line.price) || 0,
quantity: Number(line.quantity) || 1, quantity: Number(line.quantity) || 1,
lineType: String(line.lineType || 'item'), lineType: String(line.lineType || 'item'),
start: line.start ? String(line.start) : '' start: line.start ? String(line.start) : '',
minutes: Number(line.minutes) || 0
})) }))
})); }));

View file

@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { enhance } from '$app/forms'; import { enhance } from '$app/forms';
import { formatDateTime } from '$lib/calendar'; import { formatDateTime } from '$lib/calendar';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let orders = $derived(data.orders || []); let orders = $derived(data.orders || []);
@ -72,7 +73,7 @@
<li> <li>
{line.quantity}× {line.name} — {money.format(line.price)} {line.quantity}× {line.name} — {money.format(line.price)}
{#if line.lineType === 'slot' && line.start} {#if line.lineType === 'slot' && line.start}
<span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}</span> <span class="block text-sm text-base-content/60">{formatDateTime(line.start, data.timezone)}{line.minutes ? ` · ${formatDuration(line.minutes)}` : ''}</span>
{/if} {/if}
</li> </li>
{/each} {/each}

View file

@ -14,6 +14,7 @@ import {
monthGridKeys, monthGridKeys,
overlapsAny, overlapsAny,
planGeneratedSlots, planGeneratedSlots,
planWindows,
shiftByDays, shiftByDays,
timeToMinutes, timeToMinutes,
type BulkResult, type BulkResult,
@ -21,16 +22,24 @@ import {
type SlotDetail, type SlotDetail,
type TimeWindow type TimeWindow
} from '$lib/slots'; } from '$lib/slots';
import type { SlotKind, StartTimesMode } from '$lib/types';
import { parseDurations } from '$shared/items';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
type SlotPayload = /** What a slot record is saved with. */
| { payload: { item: string; start: string; end: string; capacity: number; notes: string } } type SlotFields = {
| { error: string }; kind: SlotKind;
items: string[];
start: string;
end: string;
startTimes: StartTimesMode | '';
capacity: number | null;
notes: string;
};
/** A slot to create: planned times plus what it copies (service, places, notes). */ type Service = { id: string; name: string; durations: { minutes: number; price: number }[]; bufferMinutes: number; capacity: number };
type Candidate = PlannedSlot & { item: string; capacity: number; notes: string };
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo'; const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10); const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10);
@ -41,47 +50,93 @@ const MAX_RANGE_DAYS = 366;
const MAX_COPY_WEEKS = 12; const MAX_COPY_WEEKS = 12;
const MAX_CAPACITY = 500; const MAX_CAPACITY = 500;
/** Active bookable services, with what the slot forms need. */
async function loadServices(pb: Pb): Promise<Service[]> {
const records = await pb.collection('items').getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' });
return records.map((record) => ({
id: record.id,
name: String(record.name || ''),
durations: parseDurations(record.durations),
bufferMinutes: Number(record.bufferMinutes) || 0,
capacity: Math.max(1, Number(record.capacity) || 1)
}));
}
/** /**
* Places from the form: a whole number 1–500, or the service's own * Places from the form: a whole number 1–500, or `fallback` (the service's
* capacity (default 1) when the field is left empty. * own capacity) when the field is left empty.
*/ */
function parseCapacity(data: FormData, item: Record<string, any>): number | { error: string } { function parseCapacity(data: FormData, fallback: number): number | { error: string } {
const raw = String(data.get('capacity') ?? '').trim(); const raw = String(data.get('capacity') ?? '').trim();
if (raw === '') return Math.max(1, Number(item.capacity) || 1); if (raw === '') return fallback;
const capacity = Number(raw); const capacity = Number(raw);
if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) return { error: `Places must be a whole number from 1 to ${MAX_CAPACITY}.` }; if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) return { error: `Places must be a whole number from 1 to ${MAX_CAPACITY}.` };
return capacity; return capacity;
} }
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> { function parseStartTimes(data: FormData): StartTimesMode {
const itemId = String(data.get('item') || '').trim(); return String(data.get('startTimes')) === 'edges' ? 'edges' : 'grid';
const startValue = String(data.get('start') || '').trim(); }
const notes = String(data.get('notes') || '').trim();
if (!itemId || !startValue) return { error: 'Service and start are required.' }; /** The services ticked in a window form, all of them active services. */
function chosenServices(data: FormData, services: Service[]): string[] | { error: string } {
const ids = [...new Set(data.getAll('items').map(String))];
if (!ids.length) return { error: 'Choose at least one service that can be booked in this window.' };
if (ids.some((id) => !services.some((s) => s.id === id))) return { error: 'A chosen service was not found or is inactive.' };
return ids;
}
/** A window from the form: a date, from/to times (site timezone) and its services. */
function windowFields(data: FormData, services: Service[]): SlotFields | { error: string } {
const date = String(data.get('date') || '');
const from = String(data.get('from') || '');
const to = String(data.get('to') || '');
if (!isDateKey(date) || timeToMinutes(from) === null || timeToMinutes(to) === null) return { error: 'Choose a date and the start and end times.' };
if (timeToMinutes(to)! <= timeToMinutes(from)!) return { error: 'The window must end after it starts.' };
const items = chosenServices(data, services);
if ('error' in items) return items;
const start = zonedInputToIso(`${date}T${from}`, siteTimezone());
const end = zonedInputToIso(`${date}T${to}`, siteTimezone());
if (!start || !end) return { error: 'Invalid date or time.' };
return { kind: 'window', items, start, end, startTimes: parseStartTimes(data), capacity: null, notes: String(data.get('notes') || '').trim() };
}
/** A group session from the form: one service at one of its lengths, a start and places. */
function sessionFields(data: FormData, services: Service[]): SlotFields | { error: string } {
const service = services.find((s) => s.id === String(data.get('item') || ''));
if (!service) return { error: 'Choose a service.' };
const minutes = Number(data.get('minutes'));
if (!service.durations.some((d) => d.minutes === minutes)) return { error: `Choose one of the lengths “${service.name}” is offered for.` };
// The form sends a wall-clock time in the site's timezone. // The form sends a wall-clock time in the site's timezone.
const startIso = zonedInputToIso(startValue, siteTimezone()); const start = zonedInputToIso(String(data.get('start') || ''), siteTimezone());
if (!startIso) return { error: 'Invalid start time.' }; if (!start) return { error: 'Choose a start time.' };
const start = new Date(startIso); const capacity = parseCapacity(data, service.capacity);
let item: Record<string, any>;
try {
item = await pb.collection('items').getOne(itemId);
} catch {
return { error: 'Selected service was not found.' };
}
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' };
const capacity = parseCapacity(data, item);
if (typeof capacity !== 'number') return capacity; if (typeof capacity !== 'number') return capacity;
const end = new Date(instantMs(start) + minutes * 60_000).toISOString();
return { kind: 'session', items: [service.id], start, end, startTimes: '', capacity, notes: String(data.get('notes') || '').trim() };
}
const duration = Number(item.duration) || 0; /**
const end = new Date(start.getTime() + duration * 60_000); * Slots that may not overlap: windows with any other window (one
* practitioner, one opening time), a group session with another session of
* the same service. A session may overlap a window — whichever is booked
* first blocks the other (see the README's Slot availability).
*/
function clashKey(slot: Pick<SlotFields, 'kind' | 'items'>) {
return slot.kind === 'window' ? 'window' : `session:${slot.items[0] ?? ''}`;
}
// Bookings are never stored on the slot: places are counted from orders /** A slot that `fields` would overlap (ignoring `exceptId`), or null — or undefined if PocketBase can't be read. */
// and basket holds by the shop hook, which also works out blocking. async function clashingSlot(pb: Pb, fields: SlotFields, exceptId = '') {
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), capacity, notes } }; const key = toZonedDatetimeInput(fields.start, siteTimezone()).slice(0, 10);
const existing = await slotsForDays(pb, addDaysToKey(key, -1), addDaysToKey(key, 1));
if (!existing) return undefined;
return existing.slots.find((slot) => slot.id !== exceptId && clashKey(slot) === clashKey(fields) && overlapsAny(fields, [slot])) ?? null;
}
function clashMessage(slot: SlotDetail) {
const time = `${toZonedDatetimeInput(slot.start, siteTimezone()).replace('T', ' ')}–${toZonedDatetimeInput(slot.end, siteTimezone()).slice(11)}`;
return slot.kind === 'window' ? `This overlaps the window ${time}. Change that one instead.` : `This overlaps another ${slot.itemNames[0] ?? ''} session (${time}).`;
} }
/** Validated `from`/`to` date keys from a bulk form, or an error message. */ /** Validated `from`/`to` date keys from a bulk form, or an error message. */
@ -102,23 +157,16 @@ function slotsForDays(pb: Pb, fromKey: string, toKey: string, item = '') {
}); });
} }
async function bookableService(pb: Pb, itemId: string) {
if (!itemId) return null;
const item = await pb.collection('items').getOne(itemId).catch(() => null);
return item && item.type === 'item_with_time' ? item : null;
}
/** /**
* Drop candidates that start in the past or overlap a slot of the same * Drop candidates that start in the past or overlap a slot they may not
* service (existing, or accepted earlier in this run). Different services * overlap (existing, or accepted earlier in this run — see clashKey).
* may share a time: whichever is booked first blocks the others.
*/ */
function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) { function filterCandidates(candidates: SlotFields[], existing: SlotDetail[]) {
const now = Date.now(); const now = Date.now();
const taken = new Map<string, PlannedSlot[]>(); const taken = new Map<string, PlannedSlot[]>();
for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]); for (const slot of existing) taken.set(clashKey(slot), [...(taken.get(clashKey(slot)) ?? []), slot]);
const accepted: Candidate[] = []; const accepted: SlotFields[] = [];
let skippedPast = 0; let skippedPast = 0;
let skippedOverlap = 0; let skippedOverlap = 0;
for (const candidate of candidates) { for (const candidate of candidates) {
@ -126,13 +174,13 @@ function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) {
skippedPast++; skippedPast++;
continue; continue;
} }
const ranges = taken.get(candidate.item) ?? []; const ranges = taken.get(clashKey(candidate)) ?? [];
if (overlapsAny(candidate, ranges)) { if (overlapsAny(candidate, ranges)) {
skippedOverlap++; skippedOverlap++;
continue; continue;
} }
ranges.push(candidate); ranges.push(candidate);
taken.set(candidate.item, ranges); taken.set(clashKey(candidate), ranges);
accepted.push(candidate); accepted.push(candidate);
} }
accepted.sort((a, b) => instantMs(a.start) - instantMs(b.start)); accepted.sort((a, b) => instantMs(a.start) - instantMs(b.start));
@ -158,42 +206,51 @@ async function previewOrCreate(pb: Pb, action: 'generate' | 'copy', intent: stri
}; };
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: accepted.length }); if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: accepted.length });
const created = await runInBatches(accepted, 'create', (slot) => const created = await runInBatches(accepted, 'create', (slot) => pb.collection('slots').create(slot));
pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, capacity: slot.capacity, notes: slot.notes })
);
return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created }); return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created });
} }
/** Weekdays and opening hours from a generate form, or an error. */
function weekdaysAndHours(data: FormData): { weekdays: number[]; windows: TimeWindow[] } | { error: string } {
const weekdays = data.getAll('weekday').map(Number).filter((day) => day >= 0 && day <= 6);
if (!weekdays.length) return { error: 'Choose at least one weekday.' };
const froms = data.getAll('windowFrom').map(String);
const tos = data.getAll('windowTo').map(String);
const windows: TimeWindow[] = froms.map((from, i) => ({ from, to: tos[i] ?? '' }));
if (!windows.length) return { error: 'Add at least one time window.' };
for (const window of windows) {
const from = timeToMinutes(window.from);
const to = timeToMinutes(window.to);
if (from === null || to === null) return { error: 'Every time window needs a start and an end time.' };
if (to <= from) return { error: `The hours ${window.from}–${window.to} end before they start.` };
}
return { weekdays, windows };
}
export const load: PageServerLoad = async ({ locals, url }) => { export const load: PageServerLoad = async ({ locals, url }) => {
const today = todayKey(); const today = todayKey();
const monthParam = url.searchParams.get('month') || ''; const monthParam = url.searchParams.get('month') || '';
const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7); const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7);
const itemRecords = await locals.pb const items = await loadServices(locals.pb).catch(() => []);
.collection('items')
.getFullList({ filter: "type = 'item_with_time' && active = true", sort: 'name' })
.catch(() => []);
const items = itemRecords.map((record) => ({
id: record.id,
name: String(record.name || ''),
duration: Number(record.duration) || 0,
bufferMinutes: Number(record.bufferMinutes) || 0,
capacity: Math.max(1, Number(record.capacity) || 1)
}));
// Only the slots shown in the month grid (which spans whole weeks). // Only the slots shown in the month grid (which spans whole weeks).
const grid = monthGridKeys(month); const grid = monthGridKeys(month);
const slots = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]); const details = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]);
return { items, slots: slots ?? [], slotsError: slots === null, month, today }; return { items, slots: details?.slots ?? [], bookings: details?.bookings ?? [], slotsError: details === null, month, today };
}; };
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 result = await slotPayload(data, locals.pb); const services = await loadServices(locals.pb).catch(() => []);
if ('error' in result) return fail(400, { message: result.error }); const fields = String(data.get('kind')) === 'session' ? sessionFields(data, services) : windowFields(data, services);
const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload)); if ('error' in fields) return fail(400, { message: fields.error });
const clash = await clashingSlot(locals.pb, fields);
if (clash === undefined) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
if (clash) return fail(400, { message: clashMessage(clash) });
const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(fields));
if (!created.ok) return created.failure; if (!created.ok) return created.failure;
return { ok: true }; return { ok: true };
}, },
@ -203,23 +260,31 @@ export const actions: Actions = {
if (!id) return fail(400, { message: 'Slot id is required.' }); if (!id) return fail(400, { message: 'Slot id is required.' });
// Re-read the slot: the page may be stale, and customers may have // Re-read the slot: the page may be stale, and customers may have
// booked or held places since. Once any place is taken, the service // booked or held times since.
// and time are fixed; places can't go below what's taken.
const current = await loadSlotDetail(locals.pb, id).catch(() => undefined); const current = await loadSlotDetail(locals.pb, id).catch(() => undefined);
if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' }); if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' });
if (!current) return fail(404, { message: 'This slot no longer exists.' }); if (!current) return fail(404, { message: 'This slot no longer exists.' });
const services = await loadServices(locals.pb).catch(() => []);
const taken = seatsTaken(current); const taken = seatsTaken(current);
let patch: Record<string, string | number>;
if (taken > 0) { let patch: Partial<SlotFields>;
const capacity = parseCapacity(data, { capacity: current.capacity }); if (current.kind === 'session' && taken > 0) {
// Customers booked this time and service: only places and notes can change.
const capacity = parseCapacity(data, current.capacity ?? 1);
if (typeof capacity !== 'number') return fail(400, { message: capacity.error }); if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` }); if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` });
patch = { capacity, notes: String(data.get('notes') || '').trim() }; patch = { capacity, notes: String(data.get('notes') || '').trim() };
} else { } else {
const result = await slotPayload(data, locals.pb); const fields = current.kind === 'session' ? sessionFields(data, services) : windowFields(data, services);
if ('error' in result) return fail(400, { message: result.error }); if ('error' in fields) return fail(400, { message: fields.error });
patch = result.payload; // A window keeps the times already booked in it: it can grow or
// change services, but not shrink past a booking.
const outside = current.bookings.find((b) => instantMs(b.start) < instantMs(fields.start) || instantMs(b.end) > instantMs(fields.end));
if (outside) return fail(400, { message: 'A booking in this window would fall outside the new times — the window must still cover every booked time.' });
const clash = await clashingSlot(locals.pb, fields, id);
if (clash === undefined) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
if (clash) return fail(400, { message: clashMessage(clash) });
patch = fields;
} }
const updated = await attempt('Could not save the slot.', () => locals.pb.collection('slots').update(id, patch)); const updated = await attempt('Could not save the slot.', () => locals.pb.collection('slots').update(id, patch));
if (!updated.ok) return updated.failure; if (!updated.ok) return updated.failure;
@ -232,56 +297,55 @@ export const actions: Actions = {
const current = await loadSlotDetail(locals.pb, id).catch(() => undefined); const current = await loadSlotDetail(locals.pb, id).catch(() => undefined);
if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' }); if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' });
if (current?.booked) return fail(400, { message: 'This slot has bookings and can’t be deleted.' }); if (current?.booked) return fail(400, { message: 'This slot has bookings and can’t be deleted.' });
if (current?.held) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' }); if (current?.held) return fail(400, { message: 'A time in 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)); const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
if (!deleted.ok) return deleted.failure; if (!deleted.ok) return deleted.failure;
return { ok: true }; return { ok: true };
}, },
/** Fill a date range with slots: chosen weekdays, time windows, get-ready gap. */ /**
* Fill a date range: windows (the opening hours on the chosen weekdays,
* with the chosen services) or group sessions (one service, spaced by
* its length + get-ready time within the hours).
*/
generate: async ({ request, locals }) => { generate: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const intent = String(data.get('intent') || 'preview'); const intent = String(data.get('intent') || 'preview');
const range = dateRange(data); const range = dateRange(data);
if ('error' in range) return fail(400, { message: range.error }); if ('error' in range) return fail(400, { message: range.error });
const days = weekdaysAndHours(data);
const item = await bookableService(locals.pb, String(data.get('item') || '')); if ('error' in days) return fail(400, { message: days.error });
if (!item) return fail(400, { message: 'Choose a bookable service.' }); const services = await loadServices(locals.pb).catch(() => null);
const duration = Number(item.duration) || 0; if (!services) return fail(400, { message: 'Could not read the services — is the database reachable?' });
if (duration <= 0) return fail(400, { message: `“${item.name}” has no duration — set one under Services & products.` });
const capacity = parseCapacity(data, item);
if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
const weekdays = data.getAll('weekday').map(Number).filter((day) => day >= 0 && day <= 6);
if (!weekdays.length) return fail(400, { message: 'Choose at least one weekday.' });
const froms = data.getAll('windowFrom').map(String);
const tos = data.getAll('windowTo').map(String);
const windows: TimeWindow[] = froms.map((from, i) => ({ from, to: tos[i] ?? '' }));
if (!windows.length) return fail(400, { message: 'Add at least one time window.' });
for (const window of windows) {
const from = timeToMinutes(window.from);
const to = timeToMinutes(window.to);
if (from === null || to === null) return fail(400, { message: 'Every time window needs a start and an end time.' });
if (to - from < duration) return fail(400, { message: `The window ${window.from}–${window.to} is shorter than one ${duration}-minute appointment.` });
}
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const bufferMinutes = rawBuffer === '' ? Number(item.bufferMinutes) || 0 : parseInt(rawBuffer, 10);
if (Number.isNaN(bufferMinutes) || bufferMinutes < 0) return fail(400, { message: 'Get-ready time must be 0 or more minutes.' });
const planned = planGeneratedSlots({ ...range, weekdays, windows, durationMinutes: duration, bufferMinutes, timeZone: siteTimezone() });
if (!planned.length) return fail(400, { message: 'No slots fit those days and times.' });
const existing = await slotsForDays(locals.pb, range.fromDate, range.toDate, item.id);
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
const notes = String(data.get('notes') || '').trim(); const notes = String(data.get('notes') || '').trim();
const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id, capacity, notes })), existing);
return previewOrCreate(locals.pb, 'generate', intent, result); let candidates: SlotFields[];
if (String(data.get('kind')) === 'session') {
const service = services.find((s) => s.id === String(data.get('item') || ''));
if (!service) return fail(400, { message: 'Choose a service.' });
const minutes = Number(data.get('minutes'));
if (!service.durations.some((d) => d.minutes === minutes)) return fail(400, { message: `Choose one of the lengths “${service.name}” is offered for.` });
const capacity = parseCapacity(data, service.capacity);
if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
const bufferMinutes = rawBuffer === '' ? service.bufferMinutes : parseInt(rawBuffer, 10);
if (Number.isNaN(bufferMinutes) || bufferMinutes < 0) return fail(400, { message: 'Get-ready time must be 0 or more minutes.' });
const planned = planGeneratedSlots({ ...range, ...days, durationMinutes: minutes, bufferMinutes, timeZone: siteTimezone() });
candidates = planned.map((slot) => ({ ...slot, kind: 'session', items: [service.id], startTimes: '', capacity, notes }));
} else {
const items = chosenServices(data, services);
if ('error' in items) return fail(400, { message: items.error });
const startTimes = parseStartTimes(data);
candidates = planWindows({ ...range, ...days, timeZone: siteTimezone() }).map((slot) => ({ ...slot, kind: 'window', items, startTimes, capacity: null, notes }));
}
if (!candidates.length) return fail(400, { message: 'Nothing fits those days and times.' });
const existing = await slotsForDays(locals.pb, addDaysToKey(range.fromDate, -1), addDaysToKey(range.toDate, 1));
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
return previewOrCreate(locals.pb, 'generate', intent, filterCandidates(candidates, existing.slots));
}, },
/** Repeat one week's slots (all services, or one) for the following weeks. */ /** Repeat one week's slots (all, or those offering one service) for the following weeks. */
copy: async ({ request, locals }) => { copy: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const intent = String(data.get('intent') || 'preview'); const intent = String(data.get('intent') || 'preview');
@ -292,25 +356,25 @@ export const actions: Actions = {
const itemId = String(data.get('item') || ''); const itemId = String(data.get('item') || '');
const source = await slotsForDays(locals.pb, sourceWeek, addDaysToKey(sourceWeek, 6), itemId); const source = await slotsForDays(locals.pb, sourceWeek, addDaysToKey(sourceWeek, 6), itemId);
const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 7), addDaysToKey(sourceWeek, 7 * (weeks + 1) - 1), itemId); const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 6), addDaysToKey(sourceWeek, 7 * (weeks + 1)));
if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' }); if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' });
if (!source.length) return fail(400, { message: 'That week has no slots to copy.' }); if (!source.slots.length) return fail(400, { message: 'That week has no slots to copy.' });
// Copies are new, empty slots: same service, places and notes. // Copies are new, empty slots: same kind, services, places, start times and notes.
const candidates: Candidate[] = []; const candidates: SlotFields[] = [];
for (let week = 1; week <= weeks; week++) { for (let week = 1; week <= weeks; week++) {
for (const slot of source) { for (const slot of source.slots) {
const start = shiftByDays(slot.start, 7 * week, siteTimezone()); const start = shiftByDays(slot.start, 7 * week, siteTimezone());
if (!start) continue; const end = shiftByDays(slot.end, 7 * week, siteTimezone());
const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString(); if (!start || !end) continue;
candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes }); candidates.push({ kind: slot.kind, items: slot.items, start, end, startTimes: slot.startTimes ?? '', capacity: slot.capacity ?? null, notes: slot.notes });
} }
} }
return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing)); return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing.slots));
}, },
/** Delete the slots in a date range that have no places taken. */ /** Delete the slots in a date range that have nothing booked or held. */
clear: async ({ request, locals }) => { clear: async ({ request, locals }) => {
const data = await request.formData(); const data = await request.formData();
const intent = String(data.get('intent') || 'preview'); const intent = String(data.get('intent') || 'preview');
@ -318,20 +382,20 @@ export const actions: Actions = {
if ('error' in range) return fail(400, { message: range.error }); if ('error' in range) return fail(400, { message: range.error });
const itemId = String(data.get('item') || ''); const itemId = String(data.get('item') || '');
const slots = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId); const details = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId);
if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' }); if (!details) return fail(400, { message: 'Could not read slots — is the database reachable?' });
const removable = slots.filter((slot) => seatsTaken(slot) === 0); const removable = details.slots.filter((slot) => seatsTaken(slot) === 0);
const summary = { const summary = {
action: 'clear' as const, action: 'clear' as const,
kept: slots.length - removable.length, kept: details.slots.length - removable.length,
firstStart: removable[0]?.start ?? '', firstStart: removable[0]?.start ?? '',
lastStart: removable.at(-1)?.start ?? '' lastStart: removable.at(-1)?.start ?? ''
}; };
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length }); if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length });
// Re-check each slot just before deleting it: a customer may have put // Re-check each slot just before deleting it: a customer may have put
// it in their basket since the list was read. // a time in it into their basket since the list was read.
const deleted = await runInBatches(removable, 'delete', async (slot) => { const deleted = await runInBatches(removable, 'delete', async (slot) => {
const fresh = await loadSlotDetail(locals.pb, slot.id); const fresh = await loadSlotDetail(locals.pb, slot.id);
if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview'); if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview');

View file

@ -4,33 +4,39 @@
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import { confirmSubmit } from '$lib/admin/confirm'; import { confirmSubmit } from '$lib/admin/confirm';
import Modal from '$lib/admin/Modal.svelte'; import Modal from '$lib/admin/Modal.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte'; import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte'; import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.svelte';
import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte'; import GenerateSlotsModal from '$lib/admin/slots/GenerateSlotsModal.svelte';
import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots'; import { SLOT_STATE_LABELS, START_TIMES_HINTS, START_TIMES_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
import type { BulkResult, SlotState } from '$lib/slots'; import type { BulkResult, SlotState } from '$lib/slots';
import type { SlotKind, StartTimesMode } from '$lib/types';
import { formatDuration } from '$shared/items';
let { data, form } = $props(); let { data, form } = $props();
let items = $derived(data.items || []); let items = $derived(data.items || []);
let serviceFilter = $state(''); let serviceFilter = $state('');
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter)); let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.items.includes(serviceFilter)));
type Slot = (typeof slots)[number]; type Slot = (typeof slots)[number];
let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot]))); type Booking = (typeof data.bookings)[number];
// ── Month grid (date keys in the site timezone) ── // ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4; const MAX_CHIPS = 4;
const dayKeyOf = (iso: string) => toZonedDatetimeInput(iso, data.timezone).slice(0, 10);
let gridKeys = $derived(monthGridKeys(data.month)); let gridKeys = $derived(monthGridKeys(data.month));
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' })); let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1)); let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
let slotsByDay = $derived.by(() => { let slotsByDay = $derived.by(() => {
const byDay = new Map<string, Slot[]>(); const byDay = new Map<string, Slot[]>();
for (const slot of slots) { for (const slot of slots) byDay.set(dayKeyOf(slot.start), [...(byDay.get(dayKeyOf(slot.start)) ?? []), slot]);
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
}
return byDay; return byDay;
}); });
let monthSlots = $derived(slots.filter((slot) => toZonedDatetimeInput(slot.start, data.timezone).startsWith(data.month))); let bookingsByDay = $derived.by(() => {
const byDay = new Map<string, Booking[]>();
for (const booking of data.bookings || []) byDay.set(dayKeyOf(booking.start), [...(byDay.get(dayKeyOf(booking.start)) ?? []), booking]);
return byDay;
});
let monthSlots = $derived(slots.filter((slot) => dayKeyOf(slot.start).startsWith(data.month)));
// ── Modals ── // ── Modals ──
let showEditor = $state(false); let showEditor = $state(false);
@ -42,13 +48,14 @@
let copyFrom = $state(''); let copyFrom = $state('');
let clearRange = $state({ from: '', to: '' }); let clearRange = $state({ from: '', to: '' });
let daySlots = $derived(slotsByDay.get(dayKey) ?? []); let daySlots = $derived(slotsByDay.get(dayKey) ?? []);
let dayBookings = $derived(bookingsByDay.get(dayKey) ?? []);
let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null); let bulkDone = $derived(form && 'bulk' in form && form.bulk?.intent === 'done' ? (form.bulk as BulkResult) : null);
function bulkMessage(result: BulkResult) { function bulkMessage(result: BulkResult) {
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`; const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
const verb = result.action === 'clear' ? 'Deleted' : 'Created'; const verb = result.action === 'clear' ? 'Deleted' : 'Created';
const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : ''; const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (booked in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`; return `${verb} ${n(result.count)}.${failed}`;
} }
@ -67,15 +74,26 @@
blocked: 'badge-ghost' blocked: 'badge-ghost'
}; };
/** "2/8" for group slots, '' for one-to-one. */ const range = (start: string, end: string) => `${formatTime(start, data.timezone)}–${formatTime(end, data.timezone)}`;
/** "Massage, Facial" — or the one service of a session. */
const serviceNames = (slot: Slot) => slot.itemNames.filter(Boolean).join(', ') || 'No services';
/** "2/8" for group sessions, '' otherwise. */
function places(slot: Slot) { function places(slot: Slot) {
return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : ''; return slot.kind === 'session' && (slot.capacity ?? 1) > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
} }
/** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */ /** What a window has left, e.g. "Free 10:15–12:00". */
function blockedReason(slot: Slot) { function freeLabel(slot: Slot) {
const blocker = slotsById.get(slot.blockedBy); if (!slot.free?.length) return 'No free time left';
return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking'; return `Free ${slot.free.map((f) => range(f.start, f.end)).join(', ')}`;
}
function describe(slot: Slot, state: SlotState) {
if (slot.kind === 'window') return `${serviceNames(slot)} — ${freeLabel(slot)}`;
if (state === 'blocked' && slot.blockedBy) return `Blocked by ${range(slot.blockedBy.start, slot.blockedBy.end)} ${slot.blockedBy.itemName}`;
return `${SLOT_STATE_LABELS[state]}${places(slot) ? ` (${places(slot)})` : ''}`;
} }
function openDay(key: string) { function openDay(key: string) {
@ -95,10 +113,19 @@
showClear = true; showClear = true;
} }
// ── Single slot editor ── // ── Slot editor (a window or a group session) ──
type SlotDraft = { type SlotDraft = {
id: string; id: string;
kind: SlotKind;
// window
date: string;
from: string;
to: string;
items: string[];
startTimes: StartTimesMode;
// session
item: string; item: string;
minutes: string;
start: string; start: string;
capacity: string; capacity: string;
booked: number; booked: number;
@ -106,23 +133,51 @@
notes: string; notes: string;
}; };
let draft = $state<SlotDraft>(emptyDraft()); let draft = $state<SlotDraft>(emptyDraft('window'));
let editorError = $state(''); let editorError = $state('');
let action = $derived(draft.id ? '?/update' : '?/create'); let action = $derived(draft.id ? '?/update' : '?/create');
// Once any place is taken, the service and time are fixed (customers booked them).
let taken = $derived(draft.booked + draft.held); let taken = $derived(draft.booked + draft.held);
// Once a place in a session is taken, its service and time are fixed (customers booked them).
let sessionLocked = $derived(draft.kind === 'session' && taken > 0);
let selectedItem = $derived(items.find((item) => item.id === draft.item)); let selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => { let endLabel = $derived.by(() => {
if (!selectedItem || !draft.start) return ''; if (!draft.start || !draft.minutes) return '';
const startIso = zonedInputToIso(draft.start, data.timezone); const startIso = zonedInputToIso(draft.start, data.timezone);
if (!startIso) return ''; if (!startIso) return '';
const end = new Date(new Date(startIso).getTime() + (Number(selectedItem.duration) || 0) * 60_000); return `Ends at ${formatTime(new Date(new Date(startIso).getTime() + Number(draft.minutes) * 60_000).toISOString(), data.timezone)}`;
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
}); });
function emptyDraft(day = ''): SlotDraft { function emptyDraft(kind: SlotKind, day = ''): SlotDraft {
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone); const date = day || data.today;
return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' }; const service = items.find((item) => item.id === serviceFilter);
return {
id: '',
kind,
date,
from: '09:00',
to: '12:00',
items: serviceFilter ? [serviceFilter] : oneToOneServices(items),
startTimes: 'grid',
item: serviceFilter,
minutes: service?.durations[0] ? String(service.durations[0].minutes) : '',
start: `${date}T09:00`,
capacity: '',
booked: 0,
held: 0,
notes: ''
};
}
/** What a new window offers by default: the one-to-one services (group classes get sessions), or all if there are none. */
function oneToOneServices(list: typeof items) {
const ids = list.filter((item) => item.capacity <= 1).map((item) => item.id);
return ids.length ? ids : list.map((item) => item.id);
}
function selectSessionService(id: string) {
draft.item = id;
const service = items.find((item) => item.id === id);
if (!service?.durations.some((d) => String(d.minutes) === draft.minutes)) draft.minutes = service?.durations[0] ? String(service.durations[0].minutes) : '';
} }
// Enhanced so the page keeps its ?month= after saving (a plain POST to // Enhanced so the page keeps its ?month= after saving (a plain POST to
@ -139,20 +194,28 @@
}; };
}; };
function createSlot(day = '') { function createSlot(kind: SlotKind, day = '') {
editorError = ''; editorError = '';
draft = emptyDraft(day); draft = emptyDraft(kind, day);
showDay = false; showDay = false;
showEditor = true; showEditor = true;
} }
function editSlot(slot: Slot) { function editSlot(slot: Slot) {
editorError = ''; editorError = '';
const start = toZonedDatetimeInput(slot.start, data.timezone);
draft = { draft = {
...emptyDraft(slot.kind),
id: slot.id, id: slot.id,
item: slot.item, date: start.slice(0, 10),
start: toZonedDatetimeInput(slot.start, data.timezone), from: start.slice(11, 16),
capacity: String(slot.capacity), to: toZonedDatetimeInput(slot.end, data.timezone).slice(11, 16),
items: [...slot.items],
startTimes: slot.startTimes ?? 'grid',
item: slot.items[0] ?? '',
minutes: String(slot.minutes ?? ''),
start,
capacity: String(slot.capacity ?? ''),
booked: slot.booked, booked: slot.booked,
held: slot.held, held: slot.held,
notes: slot.notes notes: slot.notes
@ -165,13 +228,16 @@
<svelte:head><title>Slots | CMS</title></svelte:head> <svelte:head><title>Slots | CMS</title></svelte:head>
<div class="space-y-6"> <div class="space-y-6">
<div class="flex flex-col justify-between gap-4 md:flex-row md:items-end"> <div class="flex flex-col gap-4">
<div> <div>
<h1 class="text-3xl font-bold">Slots</h1> <h1 class="text-3xl font-bold">Slots</h1>
<p class="text-base-content/60">Bookable time slots for your services. Times are in {data.timezone}.</p> <p class="max-w-4xl text-base-content/60">
When you can be booked. A <strong>window</strong> (e.g. 09:00–12:00) takes bookings of the services you choose, at any of their lengths; each booking takes its time plus get-ready time out of the window. A <strong>group session</strong> is one service at a fixed time with places. Times are in {data.timezone}.
</p>
</div> </div>
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button class="btn" type="button" onclick={() => createSlot()}>Create slot</button> <button class="btn" type="button" disabled={!items.length} onclick={() => createSlot('window')}>Add window</button>
<button class="btn" type="button" disabled={!items.length} onclick={() => createSlot('session')}>Add group session</button>
<button class="btn" type="button" onclick={() => openCopy(data.today)}>Copy a week</button> <button class="btn" type="button" onclick={() => openCopy(data.today)}>Copy a week</button>
<button class="btn" type="button" onclick={() => openClear(data.today > `${data.month}-01` ? data.today : `${data.month}-01`, monthEnd)}>Clear slots</button> <button class="btn" type="button" onclick={() => openClear(data.today > `${data.month}-01` ? data.today : `${data.month}-01`, monthEnd)}>Clear slots</button>
<button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button> <button class="btn btn-primary" type="button" disabled={!items.length} onclick={() => (showGenerate = true)}>Generate slots</button>
@ -218,12 +284,17 @@
<button <button
class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}" class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}"
type="button" type="button"
title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {state === 'blocked' ? blockedReason(slot) : SLOT_STATE_LABELS[state]}{places(slot) ? ` (${places(slot)})` : ''}" title="{range(slot.start, slot.end)} {slot.kind === 'window' ? 'window' : serviceNames(slot)} — {describe(slot, state)}"
onclick={() => editSlot(slot)} onclick={() => openDay(key)}
> >
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span> {#if slot.kind === 'window'}
<span class="hidden lg:inline">{slot.itemName}</span> <span class="font-semibold">{range(slot.start, slot.end)}</span>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if} {#if slot.booked + slot.held}<span class="hidden md:inline">· {slot.booked + slot.held} booked</span>{/if}
{:else}
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
<span class="hidden lg:inline">{serviceNames(slot)}</span>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
{/if}
</button> </button>
{/each} {/each}
{#if daySlotList.length > MAX_CHIPS} {#if daySlotList.length > MAX_CHIPS}
@ -238,32 +309,29 @@
{#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)} {#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)}
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {STATE_CLASSES[state as SlotState]}"></span> {label}</span> <span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {STATE_CLASSES[state as SlotState]}"></span> {label}</span>
{/each} {/each}
<span>— a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.</span> <span>— a booking blocks every other one overlapping it, including get-ready time. Click a day for its bookings and free time.</span>
</div> </div>
</div> </div>
<!-- Collapsed by default: a generated month is hundreds of rows, and the calendar covers day-to-day use. --> <!-- Collapsed by default: a generated month is many rows, and the calendar covers day-to-day use. -->
<details class="collapse collapse-arrow rounded-box bg-base-100 shadow"> <details class="collapse collapse-arrow rounded-box bg-base-100 shadow">
<summary class="collapse-title text-2xl font-bold">All slots in {monthLabel} <span class="text-base font-normal text-base-content/60">({monthSlots.length})</span></summary> <summary class="collapse-title text-2xl font-bold">All slots in {monthLabel} <span class="text-base font-normal text-base-content/60">({monthSlots.length})</span></summary>
<div class="collapse-content overflow-x-auto"> <div class="collapse-content overflow-x-auto">
<table class="table"> <table class="table">
<thead><tr><th>Service</th><th>Date</th><th>Places</th><th>Status</th><th></th></tr></thead> <thead><tr><th>When</th><th>Kind</th><th>Services</th><th>Booked</th><th>Status</th><th></th></tr></thead>
<tbody> <tbody>
{#each monthSlots as slot (slot.id)} {#each monthSlots as slot (slot.id)}
{@const state = slotState(slot)} {@const state = slotState(slot)}
<tr> <tr>
<td><span class="font-semibold">{slot.itemName}</span></td> <td>{formatDateTime(slot.start, data.timezone)}–{formatTime(slot.end, data.timezone)}</td>
<td>{formatDateTime(slot.start, data.timezone)}</td> <td>{slot.kind === 'window' ? 'Window' : 'Group session'}</td>
<td>{slot.booked + slot.held}/{slot.capacity}</td> <td>{serviceNames(slot)}</td>
<td> <td>{slot.kind === 'session' ? `${slot.booked + slot.held}/${slot.capacity}` : slot.booked + slot.held}</td>
<span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span> <td><span class="badge {BADGE_CLASSES[state]}" title={describe(slot, state)}>{SLOT_STATE_LABELS[state]}</span></td>
</td> <td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button></td>
<td class="text-right">
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
</td>
</tr> </tr>
{:else} {:else}
<tr><td colspan="5" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr> <tr><td colspan="6" class="py-10 text-center text-base-content/60">No slots this month — use “Generate slots” to fill it.</td></tr>
{/each} {/each}
</tbody> </tbody>
</table> </table>
@ -281,10 +349,14 @@
{#each daySlots as slot (slot.id)} {#each daySlots as slot (slot.id)}
{@const state = slotState(slot)} {@const state = slotState(slot)}
<li class="flex items-center gap-3 py-2"> <li class="flex items-center gap-3 py-2">
<span class="w-28 shrink-0 font-semibold">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span> <span class="w-28 shrink-0 font-semibold">{range(slot.start, slot.end)}</span>
<span class="min-w-0 flex-1"> <span class="min-w-0 flex-1">
<span class="block truncate">{slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''}</span> <span class="block truncate">
{#if state === 'blocked'}<span class="block truncate text-xs text-base-content/60">{blockedReason(slot)}</span>{/if} {slot.kind === 'window' ? 'Window' : 'Group session'} · {serviceNames(slot)}{places(slot) ? ` · ${places(slot)} places` : ''}
</span>
<span class="block truncate text-xs text-base-content/60">
{#if slot.kind === 'window'}{freeLabel(slot)} · {START_TIMES_LABELS[slot.startTimes ?? 'grid']}{:else if state === 'blocked'}{describe(slot, state)}{:else}{formatDuration(slot.minutes ?? 0)}{/if}
</span>
{#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if} {#if slot.notes}<span class="block truncate text-xs text-base-content/60">{slot.notes}</span>{/if}
</span> </span>
<span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span> <span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
@ -295,48 +367,135 @@
{:else} {:else}
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p> <p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
{/if} {/if}
{#if dayBookings.length}
<h3 class="mt-4 font-semibold">Bookings</h3>
<ul class="mt-1 divide-y divide-base-300 text-sm">
{#each dayBookings as booking (`${booking.slot}|${booking.start}|${booking.status}|${booking.item}`)}
<li class="flex items-center gap-3 py-1.5">
<span class="w-28 shrink-0 font-semibold">{range(booking.start, booking.end)}</span>
<span class="min-w-0 flex-1 truncate">
{booking.itemName}{booking.quantity > 1 ? ` · ${booking.quantity} places` : ''}
{#if booking.readyAt !== booking.end}<span class="text-base-content/60"> · ready again {formatTime(booking.readyAt, data.timezone)}</span>{/if}
</span>
<span class="badge badge-sm {booking.status === 'booked' ? 'badge-info badge-soft' : 'badge-warning'}">{booking.status === 'booked' ? 'Booked' : 'In a basket'}</span>
</li>
{/each}
</ul>
<p class="mt-1 text-xs text-base-content/60">Customer details are under Orders.</p>
{/if}
<div class="modal-action flex-wrap justify-between"> <div class="modal-action flex-wrap justify-between">
<div class="flex flex-wrap gap-2"> <div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button> <button class="btn btn-sm" type="button" onclick={() => openCopy(dayKey)}>Copy this week</button>
{#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if} {#if daySlots.length}<button class="btn btn-sm" type="button" onclick={() => openClear(dayKey, dayKey)}>Clear this day</button>{/if}
</div> </div>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot(dayKey)}>Add slot</button> <div class="flex flex-wrap gap-2">
<button class="btn btn-sm" type="button" disabled={!items.length} onclick={() => createSlot('session', dayKey)}>Add group session</button>
<button class="btn btn-primary btn-sm" type="button" disabled={!items.length} onclick={() => createSlot('window', dayKey)}>Add window</button>
</div>
</div> </div>
</Modal> </Modal>
<Modal bind:open={showEditor} title={draft.id ? 'Edit slot' : 'Create slot'}> <Modal bind:open={showEditor} title={draft.id ? (draft.kind === 'window' ? 'Edit window' : 'Edit group session') : 'Add a slot'} wide>
<form method="POST" action={action} use:enhance={submitSlot} class="space-y-1"> <form method="POST" action={action} use:enhance={submitSlot} class="space-y-1">
<input type="hidden" name="id" value={draft.id} /> <input type="hidden" name="id" value={draft.id} />
<input type="hidden" name="kind" value={draft.kind} />
{#if editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if} {#if editorError}<div class="alert alert-error mb-2 text-sm" role="alert">{editorError}</div>{/if}
{#if taken} {#if !draft.id}
<div class="alert alert-warning mb-2 text-sm"> <SegmentedControl
{[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — only the places and notes can be changed. label="Kind"
</div> class="mb-2"
options={['window', 'session']}
value={draft.kind}
formatLabel={(v) => (v === 'window' ? 'Window' : 'Group session')}
onChange={(v) => (draft.kind = v as SlotKind)}
/>
{/if} {/if}
<label class="fieldset"> {#if draft.kind === 'window'}
<span class="fieldset-legend">Service</span> {#if taken}
<select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}> <div class="alert alert-warning mb-2 text-sm">
<option value="" disabled>Select a service…</option> {[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — the window can grow or change services, but must still cover every booked time.
{#each items as item (item.id)} </div>
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option> {/if}
{/each}
</select>
</label>
<label class="fieldset"> <div class="grid gap-x-4 md:grid-cols-3">
<span class="fieldset-legend">Start ({data.timezone})</span> <label class="fieldset">
<input class="input w-full" type="datetime-local" name="start" required disabled={taken > 0} bind:value={draft.start} /> <span class="fieldset-legend">Date</span>
{#if endLabel}<span class="label">{endLabel}</span>{/if} <input class="input w-full" type="date" name="date" required bind:value={draft.date} />
</label> </label>
<label class="fieldset">
<span class="fieldset-legend">From ({data.timezone})</span>
<input class="input w-full" type="time" name="from" required bind:value={draft.from} />
</label>
<label class="fieldset">
<span class="fieldset-legend">To</span>
<input class="input w-full" type="time" name="to" required bind:value={draft.to} />
</label>
</div>
<label class="fieldset"> <div class="fieldset">
<span class="fieldset-legend">Places</span> <span class="fieldset-legend">Services that can be booked in this window</span>
<input class="input w-32" type="number" min={Math.max(1, taken)} max="500" step="1" name="capacity" placeholder={String(selectedItem?.capacity ?? 1)} bind:value={draft.capacity} /> <div class="grid gap-1 sm:grid-cols-2">
<span class="label">More than 1 for a group session.{draft.id ? '' : ' Empty = the service’s own.'}</span> {#each items as item (item.id)}
</label> <label class="label cursor-pointer gap-2 text-base-content">
<input class="checkbox checkbox-sm" type="checkbox" name="items" value={item.id} bind:group={draft.items} />
{item.name}
<span class="text-xs text-base-content/50">{item.durations.map((d) => formatDuration(d.minutes)).join(' / ')}</span>
</label>
{/each}
</div>
</div>
<div class="fieldset">
<input type="hidden" name="startTimes" value={draft.startTimes} />
<SegmentedControl
label="Start times"
options={['grid', 'edges']}
value={draft.startTimes}
formatLabel={(v) => START_TIMES_LABELS[v as StartTimesMode]}
onChange={(v) => (draft.startTimes = v as StartTimesMode)}
/>
<span class="label whitespace-normal">{START_TIMES_HINTS[draft.startTimes]}</span>
</div>
{:else}
{#if sessionLocked}
<div class="alert alert-warning mb-2 text-sm">
{[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — only the places and notes can be changed.
</div>
{/if}
<div class="grid gap-x-4 md:grid-cols-2">
<label class="fieldset">
<span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required disabled={sessionLocked} value={draft.item} onchange={(e) => selectSessionService(e.currentTarget.value)}>
<option value="" disabled>Select a service…</option>
{#each items as item (item.id)}<option value={item.id}>{item.name}</option>{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Length</span>
<select class="select w-full" name="minutes" required disabled={sessionLocked || !selectedItem} bind:value={draft.minutes}>
{#each selectedItem?.durations ?? [] as duration (duration.minutes)}
<option value={String(duration.minutes)}>{formatDuration(duration.minutes)}</option>
{/each}
</select>
</label>
<label class="fieldset">
<span class="fieldset-legend">Start ({data.timezone})</span>
<input class="input w-full" type="datetime-local" name="start" required disabled={sessionLocked} bind:value={draft.start} />
{#if endLabel}<span class="label">{endLabel}</span>{/if}
</label>
<label class="fieldset">
<span class="fieldset-legend">Places</span>
<input class="input w-32" type="number" min={Math.max(1, taken)} max="500" step="1" name="capacity" placeholder={String(selectedItem?.capacity ?? 1)} bind:value={draft.capacity} />
<span class="label">{draft.id ? 'How many people can book it.' : 'Empty = the service’s own.'}</span>
</label>
</div>
{/if}
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Notes</span> <span class="fieldset-legend">Notes</span>
@ -351,7 +510,7 @@
{/if} {/if}
<div class="flex gap-2"> <div class="flex gap-2">
<button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button> <button class="btn" type="button" onclick={() => (showEditor = false)}>Cancel</button>
<button class="btn btn-primary" type="submit">Save slot</button> <button class="btn btn-primary" type="submit">Save</button>
</div> </div>
</div> </div>
</form> </form>