diff --git a/AGENTS.md b/AGENTS.md
index f5ada8f..5e7446d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -130,7 +130,6 @@ To add an email block type: add to `EmailBlockType` in `packages/shared/src/type
- **Always build filters with `pb.filter('slug = {:slug}', { slug })`** — never interpolate values into filter strings (quotes break them).
- **Schema changes**: add a migration to `pocketbase/pb_migrations/` (runs once, on the next PocketBase start) **and** mirror it in `pb_schema.json` (fresh installs import that after the migrations have already run). Migrations must skip missing collections and must not throw for data problems — a failing migration stops PocketBase from starting.
- **API rules**: CMS collections require `@request.auth.id != ''`, so `users` must never allow public sign-up (its createRule is superuser-only). Commerce writes (orders, order_lines, baskets, basket_lines) are superuser-only; they happen in the PocketBase shop hooks (`pocketbase/pb_hooks/shop/lib.js`), which bypass rules.
-- **Slot availability** (places + blocking by overlapping bookings, incl. get-ready time) is computed only by `slotStates()` in the shop hooks — the public listing, basket holds and the admin `/slots` page all go through it (`GET /api/shop/slots`, `?detail=1` for the admin). Never store booking state on a slot or re-implement the rule elsewhere; see the README's *Slot availability*.
- **Shop / payments**: all basket, slot-hold, Stripe and order logic lives in the PocketBase hooks (JSVM: synchronous, each handler `require()`s the lib; see the header comment). The public app must stay unprivileged — no superuser login, no Stripe secret key; its routes only proxy to `/api/shop/*` and manage the `basket_id` cookie (`app-public/src/lib/server/shop.ts`). Booking emails are rendered and sent by the public app from data the webhook hook returns (`OrderEmailData`, `sendOrderEmailsFromData`); keep `orderEmailData()` in the hook and `loadOrderEmailData()` in `packages/shared/src/server/email` returning the same shape. Local testing uses `stripe-mock` (`STRIPE_API_BASE`, local compose only).
### Styling
@@ -184,4 +183,4 @@ cd app-public && npm run build
- `SITE_TIMEZONE` — IANA timezone for booking times in emails (default `Europe/Oslo`).
- Secrets (Stripe, `INTERNAL_API_SECRET`, SMTP) are read from a root-level `.env` next to `docker-compose.yml`; see `.env.example`.
- `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` → PocketBase only. `INTERNAL_API_SECRET` → PocketBase and app-public (booking-email status). No app gets PocketBase superuser credentials.
-- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`; slots via `GET /api/shop/slots`); if a Shop block has nothing to show it says "Nothing is available".
+- Shop listings are public data, loaded anonymously by `loadShopData()` in `packages/shared/src/server/shop.ts` (public layout and admin `/preview`); if a Shop block has nothing to show it says "Nothing is available".
diff --git a/README.md b/README.md
index 15f1d2f..1d1a468 100644
--- a/README.md
+++ b/README.md
@@ -112,10 +112,10 @@ 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), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `capacity` number (nullable = 1, default places for new slots), `active` bool
-- `slots` — `item` relation→items, `start` date, `end` date, `capacity` number (places; >1 = group session), `notes` text. Nothing about bookings is stored here — see *Slot availability* below
+- `items` — `name` text, `description` text, `price` number, `image` relation→media, `type` select `item|item_with_time`, `stock` number (nullable), `duration` number (nullable, minutes), `bufferMinutes` number (nullable, get-ready minutes after each appointment), `active` bool
+- `slots` — `item` relation→items, `start` date, `end` date, `status` select `available|held|booked`, `heldUntil` date (nullable), `order` relation→orders (nullable), `notes` text
- `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`, `heldUntil` date (a slot line's hold)
+- `basket_lines` — `basket` relation→baskets, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`
- `orders` — `basket` relation→baskets, `email` text, `customerDetails` json, `total` number, `status` select `pending|paid|refunded`, `stripePaymentIntentId` text, `customerEmailSentAt` date, `clientEmailSentAt` date, `emailError` text
- `order_lines` — `order` relation→orders, `item` relation→items, `slot` relation→slots (nullable), `quantity` number, `lineType` select `item|slot`, `name` text (snapshot), `price` number (snapshot), `start` date (nullable, snapshot)
- `email_templates` — `key` text (unique: `customer_confirmation` | `client_alert`), `subject` text, `blocks` json, `recipients` text, `enabled` bool
@@ -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` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (slots with no places taken). Bulk tools preview first and skip slots in the past or overlapping a slot of the same service. Different services may share a time; whichever is booked first blocks the others (see *Slot availability*). The calendar marks slots available / in a basket / booked / full / blocked, with places taken for group sessions.
+- `/slots` — bookable time slots: month calendar, single slots, and bulk tools — *Generate slots* (date range × weekdays × opening hours, spaced by the service's duration + get-ready time), *Copy a week* (repeat into the next 1–12 weeks) and *Clear slots* (free slots only). Bulk tools preview first, skip slots in the past or overlapping a slot of the same service, and never touch booked or in-basket slots. Different services may overlap — there is no cross-service collision check.
- `/orders` — confirmed bookings and purchases, with booking-email status and resend buttons
- `/emails` — block-based editor for the booking confirmation and new-booking alert emails (live preview, test send)
- `/globals` — header/footer/colors editor
@@ -147,14 +147,7 @@ All routes in `app-admin` except `/login` are guarded in `src/hooks.server.ts`.
The shop/checkout blocks implement a basket-based booking flow: visitors add services (with time slots) or products to a server-side basket, then pay with an embedded Stripe Payment Element. Order creation is confirmed by the Stripe **webhook** (never the client).
-**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that tidies expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
-
-**Slot availability** (`slotStates()` in `pocketbase/pb_hooks/shop/lib.js` — the one place these rules live):
-
-- A slot has `capacity` places. Places are taken by paid order lines and by basket lines whose `heldUntil` hasn't passed (10 min after adding, 30 min once payment starts). A lapsed hold stops counting immediately; the cron only deletes the line.
-- One practitioner works every service, so a slot with **any** place taken blocks every other slot that overlaps it — whatever the service — counting each service's get-ready time (`items.bufferMinutes`) after it. The client can offer three massages at 10:00; once one is in a basket or booked, the other two disappear. A group session with one place booked blocks massages at that time too, while staying bookable itself until full.
-- `GET /api/shop/slots` lists the bookable future slots (public; feeds the Shop block). With `?detail=1` a signed-in admin gets every slot in a range with booked/held places and what blocks it (the `/slots` page).
-- Adding to a basket (`add_slot`, with `seats`) and changing a group line's places re-check capacity and blocking inside one transaction; PocketBase runs transactions one at a time, so concurrent customers can't both get the last place or two overlapping times.
+**Where the logic lives:** all commerce writes (baskets, slot holds, Stripe PaymentIntents, the webhook that creates orders) run *inside PocketBase* as JS hooks — `pocketbase/pb_hooks/shop/lib.js`, routes under `/api/shop/*`, plus a once-a-minute cron that releases expired holds. The public app holds **no PocketBase or Stripe secret**: its `/api/basket`, `/api/checkout/create-intent`, `/api/webhooks/stripe` and `/checkout/return` only forward to those routes and keep the basket cookie. A compromised public app therefore can't read or change the database beyond what any visitor can. Its one privileged call records booking-email status on an order, authorised by `INTERNAL_API_SECRET`.
Setup:
@@ -165,7 +158,7 @@ Setup:
stripe listen --forward-to www.localhost:8080/api/webhooks/stripe
```
Copy the printed `whsec_…` signing secret into `STRIPE_WEBHOOK_SECRET`.
-4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). Two visitors can't take the same place: holds are checked and written in one PocketBase transaction (see *Slot availability*).
+4. Import the updated `pb_schema.json` (adds `items`, `slots`, `baskets`, `basket_lines`, `orders`, `order_lines`). The `basket_lines.slot` partial unique index guarantees two visitors can't hold the same slot.
5. Create a published page (e.g. slug `book`) with a `shop` block and a `checkout` block, and point the header CTA at it.
## Booking emails (Brevo)
diff --git a/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte b/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
index fe78858..40c6c73 100644
--- a/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
+++ b/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte
@@ -6,7 +6,7 @@
import BulkActions from './BulkActions.svelte';
import { bulkForm } from './bulkForm.svelte';
- type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number };
+ type Service = { id: string; name: string; duration: number; bufferMinutes: number };
let {
open = $bindable(false),
@@ -23,7 +23,6 @@
weekdays: [1, 2, 3, 4, 5],
windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[],
bufferMinutes: '',
- capacity: '',
notes: ''
});
@@ -51,10 +50,8 @@
function selectService(id: string) {
draft.item = id;
- // The service's own get-ready time and places are the defaults; both can be overridden here.
- const item = items.find((item) => item.id === id);
- draft.bufferMinutes = String(item?.bufferMinutes ?? 0);
- draft.capacity = String(item?.capacity ?? 1);
+ // The service's own get-ready time is the default; it can be overridden here.
+ draft.bufferMinutes = String(items.find((item) => item.id === id)?.bufferMinutes ?? 0);
}
function addWindow() {
@@ -112,18 +109,11 @@
-
-
-
-
+
{#if service}
diff --git a/app-admin/src/lib/server/slots.ts b/app-admin/src/lib/server/slots.ts
index f3afb64..cfe9938 100644
--- a/app-admin/src/lib/server/slots.ts
+++ b/app-admin/src/lib/server/slots.ts
@@ -1,34 +1,56 @@
-// Server helpers for the /slots page. Planning is pure and lives in
-// $shared/slots; this file does the PocketBase reads/writes around it.
+// Server helpers for the /slots bulk actions (generate, copy week, clear).
+// Planning is pure and lives in $shared/slots; this file does the PocketBase
+// reads/writes around it.
-import type { SlotDetail } from '$lib/slots';
+import { instantMs, type PlannedSlot } from '$lib/slots';
import type { createPocketBase } from '$lib/pb';
type Pb = ReturnType;
+export type ExistingSlot = PlannedSlot & {
+ id: string;
+ item: string;
+ status: string;
+ heldUntil: string;
+ notes: string;
+};
+
/** How many PocketBase writes a bulk action runs at once. */
const WRITE_CONCURRENCY = 5;
+/** Held by a basket whose hold hasn't expired yet (expired holds are released lazily). */
+export function isHoldActive(slot: Record | null) {
+ if (slot?.status !== 'held') return false;
+ const until = instantMs(String(slot.heldUntil || ''));
+ return Number.isNaN(until) || until > Date.now();
+}
+
/**
- * Slots with their places and blocking, from the shop hook — the same
- * availability rules the public shop uses (pocketbase/pb_hooks/shop/lib.js).
- * Either slots starting in `[from, to)` (optionally one service) or one slot by id.
+ * Slots starting in `[fromIso, toIso)`, optionally for one service. A slot
+ * without an end gets one from its service's duration, so overlap checks
+ * always have a real range.
*/
-export async function loadSlotDetails(pb: Pb, query: { from: string; to: string; item?: string } | { id: string }) {
- const { slots } = await pb.send<{ slots: SlotDetail[] }>('/api/shop/slots', {
- query: { detail: 1, ...query },
- requestKey: null
+export async function loadSlotsBetween(pb: Pb, fromIso: string, toIso: string, itemId = ''): Promise {
+ const filter = itemId
+ ? pb.filter('start >= {:from} && start < {:to} && item = {:item}', { from: new Date(fromIso), to: new Date(toIso), item: itemId })
+ : pb.filter('start >= {:from} && start < {:to}', { from: new Date(fromIso), to: new Date(toIso) });
+ const records = await pb.collection('slots').getFullList({ filter, sort: 'start', expand: 'item' });
+ return records.map((record) => {
+ const start = String(record.start || '');
+ const duration = Number(record.expand?.item?.duration) || 0;
+ const end = record.end ? String(record.end) : new Date(instantMs(start) + duration * 60_000).toISOString();
+ return {
+ id: record.id,
+ item: String(record.item || ''),
+ start,
+ end,
+ status: String(record.status || 'available'),
+ heldUntil: record.heldUntil ? String(record.heldUntil) : '',
+ notes: String(record.notes || '')
+ };
});
- return slots;
}
-/** One slot's details, or null if it doesn't exist (any other failure throws). */
-export async function loadSlotDetail(pb: Pb, id: string) {
- return (await loadSlotDetails(pb, { id }))[0] ?? null;
-}
-
-export const seatsTaken = (slot: Pick) => slot.booked + slot.held;
-
/** Run `fn` over `values` a few at a time; returns how many succeeded. */
export async function runInBatches(values: T[], label: string, fn: (value: T) => Promise) {
let succeeded = 0;
diff --git a/app-admin/src/routes/items/+page.server.ts b/app-admin/src/routes/items/+page.server.ts
index 8b8a2ca..090672b 100644
--- a/app-admin/src/routes/items/+page.server.ts
+++ b/app-admin/src/routes/items/+page.server.ts
@@ -9,11 +9,9 @@ function itemPayload(data: FormData) {
const rawStock = String(data.get('stock') ?? '').trim();
const rawDuration = String(data.get('duration') ?? '').trim();
const rawBuffer = String(data.get('bufferMinutes') ?? '').trim();
- const rawCapacity = String(data.get('capacity') ?? '').trim();
const stock = type === 'item' && rawStock !== '' ? parseInt(rawStock, 10) : null;
const duration = type === 'item_with_time' && rawDuration !== '' ? parseInt(rawDuration, 10) : null;
const bufferMinutes = type === 'item_with_time' && rawBuffer !== '' ? parseInt(rawBuffer, 10) : null;
- const capacity = type === 'item_with_time' && rawCapacity !== '' ? parseInt(rawCapacity, 10) : null;
return {
name: String(data.get('name') || '').trim(),
@@ -24,7 +22,6 @@ function itemPayload(data: FormData) {
stock: Number.isNaN(stock) ? null : stock,
duration: Number.isNaN(duration) ? null : duration,
bufferMinutes: Number.isNaN(bufferMinutes) ? null : bufferMinutes,
- capacity: Number.isNaN(capacity) ? null : capacity,
active: String(data.get('active')) === 'true'
};
}
@@ -42,7 +39,6 @@ function normalizeItem(record: Record): ItemRecord {
stock: record.stock ?? null,
duration: record.duration ?? null,
bufferMinutes: record.bufferMinutes ?? null,
- capacity: record.capacity ?? null,
active: record.active !== false
};
}
diff --git a/app-admin/src/routes/items/+page.svelte b/app-admin/src/routes/items/+page.svelte
index 3524857..fefdd41 100644
--- a/app-admin/src/routes/items/+page.svelte
+++ b/app-admin/src/routes/items/+page.svelte
@@ -22,7 +22,6 @@
stock: string;
duration: string;
bufferMinutes: string;
- capacity: string;
active: boolean;
};
@@ -32,7 +31,7 @@
let money = $derived(new Intl.NumberFormat('en-GB', { style: 'currency', currency: data.currency }));
function emptyDraft(): ItemDraft {
- return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true };
+ return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', active: true };
}
function createItem() {
@@ -53,7 +52,6 @@
stock: item.stock == null ? '' : String(item.stock),
duration: item.duration == null ? '' : String(item.duration),
bufferMinutes: item.bufferMinutes == null ? '' : String(item.bufferMinutes),
- capacity: item.capacity == null ? '' : String(item.capacity),
active: item.active
};
uploadError = '';
@@ -111,7 +109,7 @@
@@ -168,12 +166,7 @@
-
{/if}
diff --git a/app-admin/src/routes/slots/+page.server.ts b/app-admin/src/routes/slots/+page.server.ts
index ab5508a..070f00a 100644
--- a/app-admin/src/routes/slots/+page.server.ts
+++ b/app-admin/src/routes/slots/+page.server.ts
@@ -3,7 +3,7 @@ import { fail } from '@sveltejs/kit';
import { toZonedDatetimeInput, zonedInputToIso } from '$lib/calendar';
import type { createPocketBase } from '$lib/pb';
import { attempt } from '$lib/server/actions';
-import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots';
+import { isHoldActive, loadSlotsBetween, runInBatches, type ExistingSlot } from '$lib/server/slots';
import {
MAX_BULK_SLOTS,
addDaysToKey,
@@ -18,20 +18,17 @@ import {
timeToMinutes,
type BulkResult,
type PlannedSlot,
- type SlotDetail,
type TimeWindow
} from '$lib/slots';
+import type { SlotStatus } from '$lib/types';
import type { Actions, PageServerLoad } from './$types';
type Pb = ReturnType;
type SlotPayload =
- | { payload: { item: string; start: string; end: string; capacity: number; notes: string } }
+ | { payload: { item: string; start: string; end: string; notes: string } }
| { error: string };
-/** A slot to create: planned times plus what it copies (service, places, notes). */
-type Candidate = PlannedSlot & { item: string; capacity: number; notes: string };
-
const siteTimezone = () => env.SITE_TIMEZONE || 'Europe/Oslo';
const todayKey = () => toZonedDatetimeInput(new Date().toISOString(), siteTimezone()).slice(0, 10);
/** Midnight at the start of `key` in the site timezone, as an ISO instant. */
@@ -39,19 +36,6 @@ const dayStartIso = (key: string) => zonedInputToIso(`${key}T00:00`, siteTimezon
const MAX_RANGE_DAYS = 366;
const MAX_COPY_WEEKS = 12;
-const MAX_CAPACITY = 500;
-
-/**
- * Places from the form: a whole number 1–500, or the service's own
- * capacity (default 1) when the field is left empty.
- */
-function parseCapacity(data: FormData, item: Record): number | { error: string } {
- const raw = String(data.get('capacity') ?? '').trim();
- if (raw === '') return Math.max(1, Number(item.capacity) || 1);
- const capacity = Number(raw);
- if (!Number.isInteger(capacity) || capacity < 1 || capacity > MAX_CAPACITY) return { error: `Places must be a whole number from 1 to ${MAX_CAPACITY}.` };
- return capacity;
-}
async function slotPayload(data: FormData, pb: Pb): Promise {
const itemId = String(data.get('item') || '').trim();
@@ -73,15 +57,12 @@ async function slotPayload(data: FormData, pb: Pb): Promise {
}
if (item.type !== 'item_with_time') return { error: 'Selected service must be a bookable service.' };
- const capacity = parseCapacity(data, item);
- if (typeof capacity !== 'number') return capacity;
-
const duration = Number(item.duration) || 0;
const end = new Date(start.getTime() + duration * 60_000);
- // 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 } };
+ // Status is never taken from the form: it is owned by the booking flow
+ // (held by a basket, booked by a paid order). New slots start available.
+ return { payload: { item: itemId, start: start.toISOString(), end: end.toISOString(), notes } };
}
/** Validated `from`/`to` date keys from a bulk form, or an error message. */
@@ -94,14 +75,6 @@ function dateRange(data: FormData): { fromDate: string; toDate: string } | { err
return { fromDate, toDate };
}
-/** Slot details for the days `fromKey`–`toKey` (inclusive), or null if PocketBase can't be read. */
-function slotsForDays(pb: Pb, fromKey: string, toKey: string, item = '') {
- return loadSlotDetails(pb, { from: dayStartIso(fromKey), to: dayStartIso(addDaysToKey(toKey, 1)), item }).catch((e) => {
- console.error('[slots] could not load slot details', e);
- return null;
- });
-}
-
async function bookableService(pb: Pb, itemId: string) {
if (!itemId) return null;
const item = await pb.collection('items').getOne(itemId).catch(() => null);
@@ -111,14 +84,14 @@ async function bookableService(pb: Pb, itemId: string) {
/**
* 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.
+ * may overlap freely — there is no cross-service collision detection.
*/
-function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) {
+function filterCandidates(candidates: (PlannedSlot & { item: string })[], existing: ExistingSlot[]) {
const now = Date.now();
const taken = new Map();
for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]);
- const accepted: Candidate[] = [];
+ const accepted: typeof candidates = [];
let skippedPast = 0;
let skippedOverlap = 0;
for (const candidate of candidates) {
@@ -144,7 +117,13 @@ function bulkResult(fields: Partial & Pick) {
+async function previewOrCreate(
+ pb: Pb,
+ action: 'generate' | 'copy',
+ intent: string,
+ result: ReturnType,
+ notesFor: (slot: PlannedSlot & { item: string }) => string
+) {
const { accepted, skippedPast, skippedOverlap } = result;
if (accepted.length > MAX_BULK_SLOTS) {
return fail(400, { message: `That would create ${accepted.length} slots — at most ${MAX_BULK_SLOTS} at once. Choose a shorter range.` });
@@ -159,7 +138,7 @@ 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 })
+ pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, notes: notesFor(slot), status: 'available' })
);
return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created });
}
@@ -177,15 +156,36 @@ export const load: PageServerLoad = async ({ locals, url }) => {
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)
+ bufferMinutes: Number(record.bufferMinutes) || 0
}));
// 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 slotRecords = await locals.pb
+ .collection('slots')
+ .getFullList({
+ filter: locals.pb.filter('start >= {:from} && start < {:to}', {
+ from: new Date(dayStartIso(grid[0])),
+ to: new Date(dayStartIso(addDaysToKey(grid[grid.length - 1], 1)))
+ }),
+ sort: 'start',
+ expand: 'item'
+ })
+ .catch(() => []);
+ const slots = slotRecords.map((record) => ({
+ id: record.id,
+ item: String(record.item || ''),
+ itemName: String(record.expand?.item?.name || 'Unknown service'),
+ itemDuration: record.expand?.item?.duration ?? null,
+ start: String(record.start || ''),
+ end: record.end ? String(record.end) : '',
+ status: String(record.status || 'available') as SlotStatus,
+ heldUntil: record.heldUntil ? String(record.heldUntil) : '',
+ order: record.order ? String(record.order) : '',
+ notes: String(record.notes || '')
+ }));
- return { items, slots: slots ?? [], slotsError: slots === null, month, today };
+ return { items, slots, month, today };
};
export const actions: Actions = {
@@ -193,7 +193,9 @@ export const actions: Actions = {
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 created = await attempt('Could not create the slot.', () =>
+ locals.pb.collection('slots').create({ ...result.payload, status: 'available' })
+ );
if (!created.ok) return created.failure;
return { ok: true };
},
@@ -202,20 +204,15 @@ export const actions: Actions = {
const id = String(data.get('id') || '');
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.
- 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?' });
+ // Re-read the slot: the page may be stale, and a customer may have
+ // held or booked it since. Only notes can change while it's held.
+ const current = await locals.pb.collection('slots').getOne(id).catch(() => null);
if (!current) return fail(404, { message: 'This slot no longer exists.' });
+ if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' });
- const taken = seatsTaken(current);
- let patch: Record;
- if (taken > 0) {
- const capacity = parseCapacity(data, { capacity: current.capacity });
- if (typeof capacity !== 'number') return fail(400, { message: capacity.error });
- if (capacity < taken) return fail(400, { message: `${taken} place${taken === 1 ? ' is' : 's are'} already taken — places can’t go below that.` });
- patch = { capacity, notes: String(data.get('notes') || '').trim() };
+ let patch: Record;
+ if (isHoldActive(current)) {
+ patch = { notes: String(data.get('notes') || '').trim() };
} else {
const result = await slotPayload(data, locals.pb);
if ('error' in result) return fail(400, { message: result.error });
@@ -229,10 +226,9 @@ export const actions: Actions = {
const data = await request.formData();
const id = String(data.get('id') || '');
if (!id) return fail(400, { message: 'Slot id is required.' });
- 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.' });
+ const record = await locals.pb.collection('slots').getOne(id).catch(() => null);
+ if (record && record.status === 'booked') return fail(400, { message: 'Booked slots cannot be deleted.' });
+ if (isHoldActive(record)) return fail(400, { message: 'This slot is in a customer’s basket right now — try again in a few minutes.' });
const deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id));
if (!deleted.ok) return deleted.failure;
return { ok: true };
@@ -249,8 +245,6 @@ export const actions: Actions = {
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.' });
@@ -273,12 +267,17 @@ export const actions: Actions = {
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);
+ const existing = await loadSlotsBetween(
+ locals.pb,
+ dayStartIso(range.fromDate),
+ dayStartIso(addDaysToKey(range.toDate, 1)),
+ item.id
+ ).catch(() => null);
if (!existing) return fail(400, { message: 'Could not check existing slots — is the database reachable?' });
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);
+ const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id })), existing);
+ return previewOrCreate(locals.pb, 'generate', intent, result, () => notes);
},
/** Repeat one week's slots (all services, or one) for the following weeks. */
@@ -291,26 +290,33 @@ export const actions: Actions = {
if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` });
const itemId = String(data.get('item') || '');
- const 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 source = await loadSlotsBetween(locals.pb, dayStartIso(sourceWeek), dayStartIso(addDaysToKey(sourceWeek, 7)), itemId).catch(() => null);
+ const existing = await loadSlotsBetween(
+ locals.pb,
+ dayStartIso(addDaysToKey(sourceWeek, 7)),
+ dayStartIso(addDaysToKey(sourceWeek, 7 * (weeks + 1))),
+ itemId
+ ).catch(() => null);
if (!source || !existing) return fail(400, { message: 'Could not read slots — is the database reachable?' });
if (!source.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[] = [];
+ const notesByStart = new Map();
+ const candidates: (PlannedSlot & { item: string })[] = [];
for (let week = 1; week <= weeks; week++) {
for (const slot of source) {
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 });
+ candidates.push({ item: slot.item, start, end });
+ notesByStart.set(`${slot.item}|${start}`, slot.notes);
}
}
- return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing));
+ const result = filterCandidates(candidates, existing);
+ return previewOrCreate(locals.pb, 'copy', intent, result, (slot) => notesByStart.get(`${slot.item}|${slot.start}`) ?? '');
},
- /** Delete the slots in a date range that have no places taken. */
+ /** Delete the free slots in a date range. Booked and currently-held slots stay. */
clear: async ({ request, locals }) => {
const data = await request.formData();
const intent = String(data.get('intent') || 'preview');
@@ -318,10 +324,10 @@ 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);
+ const slots = await loadSlotsBetween(locals.pb, dayStartIso(range.fromDate), dayStartIso(addDaysToKey(range.toDate, 1)), itemId).catch(() => null);
if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' });
- const removable = slots.filter((slot) => seatsTaken(slot) === 0);
+ const removable = slots.filter((slot) => slot.status !== 'booked' && !isHoldActive(slot));
const summary = {
action: 'clear' as const,
kept: slots.length - removable.length,
@@ -333,8 +339,8 @@ export const actions: Actions = {
// Re-check each slot just before deleting it: a customer may have put
// it in 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');
+ const fresh = await locals.pb.collection('slots').getOne(slot.id);
+ if (fresh.status === 'booked' || isHoldActive(fresh)) throw new Error('taken since the preview');
await locals.pb.collection('slots').delete(slot.id);
});
return bulkResult({ ...summary, intent: 'done', count: deleted, failed: removable.length - deleted });
diff --git a/app-admin/src/routes/slots/+page.svelte b/app-admin/src/routes/slots/+page.svelte
index 20d97cc..65aafdf 100644
--- a/app-admin/src/routes/slots/+page.svelte
+++ b/app-admin/src/routes/slots/+page.svelte
@@ -7,15 +7,14 @@
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 type { BulkResult, SlotState } from '$lib/slots';
+ import { WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys } from '$lib/slots';
+ import type { BulkResult } from '$lib/slots';
let { data, form } = $props();
let items = $derived(data.items || []);
let serviceFilter = $state('');
let slots = $derived((data.slots || []).filter((slot) => !serviceFilter || slot.item === serviceFilter));
type Slot = (typeof slots)[number];
- let slotsById = $derived(new Map((data.slots || []).map((slot) => [slot.id, slot])));
// ── Month grid (date keys in the site timezone) ──
const MAX_CHIPS = 4;
@@ -48,34 +47,14 @@
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 or taken in the meantime)' : 'saved'}.` : '';
return `${verb} ${n(result.count)}.${failed}`;
}
- const STATE_CLASSES: Record = {
- free: 'border-success/40 bg-success/10',
- held: 'border-warning/50 bg-warning/20',
- booked: 'border-info/40 bg-info/15',
- full: 'border-info/60 bg-info/30',
- blocked: 'border-base-300 bg-base-100 text-base-content/40 line-through'
- };
- const BADGE_CLASSES: Record = {
- free: 'badge-success',
- held: 'badge-warning',
- booked: 'badge-info badge-soft',
- full: 'badge-info',
- blocked: 'badge-ghost'
- };
-
- /** "2/8" for group slots, '' for one-to-one. */
- function places(slot: Slot) {
- return slot.capacity > 1 ? `${slot.booked + slot.held}/${slot.capacity}` : '';
- }
-
- /** Why a slot is blocked, e.g. "Blocked by 10:00 Swedish massage". */
- function blockedReason(slot: Slot) {
- const blocker = slotsById.get(slot.blockedBy);
- return blocker ? `Blocked by ${formatTime(blocker.start, data.timezone)} ${blocker.itemName}` : 'Blocked by an overlapping booking';
+ function statusClass(status: string) {
+ if (status === 'booked') return 'border-info/40 bg-info/15';
+ if (status === 'held') return 'border-warning/50 bg-warning/20';
+ return 'border-success/40 bg-success/10';
}
function openDay(key: string) {
@@ -100,17 +79,15 @@
id: string;
item: string;
start: string;
- capacity: string;
- booked: number;
- held: number;
+ status: string;
+ heldUntil: string;
notes: string;
};
let draft = $state(emptyDraft());
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);
+ let isHeld = $derived(draft.status === 'held');
let selectedItem = $derived(items.find((item) => item.id === draft.item));
let endLabel = $derived.by(() => {
if (!selectedItem || !draft.start) return '';
@@ -122,7 +99,7 @@
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: '' };
+ return { id: '', item: serviceFilter, start, status: 'available', heldUntil: '', notes: '' };
}
// Enhanced so the page keeps its ?month= after saving (a plain POST to
@@ -152,9 +129,8 @@
id: slot.id,
item: slot.item,
start: toZonedDatetimeInput(slot.start, data.timezone),
- capacity: String(slot.capacity),
- booked: slot.booked,
- held: slot.held,
+ status: slot.status,
+ heldUntil: slot.heldUntil,
notes: slot.notes
};
showDay = false;
@@ -181,7 +157,6 @@
{#if form?.message}
{form.message}
{/if}
{#if bulkDone}
{bulkMessage(bulkDone)}
{/if}
{#if !items.length}
Add a bookable service under Services & products first.
{/if}
- {#if data.slotsError}
Could not load this month’s slots — is the database reachable?
{/if}
@@ -214,16 +189,9 @@
>
{#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)}
- {@const state = slotState(slot)}
-
- {#each Object.entries(SLOT_STATE_LABELS) as [state, label] (state)}
- {label}
- {/each}
- — a booking (or basket) at one time blocks every other service overlapping it, including get-ready time.
+ Available
+ In a basket
+ Booked
@@ -247,19 +214,23 @@
All slots in {monthLabel} ({monthSlots.length})
-
Service
Date
Places
Status
+
Service
Date
Duration
Status
{#each monthSlots as slot (slot.id)}
- {@const state = slotState(slot)}
- {[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.
+ This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed.