Admin slots: places, blocked/full states, edits limited once booked

Calendar, day panel and list show available / in a basket / booked /
full / blocked (with what blocks it) and places taken. Services, Generate
and single slots take places (default from the service); Copy keeps
them. Once any place is taken only places (not below taken) and notes
can change. All reads go through the shop hook's slot details.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
This commit is contained in:
agent 2026-10-24 08:26:37 +00:00
parent 5c6dff9e18
commit a22d9f2348
7 changed files with 231 additions and 172 deletions

View file

@ -6,7 +6,7 @@
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 }; type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number };
let { let {
open = $bindable(false), open = $bindable(false),
@ -23,6 +23,7 @@
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[],
bufferMinutes: '', bufferMinutes: '',
capacity: '',
notes: '' notes: ''
}); });
@ -50,8 +51,10 @@
function selectService(id: string) { function selectService(id: string) {
draft.item = id; draft.item = id;
// The service's own get-ready time is the default; it can be overridden here. // The service's own get-ready time and places are the defaults; both can be overridden here.
draft.bufferMinutes = String(items.find((item) => item.id === id)?.bufferMinutes ?? 0); const item = items.find((item) => item.id === id);
draft.bufferMinutes = String(item?.bufferMinutes ?? 0);
draft.capacity = String(item?.capacity ?? 1);
} }
function addWindow() { function addWindow() {
@ -109,11 +112,18 @@
<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">
<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-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} /> <input class="input w-32" type="number" min="0" step="1" name="bufferMinutes" bind:value={draft.bufferMinutes} />
<span class="label">Gap after each appointment. Defaults to the service’s own get-ready time.</span> <span class="label">Gap after each appointment. Defaults to the service’s own.</span>
</label> </label>
<label class="fieldset">
<span class="fieldset-legend">Places per slot</span>
<input class="input w-32" type="number" min="1" max="500" step="1" name="capacity" bind:value={draft.capacity} />
<span class="label">More than 1 for a group session. Defaults to the service’s own.</span>
</label>
</div>
{#if service} {#if service}
<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">

View file

@ -1,56 +1,34 @@
// Server helpers for the /slots bulk actions (generate, copy week, clear). // Server helpers for the /slots page. Planning is pure and lives in
// Planning is pure and lives in $shared/slots; this file does the PocketBase // $shared/slots; this file does the PocketBase reads/writes around it.
// reads/writes around it.
import { instantMs, type PlannedSlot } from '$lib/slots'; import type { 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>;
export type ExistingSlot = PlannedSlot & {
id: string;
item: string;
status: string;
heldUntil: string;
notes: string;
};
/** How many PocketBase writes a bulk action runs at once. */ /** How many PocketBase writes a bulk action runs at once. */
const WRITE_CONCURRENCY = 5; const WRITE_CONCURRENCY = 5;
/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */ /**
export function isHoldActive(slot: Record<string, any> | null) { * Slots with their places and blocking, from the shop hook — the same
if (slot?.status !== 'held') return false; * availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js).
const until = instantMs(String(slot.heldUntil || '')); * Either slots starting in `[from, to)` (optionally one service) or one slot by id.
return Number.isNaN(until) || until > Date.now(); */
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', {
query: { detail: 1, ...query },
requestKey: null
});
return slots;
} }
/** /** One slot's details, or null if it doesn't exist (any other failure throws). */
* Slots starting in `[fromIso, toIso)`, optionally for one service. A slot export async function loadSlotDetail(pb: Pb, id: string) {
* without an end gets one from its service's duration, so overlap checks return (await loadSlotDetails(pb, { id }))[0] ?? null;
* always have a real range.
*/
export async function loadSlotsBetween(pb: Pb, fromIso: string, toIso: string, itemId = ''): Promise<ExistingSlot[]> {
const filter = itemId
? pb.filter('start >= {:from} && start < {:to} && item = {:item}', { from: new Date(fromIso), to: new Date(toIso), item: itemId })
: pb.filter('start >= {:from} && start < {:to}', { from: new Date(fromIso), to: new Date(toIso) });
const records = await pb.collection('slots').getFullList({ filter, sort: 'start', expand: 'item' });
return records.map((record) => {
const start = String(record.start || '');
const duration = Number(record.expand?.item?.duration) || 0;
const end = record.end ? String(record.end) : new Date(instantMs(start) + duration * 60_000).toISOString();
return {
id: record.id,
item: String(record.item || ''),
start,
end,
status: String(record.status || 'available'),
heldUntil: record.heldUntil ? String(record.heldUntil) : '',
notes: String(record.notes || '')
};
});
} }
export const seatsTaken = (slot: Pick<SlotDetail, 'booked' | 'held'>) => slot.booked + slot.held;
/** Run `fn` over `values` a few at a time; returns how many succeeded. */ /** Run `fn` over `values` a few at a time; returns how many succeeded. */
export async function runInBatches<T>(values: T[], label: string, fn: (value: T) => Promise<unknown>) { export async function runInBatches<T>(values: T[], label: string, fn: (value: T) => Promise<unknown>) {
let succeeded = 0; let succeeded = 0;

View file

@ -9,9 +9,11 @@ function itemPayload(data: FormData) {
const rawStock = String(data.get('stock') ?? '').trim(); const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').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 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 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;
return { return {
name: String(data.get('name') || '').trim(), name: String(data.get('name') || '').trim(),
@ -22,6 +24,7 @@ function itemPayload(data: FormData) {
stock: Number.isNaN(stock) ? null : stock, stock: Number.isNaN(stock) ? null : stock,
duration: Number.isNaN(duration) ? null : duration, duration: Number.isNaN(duration) ? null : duration,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes, bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
capacity: Number.isNaN(capacity) ? null : capacity,
active: String(data.get('active')) === 'true' active: String(data.get('active')) === 'true'
}; };
} }
@ -39,6 +42,7 @@ function normalizeItem(record: Record<string, any>): ItemRecord {
stock: record.stock ?? null, stock: record.stock ?? null,
duration: record.duration ?? null, duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null, bufferMinutes: record.bufferMinutes ?? null,
capacity: record.capacity ?? null,
active: record.active !== false active: record.active !== false
}; };
} }

View file

@ -22,6 +22,7 @@
stock: string; stock: string;
duration: string; duration: string;
bufferMinutes: string; bufferMinutes: string;
capacity: string;
active: boolean; active: boolean;
}; };
@ -31,7 +32,7 @@
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: '', active: true }; return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true };
} }
function createItem() { function createItem() {
@ -52,6 +53,7 @@
stock: item.stock == null ? '' : String(item.stock), stock: item.stock == null ? '' : String(item.stock),
duration: item.duration == null ? '' : String(item.duration), duration: item.duration == null ? '' : String(item.duration),
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes), bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active active: item.active
}; };
uploadError = ''; uploadError = '';
@ -109,7 +111,7 @@
<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>{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` : ''}` : '—'}</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><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>
@ -166,7 +168,12 @@
<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 left after each appointment when generating slots</span> <span class="label">Gap after each appointment — between generated slots, and before another service can start</span>
</label>
<label class="fieldset">
<span class="fieldset-legend">Places per slot</span>
<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>
</label> </label>
</div> </div>
{/if} {/if}

View file

@ -3,7 +3,7 @@ import { fail } from '@sveltejs/kit';
import { toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar'; import { toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb'; import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions'; import { attempt } from '$lib/server/actions';
import { isHoldActive, loadSlotsBetween, runInBatches, type ExistingSlot } from '$lib/server/slots'; import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots';
import { import {
MAX_BULK_SLOTS, MAX_BULK_SLOTS,
addDaysToKey, addDaysToKey,
@ -18,17 +18,20 @@ import {
timeToMinutes, timeToMinutes,
type BulkResult, type BulkResult,
type PlannedSlot, type PlannedSlot,
type SlotDetail,
type TimeWindow type TimeWindow
} from '$lib/slots'; } from '$lib/slots';
import type { SlotStatus } from '$lib/types';
import type { Actions, PageServerLoad } from './$types'; import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType<typeof createPocketBase>; type Pb = ReturnType<typeof createPocketBase>;
type SlotPayload = type SlotPayload =
| { payload: { item: string; start: string; end: string; notes: string } } | { payload: { item: string; start: string; end: string; capacity: number; notes: string } }
| { error: string }; | { error: string };
/** A slot to create: planned times plus what it copies (service, places, notes). */
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);
/** Midnight at the start of `key` in the site timezone, as an ISO instant. */ /** Midnight at the start of `key` in the site timezone, as an ISO instant. */
@ -36,6 +39,19 @@ const dayStartIso = (key: string) => zonedInputToIso(`${key}T00:00`, siteTimezon
const MAX_RANGE_DAYS = 366; const MAX_RANGE_DAYS = 366;
const MAX_COPY_WEEKS = 12; const MAX_COPY_WEEKS = 12;
const MAX_CAPACITY = 500;
/**
* Places from the form: a whole number 1–500, or the service's own
* capacity (default 1) when the field is left empty.
*/
function parseCapacity(data: FormData, item: Record<string, any>): number | { error: string } {
const raw = String(data.get('capacity') ?? '').trim();
if (raw === '') return Math.max(1, Number(item.capacity) || 1);
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}.` };
return capacity;
}
async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> { async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
const itemId = String(data.get('item') || '').trim(); const itemId = String(data.get('item') || '').trim();
@ -57,12 +73,15 @@ async function slotPayload(data: FormData, pb: Pb): Promise<SlotPayload> {
} }
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' }; 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;
const duration = Number(item.duration) || 0; const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000); const end = new Date(start.getTime() + duration * 60_000);
// Status is never taken from the form: it is owned by the booking flow // Bookings are never stored on the slot: places are counted from orders
// (held by a basket, booked by a paid order). New slots start available. // and basket holds by the shop hook, which also works out blocking.
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } }; return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), capacity, notes } };
} }
/** 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. */
@ -75,6 +94,14 @@ function dateRange(data: FormData): { fromDate: string; toDate: string } | { err
return { fromDate, toDate }; return { fromDate, toDate };
} }
/** Slot details for the days `fromKey`–`toKey` (inclusive), or null if PocketBase can't be read. */
function slotsForDays(pb: Pb, fromKey: string, toKey: string, item = '') {
return loadSlotDetails(pb, { from: dayStartIso(fromKey), to: dayStartIso(addDaysToKey(toKey, 1)), item }).catch((e) => {
console.error('[slots] could not load slot details', e);
return null;
});
}
async function bookableService(pb: Pb, itemId: string) { async function bookableService(pb: Pb, itemId: string) {
if (!itemId) return null; if (!itemId) return null;
const item = await pb.collection('items').getOne(itemId).catch(() => null); const item = await pb.collection('items').getOne(itemId).catch(() => null);
@ -84,14 +111,14 @@ async function bookableService(pb: Pb, itemId: string) {
/** /**
* 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 of the same
* service (existing, or accepted earlier in this run). Different services * service (existing, or accepted earlier in this run). Different services
* may overlap freely — there is no cross-service collision detection. * may share a time: whichever is booked first blocks the others.
*/ */
function filterCandidates(candidates: (PlannedSlot & { item: string })[], existing: ExistingSlot[]) { function filterCandidates(candidates: Candidate[], 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(slot.item, [...(taken.get(slot.item) ?? []), slot]);
const accepted: typeof candidates = []; const accepted: Candidate[] = [];
let skippedPast = 0; let skippedPast = 0;
let skippedOverlap = 0; let skippedOverlap = 0;
for (const candidate of candidates) { for (const candidate of candidates) {
@ -117,13 +144,7 @@ function bulkResult(fields: Partial<BulkResult> & Pick<BulkResult, 'action' | 'i
} }
/** Preview, or create, the accepted candidates. */ /** Preview, or create, the accepted candidates. */
async function previewOrCreate( async function previewOrCreate(pb: Pb, action: 'generate' | 'copy', intent: string, result: ReturnType<typeof filterCandidates>) {
pb: Pb,
action: 'generate' | 'copy',
intent: string,
result: ReturnType<typeof filterCandidates>,
notesFor: (slot: PlannedSlot & { item: string }) => string
) {
const { accepted, skippedPast, skippedOverlap } = result; const { accepted, skippedPast, skippedOverlap } = result;
if (accepted.length > MAX_BULK_SLOTS) { if (accepted.length > MAX_BULK_SLOTS) {
return fail(400, { message: `That would create ${accepted.length} slots — at most ${MAX_BULK_SLOTS} at once. Choose a shorter range.` }); return fail(400, { message: `That would create ${accepted.length} slots — at most ${MAX_BULK_SLOTS} at once. Choose a shorter range.` });
@ -138,7 +159,7 @@ async function previewOrCreate(
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({ item: slot.item, start: slot.start, end: slot.end, notes: notesFor(slot), status: 'available' }) 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 });
} }
@ -156,36 +177,15 @@ export const load: PageServerLoad = async ({ locals, url }) => {
id: record.id, id: record.id,
name: String(record.name || ''), name: String(record.name || ''),
duration: Number(record.duration) || 0, duration: Number(record.duration) || 0,
bufferMinutes: Number(record.bufferMinutes) || 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 slotRecords = await locals.pb const slots = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]);
.collection('slots')
.getFullList({
filter: locals.pb.filter('start >= {:from} && start < {:to}', {
from: new Date(dayStartIso(grid[0])),
to: new Date(dayStartIso(addDaysToKey(grid[grid.length - 1], 1)))
}),
sort: 'start',
expand: 'item'
})
.catch(() => []);
const slots = slotRecords.map((record) => ({
id: record.id,
item: String(record.item || ''),
itemName: String(record.expand?.item?.name || 'Unknown service'),
itemDuration: record.expand?.item?.duration ?? null,
start: String(record.start || ''),
end: record.end ? String(record.end) : '',
status: String(record.status || 'available') as SlotStatus,
heldUntil: record.heldUntil ? String(record.heldUntil) : '',
order: record.order ? String(record.order) : '',
notes: String(record.notes || '')
}));
return { items, slots, month, today }; return { items, slots: slots ?? [], slotsError: slots === null, month, today };
}; };
export const actions: Actions = { export const actions: Actions = {
@ -193,9 +193,7 @@ export const actions: Actions = {
const data = await request.formData(); const data = await request.formData();
const result = await slotPayload(data, locals.pb); const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error }); if ('error' in result) return fail(400, { message: result.error });
const created = await attempt('Could not create the slot.', () => const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload));
locals.pb.collection('slots').create({ ...result.payload, status: 'available' })
);
if (!created.ok) return created.failure; if (!created.ok) return created.failure;
return { ok: true }; return { ok: true };
}, },
@ -204,15 +202,20 @@ export const actions: Actions = {
const id = String(data.get('id') || ''); const id = String(data.get('id') || '');
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 a customer may have // Re-read the slot: the page may be stale, and customers may have
// held or booked it since. Only notes can change while it's held. // booked or held places since. Once any place is taken, the service
const current = await locals.pb.collection('slots').getOne(id).catch(() => null); // and time are fixed; places can't go below what's taken.
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) return fail(404, { message: 'This slot no longer exists.' }); if (!current) return fail(404, { message: 'This slot no longer exists.' });
if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' });
let patch: Record<string, string>; const taken = seatsTaken(current);
if (isHoldActive(current)) { let patch: Record<string, string | number>;
patch = { notes: String(data.get('notes') || '').trim() }; if (taken > 0) {
const capacity = parseCapacity(data, { capacity: current.capacity });
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.` });
patch = { capacity, notes: String(data.get('notes') || '').trim() };
} else { } else {
const result = await slotPayload(data, locals.pb); const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error }); if ('error' in result) return fail(400, { message: result.error });
@ -226,9 +229,10 @@ export const actions: Actions = {
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: 'Slot id is required.' }); if (!id) return fail(400, { message: 'Slot id is required.' });
const record = await locals.pb.collection('slots').getOne(id).catch(() => null); const current = await loadSlotDetail(locals.pb, id).catch(() => undefined);
if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' }); if (current === undefined) return fail(400, { message: 'Could not read the slot — is the database reachable?' });
if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' }); 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.' });
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 };
@ -245,6 +249,8 @@ export const actions: Actions = {
if (!item) return fail(400, { message: 'Choose a bookable service.' }); if (!item) return fail(400, { message: 'Choose a bookable service.' });
const duration = Number(item.duration) || 0; const duration = Number(item.duration) || 0;
if (duration <= 0) return fail(400, { message: `“${item.name}” has no duration — set one under Services & products.` }); 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); 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.' }); if (!weekdays.length) return fail(400, { message: 'Choose at least one weekday.' });
@ -267,17 +273,12 @@ export const actions: Actions = {
const planned = planGeneratedSlots({ ...range, weekdays, windows, durationMinutes: duration, bufferMinutes, timeZone: siteTimezone() }); 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.' }); if (!planned.length) return fail(400, { message: 'No slots fit those days and times.' });
const existing = await loadSlotsBetween( const existing = await slotsForDays(locals.pb, range.fromDate, range.toDate, item.id);
locals.pb,
dayStartIso(range.fromDate),
dayStartIso(addDaysToKey(range.toDate, 1)),
item.id
).catch(() => null);
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' }); 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 })), existing); const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id, capacity, notes })), existing);
return previewOrCreate(locals.pb, 'generate', intent, result, () => notes); return previewOrCreate(locals.pb, 'generate', intent, result);
}, },
/** Repeat one week's slots (all services, or one) for the following weeks. */ /** Repeat one week's slots (all services, or one) for the following weeks. */
@ -290,33 +291,26 @@ export const actions: Actions = {
if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` }); if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` });
const itemId = String(data.get('item') || ''); const itemId = String(data.get('item') || '');
const source = await loadSlotsBetween(locals.pb, dayStartIso(sourceWeek), dayStartIso(addDaysToKey(sourceWeek, 7)), itemId).catch(() => null); const source = await slotsForDays(locals.pb, sourceWeek, addDaysToKey(sourceWeek, 6), itemId);
const existing = await loadSlotsBetween( const existing = await slotsForDays(locals.pb, addDaysToKey(sourceWeek, 7), addDaysToKey(sourceWeek, 7 * (weeks + 1) - 1), itemId);
locals.pb,
dayStartIso(addDaysToKey(sourceWeek, 7)),
dayStartIso(addDaysToKey(sourceWeek, 7 * (weeks + 1))),
itemId
).catch(() => null);
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.length) return fail(400, { message: 'That week has no slots to copy.' });
const notesByStart = new Map<string, string>(); // Copies are new, empty slots: same service, places and notes.
const candidates: (PlannedSlot & { item: string })[] = []; const candidates: Candidate[] = [];
for (let week = 1; week <= weeks; week++) { for (let week = 1; week <= weeks; week++) {
for (const slot of source) { for (const slot of source) {
const start = shiftByDays(slot.start, 7 * week, siteTimezone()); const start = shiftByDays(slot.start, 7 * week, siteTimezone());
if (!start) continue; if (!start) continue;
const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString(); const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString();
candidates.push({ item: slot.item, start, end }); candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes });
notesByStart.set(`${slot.item}|${start}`, slot.notes);
} }
} }
const result = filterCandidates(candidates, existing); return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing));
return previewOrCreate(locals.pb, 'copy', intent, result, (slot) => notesByStart.get(`${slot.item}|${slot.start}`) ?? '');
}, },
/** Delete the free slots in a date range. Booked and currently-held slots stay. */ /** Delete the slots in a date range that have no places taken. */
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');
@ -324,10 +318,10 @@ 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 loadSlotsBetween(locals.pb, dayStartIso(range.fromDate), dayStartIso(addDaysToKey(range.toDate, 1)), itemId).catch(() => null); const slots = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId);
if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' }); if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' });
const removable = slots.filter((slot) => slot.status !== 'booked' && !isHoldActive(slot)); const removable = slots.filter((slot) => seatsTaken(slot) === 0);
const summary = { const summary = {
action: 'clear' as const, action: 'clear' as const,
kept: slots.length - removable.length, kept: slots.length - removable.length,
@ -339,8 +333,8 @@ export const actions: Actions = {
// 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. // it in 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 locals.pb.collection('slots').getOne(slot.id); const fresh = await loadSlotDetail(locals.pb, slot.id);
if (fresh.status === 'booked' || isHoldActive(fresh)) throw new Error('taken since the preview'); if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview');
await locals.pb.collection('slots').delete(slot.id); await locals.pb.collection('slots').delete(slot.id);
}); });
return bulkResult({ ...summary, intent: 'done', count: deleted, failed: removable.length - deleted }); return bulkResult({ ...summary, intent: 'done', count: deleted, failed: removable.length - deleted });

View file

@ -7,14 +7,15 @@
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 { WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys } from '$lib/slots'; import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
import type { BulkResult } from '$lib/slots'; import type { BulkResult, SlotState } from '$lib/slots';
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.item === serviceFilter));
type Slot = (typeof slots)[number]; type Slot = (typeof slots)[number];
let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot])));
// ── Month grid (date keys in the site timezone) ── // ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4; const MAX_CHIPS = 4;
@ -47,14 +48,34 @@
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 (booked or taken in the meantime)' : 'saved'}.` : ''; const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`; return `${verb} ${n(result.count)}.${failed}`;
} }
function statusClass(status: string) { const STATE_CLASSES: Record<SlotState, string> = {
if (status === 'booked') return 'border-info/40 bg-info/15'; free: 'border-success/40 bg-success/10',
if (status === 'held') return 'border-warning/50 bg-warning/20'; held: 'border-warning/50 bg-warning/20',
return 'border-success/40 bg-success/10'; booked: 'border-info/40 bg-info/15',
full: 'border-info/60 bg-info/30',
blocked: 'border-base-300 bg-base-100 text-base-content/40 line-through'
};
const BADGE_CLASSES: Record<SlotState, string> = {
free: 'badge-success',
held: 'badge-warning',
booked: 'badge-info badge-soft',
full: 'badge-info',
blocked: 'badge-ghost'
};
/** "2/8" for group slots, '' for one-to-one. */
function places(slot: Slot) {
return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
}
/** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */
function blockedReason(slot: Slot) {
const blocker = slotsById.get(slot.blockedBy);
return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking';
} }
function openDay(key: string) { function openDay(key: string) {
@ -79,15 +100,17 @@
id: string; id: string;
item: string; item: string;
start: string; start: string;
status: string; capacity: string;
heldUntil: string; booked: number;
held: number;
notes: string; notes: string;
}; };
let draft = $state<SlotDraft>(emptyDraft()); let draft = $state<SlotDraft>(emptyDraft());
let editorError = $state(''); let editorError = $state('');
let action = $derived(draft.id ? '?/update' : '?/create'); let action = $derived(draft.id ? '?/update' : '?/create');
let isHeld = $derived(draft.status === 'held'); // Once any place is taken, the service and time are fixed (customers booked them).
let taken = $derived(draft.booked + draft.held);
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 (!selectedItem || !draft.start) return '';
@ -99,7 +122,7 @@
function emptyDraft(day = ''): SlotDraft { function emptyDraft(day = ''): SlotDraft {
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone); const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
return { id: '', item: serviceFilter, start, status: 'available', heldUntil: '', notes: '' }; return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' };
} }
// 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
@ -129,8 +152,9 @@
id: slot.id, id: slot.id,
item: slot.item, item: slot.item,
start: toZonedDatetimeInput(slot.start, data.timezone), start: toZonedDatetimeInput(slot.start, data.timezone),
status: slot.status, capacity: String(slot.capacity),
heldUntil: slot.heldUntil, booked: slot.booked,
held: slot.held,
notes: slot.notes notes: slot.notes
}; };
showDay = false; showDay = false;
@ -157,6 +181,7 @@
{#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if} {#if form?.message}<div class="alert alert-error" role="alert">{form.message}</div>{/if}
{#if bulkDone}<div class="alert alert-success" role="status">{bulkMessage(bulkDone)}</div>{/if} {#if bulkDone}<div class="alert alert-success" role="status">{bulkMessage(bulkDone)}</div>{/if}
{#if !items.length}<div class="alert" role="status">Add a bookable service under Services & products first.</div>{/if} {#if !items.length}<div class="alert" role="status">Add a bookable service under Services & products first.</div>{/if}
{#if data.slotsError}<div class="alert alert-error" role="alert">Could not load this month’s slots — is the database reachable?</div>{/if}
<div class="rounded-box bg-base-100 p-5 shadow"> <div class="rounded-box bg-base-100 p-5 shadow">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3"> <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
@ -189,9 +214,16 @@
> >
<div class="space-y-1"> <div class="space-y-1">
{#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)} {#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)}
<button class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {statusClass(slot.status)}" type="button" title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {slot.status}" onclick={() => (slot.status === 'booked' ? openDay(key) : editSlot(slot))}> {@const state = slotState(slot)}
<button
class="block w-full truncate rounded border px-1 text-left text-[0.7rem] leading-5 {STATE_CLASSES[state]}"
type="button"
title="{formatTime(slot.start, data.timezone)} {slot.itemName} — {state === 'blocked' ? blockedReason(slot) : SLOT_STATE_LABELS[state]}{places(slot) ? ` (${places(slot)})` : ''}"
onclick={() => editSlot(slot)}
>
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span> <span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
<span class="hidden lg:inline">{slot.itemName}</span> <span class="hidden lg:inline">{slot.itemName}</span>
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
</button> </button>
{/each} {/each}
{#if daySlotList.length > MAX_CHIPS} {#if daySlotList.length > MAX_CHIPS}
@ -203,9 +235,10 @@
</div> </div>
<div class="mt-4 flex flex-wrap gap-4 text-xs text-base-content/70"> <div class="mt-4 flex flex-wrap gap-4 text-xs text-base-content/70">
<span class="flex items-center gap-1"><span class="inline-block size-3 rounded border {statusClass('available')}"></span> Available</span> {#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 {statusClass('held')}"></span> In a basket</span> <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 {statusClass('booked')}"></span> Booked</span> {/each}
<span>— a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.</span>
</div> </div>
</div> </div>
@ -214,23 +247,19 @@
<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>Duration</th><th>Status</th><th></th></tr></thead> <thead><tr><th>Service</th><th>Date</th><th>Places</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)}
<tr> <tr>
<td><span class="font-semibold">{slot.itemName}</span></td> <td><span class="font-semibold">{slot.itemName}</span></td>
<td>{formatDateTime(slot.start, data.timezone)}</td> <td>{formatDateTime(slot.start, data.timezone)}</td>
<td>{slot.itemDuration ? `${slot.itemDuration} min` : '—'}</td> <td>{slot.booked + slot.held}/{slot.capacity}</td>
<td> <td>
<span <span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span>
class="badge capitalize"
class:badge-success={slot.status === 'available'}
class:badge-warning={slot.status === 'held'}
class:badge-info={slot.status === 'booked'}
>{slot.status}</span>
</td> </td>
<td class="text-right"> <td class="text-right">
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} title={slot.status === 'booked' ? 'Booked slots can’t be edited' : undefined} onclick={() => editSlot(slot)}>Edit</button> <button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
</td> </td>
</tr> </tr>
{:else} {:else}
@ -250,19 +279,16 @@
{#if daySlots.length} {#if daySlots.length}
<ul class="divide-y divide-base-300"> <ul class="divide-y divide-base-300">
{#each daySlots as slot (slot.id)} {#each daySlots as slot (slot.id)}
{@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">{formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''}</span>
<span class="min-w-0 flex-1"> <span class="min-w-0 flex-1">
<span class="block truncate">{slot.itemName}</span> <span class="block truncate">{slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''}</span>
{#if state === 'blocked'}<span class="block truncate text-xs text-base-content/60">{blockedReason(slot)}</span>{/if}
{#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 <span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
class="badge capitalize" <button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
class:badge-success={slot.status === 'available'}
class:badge-warning={slot.status === 'held'}
class:badge-info={slot.status === 'booked'}
>{slot.status}</span>
<button class="btn btn-sm" type="button" disabled={slot.status === 'booked'} onclick={() => editSlot(slot)}>Edit</button>
</li> </li>
{/each} {/each}
</ul> </ul>
@ -284,15 +310,15 @@
{#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 isHeld} {#if taken}
<div class="alert alert-warning mb-2 text-sm"> <div class="alert alert-warning mb-2 text-sm">
This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed. {[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> </div>
{/if} {/if}
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Service</span> <span class="fieldset-legend">Service</span>
<select class="select w-full" name="item" required disabled={isHeld} bind:value={draft.item}> <select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}>
<option value="" disabled>Select a service…</option> <option value="" disabled>Select a service…</option>
{#each items as item (item.id)} {#each items as item (item.id)}
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option> <option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
@ -302,17 +328,23 @@
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Start ({data.timezone})</span> <span class="fieldset-legend">Start ({data.timezone})</span>
<input class="input w-full" type="datetime-local" name="start" required disabled={isHeld} bind:value={draft.start} /> <input class="input w-full" type="datetime-local" name="start" required disabled={taken > 0} bind:value={draft.start} />
{#if endLabel}<span class="label">{endLabel}</span>{/if} {#if endLabel}<span class="label">{endLabel}</span>{/if}
</label> </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">More than 1 for a group session.{draft.id ? '' : ' Empty = the service’s own.'}</span>
</label>
<label class="fieldset"> <label class="fieldset">
<span class="fieldset-legend">Notes</span> <span class="fieldset-legend">Notes</span>
<textarea class="textarea w-full" name="notes" bind:value={draft.notes}></textarea> <textarea class="textarea w-full" name="notes" bind:value={draft.notes}></textarea>
</label> </label>
<div class="modal-action justify-between"> <div class="modal-action justify-between">
{#if draft.id && !isHeld} {#if draft.id && !taken}
<button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit('Delete this slot?')}>Delete</button> <button class="btn btn-error btn-outline" type="submit" formaction="?/delete" formnovalidate onclick={confirmSubmit('Delete this slot?')}>Delete</button>
{:else} {:else}
<span></span> <span></span>

View file

@ -42,6 +42,40 @@ export type BulkResult = {
failed: number; failed: number;
}; };
/**
* A slot with its places and blocking, as the shop hook reports it to the
* admin (GET /api/shop/slots?detail=1). Places are taken by paid orders
* (`booked`) and by baskets whose hold hasn't lapsed (`held`); `blockedBy`
* is the overlapping slot whose booking/hold blocks this one.
*/
export type SlotDetail = PlannedSlot & {
id: string;
item: string;
itemName: string;
capacity: number;
notes: string;
booked: number;
held: number;
blockedBy: string;
};
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
export const SLOT_STATE_LABELS: Record<SlotState, string> = {
free: 'Available',
held: 'In a basket',
booked: 'Booked',
full: 'Full',
blocked: 'Blocked'
};
export function slotState(slot: Pick<SlotDetail, 'booked' | 'held' | 'capacity' | 'blockedBy'>): SlotState {
if (slot.booked + slot.held >= slot.capacity) return 'full';
if (slot.booked) return 'booked';
if (slot.held) return 'held';
return slot.blockedBy ? 'blocked' : 'free';
}
/** One generate/copy run may create at most this many slots. */ /** One generate/copy run may create at most this many slots. */
export const MAX_BULK_SLOTS = 1000; export const MAX_BULK_SLOTS = 1000;