Windows: choose the start-time step (10–60 min, default 30)

A window on fixed steps now has gridMinutes; the admin picks it when
creating or generating windows, and copies keep it. Added to the
(unmerged, undeployed) time-windows migration and pb_schema.json.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hy2vMnHJYP7QGsiH21zHxW
This commit is contained in:
agent 2026-10-25 21:03:40 +00:00
parent 6ab0b75ec3
commit ce3866550a
8 changed files with 69 additions and 26 deletions

View file

@ -113,7 +113,7 @@ If schema import fails because of a PocketBase version mismatch, create these co
Commerce collections (see the Stripe section above for context):
- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `durations` json (services: `[{ minutes, price }]`, the lengths it can be booked for; `price` is then kept at the lowest of them), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new group sessions), `active` bool
- `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
- `slots` — `kind` select `window|session`, `items` relation→items (multiple: the services bookable in a window; a session's one service), `start` date, `end` date, `startTimes` select `grid|edges` and `gridMinutes` number (windows), `capacity` number (sessions: places), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
- `baskets` — `status` select `active|completed|abandoned`, `expiresAt` date, `email` text, `customerDetails` json, `stripePaymentIntentId` text
- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number (places, for a slot line), `lineType` select `item|slot`, `start` date and `minutes` number (a slot line's booked time), `heldUntil` date (a slot line's hold)
- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text, `anonymisedAt` date (set by GDPR erasure/retention; `email` is then empty)
@ -138,7 +138,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
- `/pages/[slug]` — block editor with draft preview
- `/calendar` — events shown by Upcoming Calendar blocks
- `/items` — services and products shown in Shop blocks
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — every 30 min, or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). Windows may not overlap each other, nor sessions of the same service; bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.
- `/slots` — when the practitioner can be booked: **windows** (e.g. 09:00–12:00, with the services bookable in it and where bookings may start — in fixed steps (every 10–60 min, default 30), or only at the start/end of the free time) and **group sessions** (one service at one of its lengths, fixed time, places). Month calendar, a day view with free time and bookings, and bulk tools — *Generate slots* (date range × weekdays × hours → windows, or sessions spaced by length + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with nothing booked). Windows may not overlap each other, nor sessions of the same service; bulk tools preview first and skip past or overlapping slots. A window can't shrink past a booking in it.
- `/items` lists each service's lengths and prices (*Lengths and prices* rows); the Shop block shows a slider between them.
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons
- `/customers` — customer personal data (GDPR): search, export as JSON, correct details on every order, erase, and the data-retention settings (see *Personal data (GDPR)*)
@ -155,7 +155,7 @@ The shop/checkout blocks implement a basket-based booking flow: visitors add ser
- A **booking** is a paid order line or a basket line whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts), each with its own `start` and `minutes`. It keeps the practitioner busy until its service's get-ready time (`items.bufferMinutes`) is over. A lapsed hold stops counting immediately; the cron only deletes the line. The checkout shows a countdown to the first hold running out, offers "Keep it 10 more minutes" (basket action `renew_holds`; holds are extended, never shortened) in the last 3 minutes, and says which times ran out when one does.
- One practitioner works every service, so no booking may overlap another — whatever the service, whatever the slot — including get-ready time.
- A **window** offers its services at any of their lengths. A booking must start and end inside it (its get-ready time may run past the end) and fit before the next booking. `startTimes = grid`: every 30 min from the window's start. `edges`: only right at the start or the end of each free stretch — a 09:00–12:00 window offers a 1-hour massage at 09:00 or 11:00; once 09:00 is booked (+15 min get-ready) it offers 10:15 or 11:00 — so time is taken from the ends and no gaps are left.
- A **window** offers its services at any of their lengths. A booking must start and end inside it (its get-ready time may run past the end) and fit before the next booking. `startTimes = grid`: every `gridMinutes` (chosen per window: 10, 15, 20, 30, 45 or 60; default 30) from the window's start. `edges`: only right at the start or the end of each free stretch — a 09:00–12:00 window offers a 1-hour massage at 09:00 or 11:00; once 09:00 is booked (+15 min get-ready) it offers 10:15 or 11:00 — so time is taken from the ends and no gaps are left.
- A **group session** has `capacity` places for one service at one length; places are counted from its bookings. With any place taken its whole time is busy (windows lose that time); it stays bookable until full, and can't be booked while another booking overlaps it.
- `GET /api/shop/slots?item=&minutes=&from=&to=` lists the times a customer can book for one service and length (public; the Shop block fetches it through each app's `GET /api/slots` for the months on screen), plus `next` — the first bookable time after the range — when there are none in it. With `?detail=1` a signed-in admin gets every slot in a range with its bookings, free stretches and what blocks it (the `/slots` page).
- Adding to a basket (`add_slot`: `slotId` plus `itemId`, `minutes`, `start` for a window, or `seats` for a session) and changing a group line's places re-check everything inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times. The price is the service's price for the booked length, read again at checkout.

View file

@ -3,7 +3,7 @@
import { enhance } from '$app/forms';
import Modal from '$lib/admin/Modal.svelte';
import SegmentedControl from '$lib/admin/editors/SegmentedControl.svelte';
import { START_TIMES_HINTS, START_TIMES_LABELS, WEEKDAYS, addDaysToKey, startTimesInWindows, timeToMinutes, type TimeWindow } from '$lib/slots';
import { DEFAULT_GRID_MINUTES, GRID_STEP_OPTIONS, START_TIMES_LABELS, WEEKDAYS, startTimesHint, addDaysToKey, startTimesInWindows, timeToMinutes, type TimeWindow } from '$lib/slots';
import type { ItemDuration, SlotKind, StartTimesMode } from '$lib/types';
import { formatDuration } from '$shared/items';
import BulkActions from './BulkActions.svelte';
@ -29,6 +29,7 @@
// windows
items: [] as string[],
startTimes: 'grid' as StartTimesMode,
gridMinutes: DEFAULT_GRID_MINUTES,
// group sessions
item: '',
minutes: '',
@ -149,7 +150,15 @@
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>
{#if draft.startTimes === 'grid'}
<label class="mt-2 flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-medium">Step</span>
<select class="select select-sm w-40" name="gridMinutes" bind:value={draft.gridMinutes}>
{#each GRID_STEP_OPTIONS as step (step)}<option value={step}>Every {step} min</option>{/each}
</select>
</label>
{/if}
<span class="label whitespace-normal">{startTimesHint(draft.startTimes, draft.gridMinutes)}</span>
</div>
<p class="rounded-box bg-base-200 px-4 py-2 text-sm">
{draft.windows.length} window{draft.windows.length === 1 ? '' : 's'} per chosen day, {windowHours} hours in total.

View file

@ -5,6 +5,8 @@ import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots';
import {
DEFAULT_GRID_MINUTES,
GRID_STEP_OPTIONS,
MAX_BULK_SLOTS,
addDaysToKey,
dateKeysBetween,
@ -35,6 +37,7 @@ type SlotFields = {
start: string;
end: string;
startTimes: StartTimesMode | '';
gridMinutes: number | null;
capacity: number | null;
notes: string;
};
@ -74,8 +77,11 @@ function parseCapacity(data: FormData, fallback: number): number | { error: stri
return capacity;
}
function parseStartTimes(data: FormData): StartTimesMode {
return String(data.get('startTimes')) === 'edges' ? 'edges' : 'grid';
/** A window's start-times mode and, for `grid`, its step (one of GRID_STEP_OPTIONS). */
function parseStartTimes(data: FormData): { startTimes: StartTimesMode; gridMinutes: number | null } {
if (String(data.get('startTimes')) === 'edges') return { startTimes: 'edges', gridMinutes: null };
const step = Number(data.get('gridMinutes'));
return { startTimes: 'grid', gridMinutes: GRID_STEP_OPTIONS.includes(step) ? step : DEFAULT_GRID_MINUTES };
}
/** The services ticked in a window form, all of them active services. */
@ -98,7 +104,7 @@ function windowFields(data: FormData, services: Service[]): SlotFields | { error
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() };
return { kind: 'window', items, start, end, ...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. */
@ -113,7 +119,7 @@ function sessionFields(data: FormData, services: Service[]): SlotFields | { erro
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() };
return { kind: 'session', items: [service.id], start, end, startTimes: '', gridMinutes: null, capacity, notes: String(data.get('notes') || '').trim() };
}
/**
@ -331,12 +337,12 @@ export const actions: Actions = {
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 }));
candidates = planned.map((slot) => ({ ...slot, kind: 'session', items: [service.id], startTimes: '', gridMinutes: null, 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 }));
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.' });
@ -367,7 +373,7 @@ export const actions: Actions = {
const start = shiftByDays(slot.start, 7 * week, siteTimezone());
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 });
candidates.push({ kind: slot.kind, items: slot.items, start, end, startTimes: slot.startTimes ?? '', gridMinutes: slot.gridMinutes ?? null, capacity: slot.capacity ?? null, notes: slot.notes });
}
}

View file

@ -8,7 +8,7 @@
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, START_TIMES_HINTS, START_TIMES_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots';
import { DEFAULT_GRID_MINUTES, GRID_STEP_OPTIONS, SLOT_STATE_LABELS, START_TIMES_LABELS, WEEKDAYS, startTimesHint, startTimesLabel, 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';
@ -123,6 +123,7 @@
to: string;
items: string[];
startTimes: StartTimesMode;
gridMinutes: number;
// session
item: string;
minutes: string;
@ -158,6 +159,7 @@
to: '12:00',
items: serviceFilter ? [serviceFilter] : oneToOneServices(items),
startTimes: 'grid',
gridMinutes: DEFAULT_GRID_MINUTES,
item: serviceFilter,
minutes: service?.durations[0] ? String(service.durations[0].minutes) : '',
start: `${date}T09:00`,
@ -212,6 +214,7 @@
to: toZonedDatetimeInput(slot.end, data.timezone).slice(11, 16),
items: [...slot.items],
startTimes: slot.startTimes ?? 'grid',
gridMinutes: slot.gridMinutes ?? DEFAULT_GRID_MINUTES,
item: slot.items[0] ?? '',
minutes: String(slot.minutes ?? ''),
start,
@ -355,7 +358,7 @@
{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}
{#if slot.kind === 'window'}{freeLabel(slot)} · {startTimesLabel(slot.startTimes ?? 'grid', slot.gridMinutes)}{: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>
@ -459,7 +462,15 @@
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>
{#if draft.startTimes === 'grid'}
<label class="mt-2 flex items-center gap-3">
<span class="w-28 shrink-0 text-sm font-medium">Step</span>
<select class="select select-sm w-40" name="gridMinutes" bind:value={draft.gridMinutes}>
{#each GRID_STEP_OPTIONS as step (step)}<option value={step}>Every {step} min</option>{/each}
</select>
</label>
{/if}
<span class="label whitespace-normal">{startTimesHint(draft.startTimes, draft.gridMinutes)}</span>
</div>
{:else}
{#if sessionLocked}

View file

@ -72,6 +72,8 @@ export type SlotDetail = PlannedSlot & {
held: number;
// window
startTimes?: StartTimesMode;
/** `grid` windows: minutes between start times. */
gridMinutes?: number;
free?: PlannedSlot[];
// session
minutes?: number;
@ -80,14 +82,25 @@ export type SlotDetail = PlannedSlot & {
};
export const START_TIMES_LABELS: Record<StartTimesMode, string> = {
grid: 'Every 30 min',
grid: 'Fixed steps',
edges: 'Next free time'
};
export const START_TIMES_HINTS: Record<StartTimesMode, string> = {
grid: 'Customers can start at any half hour where their booking fits.',
edges: 'Customers can only book right at the start or the end of the free time, so the window shrinks from either end and no gaps are left.'
};
/** Step choices for `grid` windows, in minutes; 30 is the default. */
export const GRID_STEP_OPTIONS = [10, 15, 20, 30, 45, 60];
export const DEFAULT_GRID_MINUTES = 30;
/** What a window's start-times setting means, for the admin forms and day view. */
export function startTimesHint(mode: StartTimesMode, gridMinutes = DEFAULT_GRID_MINUTES) {
return mode === 'grid'
? `Customers can start every ${gridMinutes} minutes from the window’s start, wherever their booking fits.`
: 'Customers can only book right at the start or the end of the free time, so the window shrinks from either end and no gaps are left.';
}
/** "Every 15 min" / "Next free time". */
export function startTimesLabel(mode: StartTimesMode, gridMinutes = DEFAULT_GRID_MINUTES) {
return mode === 'grid' ? `Every ${gridMinutes} min` : START_TIMES_LABELS.edges;
}
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';

View file

@ -356,6 +356,7 @@
{ "id": "sel_slotkind001", "name": "kind", "type": "select", "system": false, "required": true, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["window", "session"] },
{ "id": "rel_slotitems01", "name": "items", "type": "relation", "system": false, "required": false, "presentable": false, "hidden": false, "collectionId": "pbc_items00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 50 },
{ "id": "sel_slotstarts1", "name": "startTimes", "type": "select", "system": false, "required": false, "presentable": false, "hidden": false, "maxSelect": 1, "values": ["grid", "edges"] },
{ "id": "num_slotgridmin1", "name": "gridMinutes", "type": "number", "system": false, "required": false, "presentable": false, "hidden": false, "min": 5, "max": 240, "onlyInt": true },
{ "id": "date_slotstart0", "name": "start", "type": "date", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "date_slotend000", "name": "end", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } },
{ "id": "num_slotcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },

View file

@ -63,8 +63,8 @@ function pbDate(ms) {
const DAY_MS = 24 * 60 * 60 * 1000;
const MINUTE_MS = 60 * 1000;
/** Window start times in `grid` mode are this far apart, from the window's start. */
const GRID_MS = 30 * MINUTE_MS;
/** Window start times in `grid` mode are `gridMinutes` apart, from the window's start; this when unset. */
const DEFAULT_GRID_MINUTES = 30;
/** In `edges` mode, a free stretch that has already begun starts at the next quarter hour. */
const EDGE_ROUND_MS = 15 * MINUTE_MS;
@ -128,7 +128,7 @@ function itemLookup(app) {
// A slot is either
// - a `window` (09:00–12:00 with the services that can be booked in it):
// a booking may start wherever its length plus get-ready time is free.
// `startTimes` = `grid`: every 30 minutes from the window's start;
// `startTimes` = `grid`: every `gridMinutes` (default 30) from the window's start;
// `edges`: only right at the start or end of a free stretch, so the
// window shrinks from either end and no unusable gaps are left. A
// booking must end inside the window; its get-ready time may run past.
@ -206,6 +206,7 @@ function availability(app, rangeStart, rangeEnd, options) {
slot.held = count('held');
if (slot.kind === 'window') {
slot.startTimes = record.getString('startTimes') === 'edges' ? 'edges' : 'grid';
slot.gridMinutes = Math.max(5, record.getInt('gridMinutes') || DEFAULT_GRID_MINUTES);
return slot;
}
const service = item(items[0]);
@ -252,7 +253,7 @@ function windowStartTimes(window, item, minutes, busy, now) {
candidates.push(Math.min(window.end - length, (next ? next.start : Infinity) - until));
}
} else {
for (let start = window.start; start + length <= window.end; start += GRID_MS) candidates.push(start);
for (let start = window.start; start + length <= window.end; start += window.gridMinutes * MINUTE_MS) candidates.push(start);
}
return candidates.filter((start, i) => candidates.indexOf(start) === i && fits(start)).sort((a, b) => a - b);
}
@ -337,6 +338,7 @@ function slotDetails(app, query) {
const detail = { id: s.id, kind: s.kind, items: s.items, itemNames: s.itemNames, start: iso(s.start), end: iso(s.end), notes: s.notes, booked: s.booked, held: s.held };
if (s.kind === 'window') {
detail.startTimes = s.startTimes;
detail.gridMinutes = s.gridMinutes;
detail.free = freeTimes(s, busy).map((f) => ({ start: iso(f.start), end: iso(f.end) }));
} else {
detail.minutes = s.minutes;

View file

@ -11,7 +11,7 @@
// - slots.kind: `window` — a stretch of time (09:00–12:00) in which any of
// its `items` can be booked, for any of their durations; each booking
// takes its time plus get-ready time out of the window. `startTimes`
// says where bookings may start: `grid` (every 30 min) or `edges` (only
// says where bookings may start: `grid` (every `gridMinutes`, default 30) or `edges` (only
// right at the start or end of the free time, so no gaps are left).
// `session` — a fixed time for one service with `capacity` places (a
// group class), as slots were before.
@ -113,6 +113,7 @@ migrate(
slots.fields.add(new SelectField({ id: 'sel_slotkind001', name: 'kind', values: ['window', 'session'], maxSelect: 1, required: true }));
slots.fields.add(new RelationField({ id: 'rel_slotitems01', name: 'items', collectionId: items ? items.id : 'pbc_items00001', maxSelect: 50, cascadeDelete: false }));
slots.fields.add(new SelectField({ id: 'sel_slotstarts1', name: 'startTimes', values: ['grid', 'edges'], maxSelect: 1 }));
slots.fields.add(new NumberField({ id: 'num_slotgridmin1', name: 'gridMinutes', min: 5, max: 240, onlyInt: true }));
app.save(slots);
}
},
@ -141,7 +142,7 @@ migrate(
if (slots && !slots.fields.getByName('item')) {
for (const line of app.findRecordsByFilter('basket_lines', "lineType = 'slot'", '', 0, 0)) app.delete(line);
for (const slot of app.findAllRecords('slots')) app.delete(slot);
for (const name of ['kind', 'items', 'startTimes']) {
for (const name of ['kind', 'items', 'startTimes', 'gridMinutes']) {
if (slots.fields.getByName(name)) slots.fields.removeByName(name);
}
slots.fields.add(new RelationField({ id: 'rel_slotitem001', name: 'item', required: true, collectionId: items ? items.id : 'pbc_items00001', maxSelect: 1, cascadeDelete: true }));