- Available times · {formatDateKey(ui.selectedDayKey, { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
+ Available times · {longDate(ui.selectedDayKey)}
- {#each daySlots as slot (slot.id)}
- {@const line = basket.lines.find((l) => l.slot === slot.id)}
- {@const isGroup = slot.capacity > 1}
- {@const label = `${formatTime(slot.start)}${item.duration != null ? ` · ${item.duration} min` : ''}`}
- {#if isGroup && line}
+ {#each byDay.get(ui.selectedDayKey) ?? [] as entry (`${entry.slot}|${entry.start}`)}
+ {@const isGroup = (entry.time?.capacity ?? entry.line?.slotCapacity ?? 1) > 1}
+ {@const free = entry.time?.free ?? 0}
+ {@const pending = ui.pendingKey === `${entry.slot}|${entry.start}`}
+ {@const label = `${formatTime(entry.start)}–${formatTime(entry.end)}`}
+ {#if isGroup && entry.line}
- {label} · {placesLeft(slot.free)}
+ {label} · {placesLeft(free)}
changeSeats(item.id, line, -1)}
+ onclick={() => changeSeats(item.id, entry, -1)}
>
−
- {#if ui.pendingSlotId === slot.id} {:else}{line.quantity}{/if}
- {line.quantity === 1 ? 'place' : 'places'} in your basket
+ {#if pending} {:else}{entry.line.quantity}{/if}
+ {entry.line.quantity === 1 ? 'place' : 'places'} in your basket
changeSeats(item.id, line, 1)}
+ disabled={ui.adding || free <= 0}
+ onclick={() => changeSeats(item.id, entry, 1)}
>
+
@@ -424,27 +546,25 @@
{:else}
addSlot(item.id, slot.id)}
- class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {line
+ disabled={!!entry.line || !entry.time || ui.adding}
+ onclick={() => entry.time && addTime(item, duration.minutes, entry.time)}
+ class="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-sm transition {entry.line
? 'cursor-not-allowed border-transparent bg-sage/15 text-sage-dark'
: 'border-charcoal/15 bg-white text-charcoal hover:border-sage hover:bg-sage/10'} disabled:opacity-60 {ui.adding &&
- !line
+ !entry.line
? 'cursor-wait'
: ''}"
>
- {#if ui.pendingSlotId === slot.id}
+ {#if pending}
{/if}
- {label}{isGroup ? ` · ${placesLeft(slot.free)}` : ''}{line ? ' · In basket' : ''}
+ {label}{isGroup ? ` · ${placesLeft(free)}` : ''}{entry.line ? ' · In basket' : ''}
{/if}
{/each}
{:else if anyShown}
-
- Days with availability are highlighted{item.duration != null ? ` · ${item.duration} min per session` : ''}.
-
+
Days with availability are highlighted.
{/if}
{#if ui.justAdded}
diff --git a/packages/shared/src/items.ts b/packages/shared/src/items.ts
new file mode 100644
index 0000000..2d1fd5c
--- /dev/null
+++ b/packages/shared/src/items.ts
@@ -0,0 +1,29 @@
+// Services and their durations — pure helpers shared by the admin editor,
+// the Shop block and the checkout. Which duration costs what is decided
+// (and charged) by the shop hooks in PocketBase; this only reads and shows it.
+
+import type { ItemDuration } from './types';
+
+/** A service's `durations` field (JSON, possibly hand-edited) → valid entries, shortest first, one per length. */
+export function parseDurations(raw: unknown): ItemDuration[] {
+ const list = Array.isArray(raw) ? raw : [];
+ const seen = new Set
();
+ return list
+ .map((d) => ({ minutes: Math.floor(Number(d?.minutes)), price: Number(d?.price) }))
+ .filter((d) => d.minutes > 0 && Number.isFinite(d.price) && d.price >= 0 && !seen.has(d.minutes) && seen.add(d.minutes))
+ .sort((a, b) => a.minutes - b.minutes);
+}
+
+/** `45` → "45 min", `60` → "1 hour", `120` → "2 hours", `90` → "1 h 30 min". */
+export function formatDuration(minutes: number) {
+ if (minutes < 60) return `${minutes} min`;
+ const hours = Math.floor(minutes / 60);
+ const rest = minutes % 60;
+ if (!rest) return `${hours} ${hours === 1 ? 'hour' : 'hours'}`;
+ return `${hours} h ${rest} min`;
+}
+
+/** The lowest price among a service's durations (what "from …" shows), or null without any. */
+export function lowestPrice(durations: ItemDuration[]) {
+ return durations.length ? Math.min(...durations.map((d) => d.price)) : null;
+}
diff --git a/packages/shared/src/server/email/index.ts b/packages/shared/src/server/email/index.ts
index 9b775e0..26c284e 100644
--- a/packages/shared/src/server/email/index.ts
+++ b/packages/shared/src/server/email/index.ts
@@ -148,14 +148,12 @@ function orderEmailContext(data: OrderEmailData, settings: EmailSettings) {
const lineRecords = [...data.lines].sort((a, b) => String(a.start || '').localeCompare(String(b.start || '')));
const lines: EmailLine[] = lineRecords.map((line) => {
+ // A booking ends after its own length (order lines from before
+ // lengths were stored fall back to their slot's end).
const start = line.start ? new Date(line.start).toISOString() : null;
+ const minutes = Number(line.minutes) || 0;
const slotEnd = line.expand?.slot?.end;
- const duration = Number(line.expand?.item?.duration) || 0;
- const end = slotEnd
- ? new Date(slotEnd).toISOString()
- : start && duration
- ? new Date(new Date(start).getTime() + duration * 60_000).toISOString()
- : null;
+ const end = start && minutes ? new Date(new Date(start).getTime() + minutes * 60_000).toISOString() : slotEnd ? new Date(slotEnd).toISOString() : null;
return {
name: String(line.name || 'Item'),
price: Number(line.price) || 0,
diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts
index 9d8257a..0fbfe2a 100644
--- a/packages/shared/src/server/shop.ts
+++ b/packages/shared/src/server/shop.ts
@@ -1,39 +1,63 @@
import type PocketBase from 'pocketbase';
import { getFileUrl } from '../pb';
-import type { ItemRecord, SlotRecord } from '../types';
+import { parseDurations } from '../items';
+import type { BookableTime, ItemRecord } from '../types';
+
+/** An `items` record (with `expand.image`) → `ItemRecord`. */
+export function mapItemRecord(record: Record): ItemRecord {
+ const media = record.expand?.image;
+ const type = record.type === 'item_with_time' ? 'item_with_time' : 'item';
+ return {
+ id: record.id,
+ name: String(record.name || ''),
+ description: String(record.description || ''),
+ price: Number(record.price) || 0,
+ image: String(record.image || ''),
+ imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
+ type,
+ stock: record.stock ?? null,
+ durations: type === 'item_with_time' ? parseDurations(record.durations) : [],
+ bufferMinutes: record.bufferMinutes ?? null,
+ capacity: record.capacity ?? null,
+ active: record.active !== false
+ };
+}
/**
- * Active items and bookable future slots, shaped for the Shop/Checkout
- * blocks. Used by the public layout and the admin draft preview so both
- * render the same shop.
- *
- * Works with an anonymous client: active items and media are public, and
- * slots come from the shop hook (GET /api/shop/slots), which leaves out
- * full slots and slots blocked by an overlapping booking. Errors propagate.
+ * Active items, shaped for the Shop/Checkout blocks. Used by the public
+ * layout and the admin draft preview so both render the same shop. Works
+ * with an anonymous client (active items and media are public). Bookable
+ * times are fetched by the Shop block itself, per service and duration
+ * (see `loadBookableTimes`). Errors propagate.
*/
-export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> {
- const [itemRecords, { slots }] = await Promise.all([
- pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }),
- pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null })
- ]);
-
- const items = itemRecords.map((record): ItemRecord => {
- const media = record.expand?.image;
- return {
- id: record.id,
- name: record.name,
- description: record.description || '',
- price: record.price,
- image: record.image || '',
- imageUrl: media ? getFileUrl('media', media.id, media.file) : '',
- type: record.type,
- stock: record.stock ?? null,
- duration: record.duration ?? null,
- bufferMinutes: record.bufferMinutes ?? null,
- capacity: record.capacity ?? null,
- active: record.active
- };
- });
-
- return { items, slots };
+export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[] }> {
+ const records = await pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' });
+ return { items: records.map(mapItemRecord) };
+}
+
+export type BookableTimesQuery = { item: string; minutes: string; from: string; to: string };
+
+/**
+ * Times a customer can book for one service and duration, from the shop
+ * hook (GET /api/shop/slots), which applies every availability rule. When
+ * none start in [from, to), `next` is the first one after (or null).
+ */
+export function loadBookableTimes(pb: PocketBase, query: BookableTimesQuery) {
+ return pb.send<{ times: BookableTime[]; next: string | null }>('/api/shop/slots', { query, requestKey: null });
+}
+
+/**
+ * GET /api/slots in both apps (the Shop block's time picker): forwards
+ * ?item=&minutes=&from=&to= to the shop hook. A PocketBase error keeps its
+ * status and message; PocketBase being down is a 503.
+ */
+export async function bookableTimesResponse(pb: PocketBase, url: URL): Promise {
+ const param = (key: string) => url.searchParams.get(key) ?? '';
+ try {
+ return Response.json(await loadBookableTimes(pb, { item: param('item'), minutes: param('minutes'), from: param('from'), to: param('to') }));
+ } catch (e) {
+ const status = Number((e as { status?: number })?.status) || 0;
+ const message = (e as { response?: { message?: string } })?.response?.message;
+ return Response.json({ message: message || 'Could not load the available times — please try again' }, { status: status >= 400 ? status : 503 });
+ }
}
diff --git a/packages/shared/src/slots.ts b/packages/shared/src/slots.ts
index 311ec0b..d02ba34 100644
--- a/packages/shared/src/slots.ts
+++ b/packages/shared/src/slots.ts
@@ -6,6 +6,7 @@
// zonedInputToIso, so a run across a DST change still starts at 09:00.
import { DISPLAY_LOCALE, toZonedDatetimeInput, zonedInputToIso } from './calendar';
+import type { SlotKind, StartTimesMode } from './types';
/** A stretch of the day in which appointments may start and end, e.g. 09:00–12:00. */
export type TimeWindow = { from: string; to: string };
@@ -43,20 +44,49 @@ export type BulkResult = {
};
/**
- * 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.
+ * A booked or held time, as the shop hook reports it to the admin: paid
+ * order lines (`booked`) and basket lines whose hold hasn't lapsed
+ * (`held`). The practitioner is busy until `readyAt` (end + get-ready time).
+ */
+export type SlotBooking = PlannedSlot & {
+ slot: string;
+ item: string;
+ itemName: string;
+ readyAt: string;
+ quantity: number;
+ status: 'booked' | 'held';
+};
+
+/**
+ * A slot with what's booked in it (GET /api/shop/slots?detail=1). A window
+ * counts its bookings in `booked`/`held` and lists its `free` stretches; a
+ * group session has places and may be blocked by an overlapping booking.
*/
export type SlotDetail = PlannedSlot & {
id: string;
- item: string;
- itemName: string;
- capacity: number;
+ kind: SlotKind;
+ items: string[];
+ itemNames: string[];
notes: string;
booked: number;
held: number;
- blockedBy: string;
+ // window
+ startTimes?: StartTimesMode;
+ free?: PlannedSlot[];
+ // session
+ minutes?: number;
+ capacity?: number;
+ blockedBy?: SlotBooking | null;
+};
+
+export const START_TIMES_LABELS: Record = {
+ grid: 'Every 30 min',
+ edges: 'Next free time'
+};
+
+export const START_TIMES_HINTS: Record = {
+ 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.'
};
export type SlotState = 'free' | 'held' | 'booked' | 'full' | 'blocked';
@@ -70,12 +100,18 @@ export const SLOT_STATE_LABELS: Record = {
};
/**
- * `full` only when paid bookings fill a group; a slot whose last places are
- * in baskets reads `held`, since it frees up again if those holds lapse.
+ * A window is `full` once no free time is left. A session is `full` only
+ * when paid bookings fill a group; one whose last places are in baskets
+ * reads `held`, since it frees up again if those holds lapse.
*/
-export function slotState(slot: Pick): SlotState {
- if (slot.booked >= slot.capacity) return slot.capacity > 1 ? 'full' : 'booked';
- if (slot.held && slot.booked + slot.held >= slot.capacity) return 'held';
+export function slotState(slot: Pick): SlotState {
+ if (slot.kind === 'window') {
+ if ((slot.booked || slot.held) && !slot.free?.length) return slot.booked ? 'full' : 'held';
+ return slot.booked ? 'booked' : slot.held ? 'held' : 'free';
+ }
+ const capacity = slot.capacity ?? 1;
+ if (slot.booked >= capacity) return capacity > 1 ? 'full' : 'booked';
+ if (slot.held && slot.booked + slot.held >= capacity) return 'held';
if (slot.booked) return 'booked';
if (slot.held) return 'held';
return slot.blockedBy ? 'blocked' : 'free';
@@ -191,7 +227,22 @@ export type GeneratePlanInput = {
timeZone: string;
};
-/** Every slot the generator would create, before skipping overlaps/past ones. */
+/** Each chosen day's opening hours as windows (dates in `timeZone`), before skipping overlaps/past ones. */
+export function planWindows(input: Omit): PlannedSlot[] {
+ const days = new Set(input.weekdays);
+ const slots: PlannedSlot[] = [];
+ for (const key of dateKeysBetween(input.fromDate, input.toDate)) {
+ if (!days.has(weekdayOfKey(key))) continue;
+ for (const window of input.windows) {
+ const start = zonedInputToIso(`${key}T${window.from}`, input.timeZone);
+ const end = zonedInputToIso(`${key}T${window.to}`, input.timeZone);
+ if (start && end && end > start) slots.push({ start, end });
+ }
+ }
+ return slots;
+}
+
+/** Every group session the generator would create, before skipping overlaps/past ones. */
export function planGeneratedSlots(input: GeneratePlanInput): PlannedSlot[] {
const times = startTimesInWindows(input.windows, input.durationMinutes, input.bufferMinutes);
const days = new Set(input.weekdays);
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 09e61c3..aa0a888 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -119,31 +119,42 @@ export const defaultPrivacy: PrivacyGlobal = {
export type ItemType = 'item' | 'item_with_time';
+/** One length a service can be booked for, and its price. */
+export type ItemDuration = { minutes: number; price: number };
+
export type ItemRecord = {
id: string;
name: string;
description: string;
+ /** A product's price; for a service, its lowest duration price (kept in sync by the admin). */
price: number;
image: string; // media record id
imageUrl: string; // resolved URL (populated by server load)
type: ItemType;
stock: number | null;
- duration: number | null; // minutes, for item_with_time
- bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots
- capacity: number | null; // places per slot (default for new slots; >1 = group session)
+ durations: ItemDuration[]; // item_with_time: the lengths it can be booked for, shortest first
+ bufferMinutes: number | null; // get-ready time after each appointment
+ capacity: number | null; // places in a new group session (>1 = group)
active: boolean;
};
+/** `window`: a stretch of time in which its services can be booked; `session`: one service at a fixed time with places. */
+export type SlotKind = 'window' | 'session';
+
+/** Where bookings may start in a window: every 30 minutes, or only at the start/end of the free time. */
+export type StartTimesMode = 'grid' | 'edges';
+
/**
- * A bookable slot as the shop lists it (GET /api/shop/slots): only slots
- * with places left that no overlapping booking blocks.
+ * A time a customer can book, as the shop lists it (GET /api/shop/slots for
+ * one service and duration): a start time in a window, or a group session
+ * with places left.
*/
-export type SlotRecord = {
- id: string;
- item: string; // item id
+export type BookableTime = {
+ slot: string; // slot id (window or session)
+ kind: SlotKind;
start: string;
end: string;
- capacity: number; // places in total
+ capacity: number; // places in total (1 in a window)
free: number; // places still bookable
};
@@ -156,12 +167,16 @@ export type BasketLine = {
slot: string | null;
quantity: number;
lineType: 'item' | 'slot';
+ /** Slot lines: the booked time and length. */
+ start?: string;
+ end?: string;
+ minutes?: number;
// Expanded fields (populated server-side)
itemName?: string;
- itemPrice?: number;
+ /** Price of one unit (a product, or the service at this length); null if no longer offered. */
+ itemPrice?: number | null;
itemImageUrl?: string;
- slotStart?: string;
- slotEnd?: string;
+ slotKind?: SlotKind;
slotCapacity?: number;
/** Slot lines: when the reservation lapses and the line is dropped (ISO). */
heldUntil?: string;
@@ -211,6 +226,8 @@ export type OrderLine = {
name: string;
price: number;
start: string | null;
+ /** Slot lines: the booked length. */
+ minutes: number | null;
};
// ── Block data types ──────────────────────────────────────────────────