Admin: lengths and prices per service; windows and group sessions on /slots
Services get rows of length + price. /slots creates windows (date, hours, services, start-times mode) and group sessions (service, length, start, places); the day view shows free time and bookings. Generate/copy/clear handle both kinds; windows may not overlap and can't shrink past a booking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
parent
eac99b2abe
commit
636b59c706
12 changed files with 667 additions and 329 deletions
|
|
@ -14,6 +14,7 @@ import {
|
|||
monthGridKeys,
|
||||
overlapsAny,
|
||||
planGeneratedSlots,
|
||||
planWindows,
|
||||
shiftByDays,
|
||||
timeToMinutes,
|
||||
type BulkResult,
|
||||
|
|
@ -21,16 +22,24 @@ import {
|
|||
type SlotDetail,
|
||||
type TimeWindow
|
||||
} from '$lib/slots';
|
||||
import type { SlotKind, StartTimesMode } from '$lib/types';
|
||||
import { parseDurations } from '$shared/items';
|
||||
import type { Actions, PageServerLoad } from './$types';
|
||||
|
||||
type Pb = ReturnType<typeof createPocketBase>;
|
||||
|
||||
type SlotPayload =
|
||||
| { payload: { item: string; start: string; end: string; capacity: number; notes: string } }
|
||||
| { error: string };
|
||||
/** What a slot record is saved with. */
|
||||
type SlotFields = {
|
||||
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 Candidate = PlannedSlot & { item: string; capacity: number; notes: string };
|
||||
type Service = { id: string; name: string; durations: { minutes: number; price: number }[]; bufferMinutes: number; capacity: number };
|
||||
|
||||
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
|
||||
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_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
|
||||
* capacity (default 1) when the field is left empty.
|
||||
* Places from the form: a whole number 1–500, or `fallback` (the service's
|
||||
* 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();
|
||||
if (raw === '') return Math.max(1, Number(item.capacity) || 1);
|
||||
if (raw === '') return fallback;
|
||||
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> {
|
||||
const itemId = String(data.get('item') || '').trim();
|
||||
const startValue = String(data.get('start') || '').trim();
|
||||
const notes = String(data.get('notes') || '').trim();
|
||||
function parseStartTimes(data: FormData): StartTimesMode {
|
||||
return String(data.get('startTimes')) === 'edges' ? 'edges' : 'grid';
|
||||
}
|
||||
|
||||
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.
|
||||
const startIso = zonedInputToIso(startValue, siteTimezone());
|
||||
if (!startIso) return { error: 'Invalid start time.' };
|
||||
const start = new Date(startIso);
|
||||
|
||||
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);
|
||||
const start = zonedInputToIso(String(data.get('start') || ''), siteTimezone());
|
||||
if (!start) return { error: 'Choose a start time.' };
|
||||
const capacity = parseCapacity(data, service.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
|
||||
// and basket holds by the shop hook, which also works out blocking.
|
||||
return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), capacity, notes } };
|
||||
/** A slot that `fields` would overlap (ignoring `exceptId`), or null — or undefined if PocketBase can't be read. */
|
||||
async function clashingSlot(pb: Pb, fields: SlotFields, exceptId = '') {
|
||||
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. */
|
||||
|
|
@ -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
|
||||
* service (existing, or accepted earlier in this run). Different services
|
||||
* may share a time: whichever is booked first blocks the others.
|
||||
* Drop candidates that start in the past or overlap a slot they may not
|
||||
* overlap (existing, or accepted earlier in this run — see clashKey).
|
||||
*/
|
||||
function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) {
|
||||
function filterCandidates(candidates: SlotFields[], existing: SlotDetail[]) {
|
||||
const now = Date.now();
|
||||
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 skippedOverlap = 0;
|
||||
for (const candidate of candidates) {
|
||||
|
|
@ -126,13 +174,13 @@ function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) {
|
|||
skippedPast++;
|
||||
continue;
|
||||
}
|
||||
const ranges = taken.get(candidate.item) ?? [];
|
||||
const ranges = taken.get(clashKey(candidate)) ?? [];
|
||||
if (overlapsAny(candidate, ranges)) {
|
||||
skippedOverlap++;
|
||||
continue;
|
||||
}
|
||||
ranges.push(candidate);
|
||||
taken.set(candidate.item, ranges);
|
||||
taken.set(clashKey(candidate), ranges);
|
||||
accepted.push(candidate);
|
||||
}
|
||||
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 });
|
||||
|
||||
const created = await runInBatches(accepted, 'create', (slot) =>
|
||||
pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, capacity: slot.capacity, notes: slot.notes })
|
||||
);
|
||||
const created = await runInBatches(accepted, 'create', (slot) => pb.collection('slots').create(slot));
|
||||
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 }) => {
|
||||
const today = todayKey();
|
||||
const monthParam = url.searchParams.get('month') || '';
|
||||
const month = /^\d{4}-(0[1-9]|1[0-2])$/.test(monthParam) ? monthParam : today.slice(0, 7);
|
||||
|
||||
const itemRecords = await locals.pb
|
||||
.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)
|
||||
}));
|
||||
const items = await loadServices(locals.pb).catch(() => []);
|
||||
|
||||
// Only the slots shown in the month grid (which spans whole weeks).
|
||||
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 = {
|
||||
create: async ({ request, locals }) => {
|
||||
const data = await request.formData();
|
||||
const result = await slotPayload(data, locals.pb);
|
||||
if ('error' in result) return fail(400, { message: result.error });
|
||||
const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload));
|
||||
const services = await loadServices(locals.pb).catch(() => []);
|
||||
const fields = String(data.get('kind')) === 'session' ? sessionFields(data, services) : windowFields(data, services);
|
||||
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;
|
||||
return { ok: true };
|
||||
},
|
||||
|
|
@ -203,23 +260,31 @@ export const actions: Actions = {
|
|||
if (!id) return fail(400, { message: 'Slot id is required.' });
|
||||
|
||||
// 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
|
||||
// and time are fixed; places can't go below what's taken.
|
||||
// booked or held times since.
|
||||
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.' });
|
||||
|
||||
const services = await loadServices(locals.pb).catch(() => []);
|
||||
const taken = seatsTaken(current);
|
||||
let patch: Record<string, string | number>;
|
||||
if (taken > 0) {
|
||||
const capacity = parseCapacity(data, { capacity: current.capacity });
|
||||
|
||||
let patch: Partial<SlotFields>;
|
||||
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 (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 {
|
||||
const result = await slotPayload(data, locals.pb);
|
||||
if ('error' in result) return fail(400, { message: result.error });
|
||||
patch = result.payload;
|
||||
const fields = current.kind === 'session' ? sessionFields(data, services) : windowFields(data, services);
|
||||
if ('error' in fields) return fail(400, { message: fields.error });
|
||||
// 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));
|
||||
if (!updated.ok) return updated.failure;
|
||||
|
|
@ -232,56 +297,55 @@ export const actions: Actions = {
|
|||
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?.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));
|
||||
if (!deleted.ok) return deleted.failure;
|
||||
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 }) => {
|
||||
const data = await request.formData();
|
||||
const intent = String(data.get('intent') || 'preview');
|
||||
const range = dateRange(data);
|
||||
if ('error' in range) return fail(400, { message: range.error });
|
||||
|
||||
const item = await bookableService(locals.pb, String(data.get('item') || ''));
|
||||
if (!item) return fail(400, { message: 'Choose a bookable service.' });
|
||||
const duration = Number(item.duration) || 0;
|
||||
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 days = weekdaysAndHours(data);
|
||||
if ('error' in days) return fail(400, { message: days.error });
|
||||
const services = await loadServices(locals.pb).catch(() => null);
|
||||
if (!services) return fail(400, { message: 'Could not read the services — is the database reachable?' });
|
||||
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 }) => {
|
||||
const data = await request.formData();
|
||||
const intent = String(data.get('intent') || 'preview');
|
||||
|
|
@ -292,25 +356,25 @@ export const actions: Actions = {
|
|||
const itemId = String(data.get('item') || '');
|
||||
|
||||
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.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.
|
||||
const candidates: Candidate[] = [];
|
||||
// Copies are new, empty slots: same kind, services, places, start times and notes.
|
||||
const candidates: SlotFields[] = [];
|
||||
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());
|
||||
if (!start) continue;
|
||||
const end = new Date(instantMs(start) + (instantMs(slot.end) - instantMs(slot.start))).toISOString();
|
||||
candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes });
|
||||
const end = shiftByDays(slot.end, 7 * week, siteTimezone());
|
||||
if (!start || !end) continue;
|
||||
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 }) => {
|
||||
const data = await request.formData();
|
||||
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 });
|
||||
const itemId = String(data.get('item') || '');
|
||||
|
||||
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?' });
|
||||
const details = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId);
|
||||
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 = {
|
||||
action: 'clear' as const,
|
||||
kept: slots.length - removable.length,
|
||||
kept: details.slots.length - removable.length,
|
||||
firstStart: removable[0]?.start ?? '',
|
||||
lastStart: removable.at(-1)?.start ?? ''
|
||||
};
|
||||
if (intent !== 'create') return bulkResult({ ...summary, intent: 'preview', count: removable.length });
|
||||
|
||||
// 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 fresh = await loadSlotDetail(locals.pb, slot.id);
|
||||
if (fresh && seatsTaken(fresh) > 0) throw new Error('taken since the preview');
|
||||
|
|
|
|||
|
|
@ -4,33 +4,39 @@
|
|||
import { formatDateTime, formatTime, toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
|
||||
import { confirmSubmit } from '$lib/admin/confirm';
|
||||
import Modal from '$lib/admin/Modal.svelte';
|
||||
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
|
||||
import ClearSlotsModal from '$lib/admin/slots/ClearSlotsModal.svelte';
|
||||
import CopyWeekModal from '$lib/admin/slots/CopyWeekModal.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 { SlotKind, StartTimesMode } from '$lib/types';
|
||||
import { formatDuration } from '$shared/items';
|
||||
|
||||
let { data, form } = $props();
|
||||
let items = $derived(data.items || []);
|
||||
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];
|
||||
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) ──
|
||||
const MAX_CHIPS = 4;
|
||||
const dayKeyOf = (iso: string) => toZonedDatetimeInput(iso, data.timezone).slice(0, 10);
|
||||
let gridKeys = $derived(monthGridKeys(data.month));
|
||||
let monthLabel = $derived(formatDateKey(`${data.month}-01`, { month: 'long', year: 'numeric' }));
|
||||
let monthEnd = $derived(addDaysToKey(`${addMonthsToKey(data.month, 1)}-01`, -1));
|
||||
let slotsByDay = $derived.by(() => {
|
||||
const byDay = new Map<string, Slot[]>();
|
||||
for (const slot of slots) {
|
||||
const key = toZonedDatetimeInput(slot.start, data.timezone).slice(0, 10);
|
||||
byDay.set(key, [...(byDay.get(key) ?? []), slot]);
|
||||
}
|
||||
for (const slot of slots) byDay.set(dayKeyOf(slot.start), [...(byDay.get(dayKeyOf(slot.start)) ?? []), slot]);
|
||||
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 ──
|
||||
let showEditor = $state(false);
|
||||
|
|
@ -42,13 +48,14 @@
|
|||
let copyFrom = $state('');
|
||||
let clearRange = $state({ from: '', to: '' });
|
||||
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);
|
||||
|
||||
function bulkMessage(result: BulkResult) {
|
||||
const n = (count: number) => `${count} slot${count === 1 ? '' : 's'}`;
|
||||
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}`;
|
||||
}
|
||||
|
||||
|
|
@ -67,15 +74,26 @@
|
|||
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) {
|
||||
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". */
|
||||
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';
|
||||
/** What a window has left, e.g. "Free 10:15–12:00". */
|
||||
function freeLabel(slot: Slot) {
|
||||
if (!slot.free?.length) return 'No free time left';
|
||||
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) {
|
||||
|
|
@ -95,10 +113,19 @@
|
|||
showClear = true;
|
||||
}
|
||||
|
||||
// ── Single slot editor ──
|
||||
// ── Slot editor (a window or a group session) ──
|
||||
type SlotDraft = {
|
||||
id: string;
|
||||
kind: SlotKind;
|
||||
// window
|
||||
date: string;
|
||||
from: string;
|
||||
to: string;
|
||||
items: string[];
|
||||
startTimes: StartTimesMode;
|
||||
// session
|
||||
item: string;
|
||||
minutes: string;
|
||||
start: string;
|
||||
capacity: string;
|
||||
booked: number;
|
||||
|
|
@ -106,23 +133,51 @@
|
|||
notes: string;
|
||||
};
|
||||
|
||||
let draft = $state<SlotDraft>(emptyDraft());
|
||||
let draft = $state<SlotDraft>(emptyDraft('window'));
|
||||
let editorError = $state('');
|
||||
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);
|
||||
// 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 endLabel = $derived.by(() => {
|
||||
if (!selectedItem || !draft.start) return '';
|
||||
if (!draft.start || !draft.minutes) return '';
|
||||
const startIso = zonedInputToIso(draft.start, data.timezone);
|
||||
if (!startIso) return '';
|
||||
const end = new Date(new Date(startIso).getTime() + (Number(selectedItem.duration) || 0) * 60_000);
|
||||
return `Ends at ${formatTime(end.toISOString(), data.timezone)}`;
|
||||
return `Ends at ${formatTime(new Date(new Date(startIso).getTime() + Number(draft.minutes) * 60_000).toISOString(), data.timezone)}`;
|
||||
});
|
||||
|
||||
function emptyDraft(day = ''): SlotDraft {
|
||||
const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone);
|
||||
return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' };
|
||||
function emptyDraft(kind: SlotKind, day = ''): SlotDraft {
|
||||
const date = day || data.today;
|
||||
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
|
||||
|
|
@ -139,20 +194,28 @@
|
|||
};
|
||||
};
|
||||
|
||||
function createSlot(day = '') {
|
||||
function createSlot(kind: SlotKind, day = '') {
|
||||
editorError = '';
|
||||
draft = emptyDraft(day);
|
||||
draft = emptyDraft(kind, day);
|
||||
showDay = false;
|
||||
showEditor = true;
|
||||
}
|
||||
|
||||
function editSlot(slot: Slot) {
|
||||
editorError = '';
|
||||
const start = toZonedDatetimeInput(slot.start, data.timezone);
|
||||
draft = {
|
||||
...emptyDraft(slot.kind),
|
||||
id: slot.id,
|
||||
item: slot.item,
|
||||
start: toZonedDatetimeInput(slot.start, data.timezone),
|
||||
capacity: String(slot.capacity),
|
||||
date: start.slice(0, 10),
|
||||
from: start.slice(11, 16),
|
||||
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,
|
||||
held: slot.held,
|
||||
notes: slot.notes
|
||||
|
|
@ -165,13 +228,16 @@
|
|||
<svelte:head><title>Slots | CMS</title></svelte:head>
|
||||
|
||||
<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>
|
||||
<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 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={() => 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>
|
||||
|
|
@ -218,12 +284,17 @@
|
|||
<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)}
|
||||
title="{range(slot.start, slot.end)} {slot.kind === 'window' ? 'window' : serviceNames(slot)} — {describe(slot, state)}"
|
||||
onclick={() => openDay(key)}
|
||||
>
|
||||
<span class="font-semibold">{formatTime(slot.start, data.timezone)}</span>
|
||||
<span class="hidden lg:inline">{slot.itemName}</span>
|
||||
{#if places(slot)}<span class="hidden md:inline">· {places(slot)}</span>{/if}
|
||||
{#if slot.kind === 'window'}
|
||||
<span class="font-semibold">{range(slot.start, slot.end)}</span>
|
||||
{#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>
|
||||
{/each}
|
||||
{#if daySlotList.length > MAX_CHIPS}
|
||||
|
|
@ -238,32 +309,29 @@
|
|||
{#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>
|
||||
{/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>
|
||||
|
||||
<!-- 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">
|
||||
<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">
|
||||
<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>
|
||||
{#each monthSlots as slot (slot.id)}
|
||||
{@const state = slotState(slot)}
|
||||
<tr>
|
||||
<td><span class="font-semibold">{slot.itemName}</span></td>
|
||||
<td>{formatDateTime(slot.start, data.timezone)}</td>
|
||||
<td>{slot.booked + slot.held}/{slot.capacity}</td>
|
||||
<td>
|
||||
<span class="badge {BADGE_CLASSES[state]}" title={state === 'blocked' ? blockedReason(slot) : undefined}>{SLOT_STATE_LABELS[state]}</span>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button>
|
||||
</td>
|
||||
<td>{formatDateTime(slot.start, data.timezone)}–{formatTime(slot.end, data.timezone)}</td>
|
||||
<td>{slot.kind === 'window' ? 'Window' : 'Group session'}</td>
|
||||
<td>{serviceNames(slot)}</td>
|
||||
<td>{slot.kind === 'session' ? `${slot.booked + slot.held}/${slot.capacity}` : slot.booked + slot.held}</td>
|
||||
<td><span class="badge {BADGE_CLASSES[state]}" title={describe(slot, state)}>{SLOT_STATE_LABELS[state]}</span></td>
|
||||
<td class="text-right"><button class="btn btn-sm" type="button" onclick={() => editSlot(slot)}>Edit</button></td>
|
||||
</tr>
|
||||
{: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}
|
||||
</tbody>
|
||||
</table>
|
||||
|
|
@ -281,10 +349,14 @@
|
|||
{#each daySlots as slot (slot.id)}
|
||||
{@const state = slotState(slot)}
|
||||
<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="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}
|
||||
<span class="block truncate">
|
||||
{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}
|
||||
</span>
|
||||
<span class="badge {BADGE_CLASSES[state]}">{SLOT_STATE_LABELS[state]}</span>
|
||||
|
|
@ -295,48 +367,135 @@
|
|||
{:else}
|
||||
<p class="py-6 text-center text-base-content/60">No slots on this day{serviceFilter ? ' for this service' : ''}.</p>
|
||||
{/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="flex flex-wrap gap-2">
|
||||
<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}
|
||||
</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>
|
||||
</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">
|
||||
<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 taken}
|
||||
<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 !draft.id}
|
||||
<SegmentedControl
|
||||
label="Kind"
|
||||
class="mb-2"
|
||||
options={['window', 'session']}
|
||||
value={draft.kind}
|
||||
formatLabel={(v) => (v === 'window' ? 'Window' : 'Group session')}
|
||||
onChange={(v) => (draft.kind = v as SlotKind)}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Service</span>
|
||||
<select class="select w-full" name="item" required disabled={taken > 0} bind:value={draft.item}>
|
||||
<option value="" disabled>Select a service…</option>
|
||||
{#each items as item (item.id)}
|
||||
<option value={item.id}>{item.name}{item.duration ? ` (${item.duration} min)` : ''}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
{#if draft.kind === 'window'}
|
||||
{#if taken}
|
||||
<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(', ')} — the window can grow or change services, but must still cover every booked time.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Start ({data.timezone})</span>
|
||||
<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}
|
||||
</label>
|
||||
<div class="grid gap-x-4 md:grid-cols-3">
|
||||
<label class="fieldset">
|
||||
<span class="fieldset-legend">Date</span>
|
||||
<input class="input w-full" type="date" name="date" required bind:value={draft.date} />
|
||||
</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">
|
||||
<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>
|
||||
<div class="fieldset">
|
||||
<span class="fieldset-legend">Services that can be booked in this window</span>
|
||||
<div class="grid gap-1 sm:grid-cols-2">
|
||||
{#each items as item (item.id)}
|
||||
<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">
|
||||
<span class="fieldset-legend">Notes</span>
|
||||
|
|
@ -351,7 +510,7 @@
|
|||
{/if}
|
||||
<div class="flex gap-2">
|
||||
<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>
|
||||
</form>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue