From d7765fe605d603b730781e98e610531bc96a33c7 Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 08:26:37 +0000 Subject: [PATCH 1/4] Shop: places per slot, and bookings block overlapping slots Slots get a capacity (items.capacity is the service default). Booking state is no longer stored on the slot: slotStates() in the shop hooks counts places from paid order lines and live basket holds (heldUntil moves to the basket line), and a slot with any place taken blocks every overlapping slot of any service, including get-ready time. GET /api/shop/slots lists bookable slots (public) or full detail for a signed-in admin. add_slot takes seats and adds to an existing line; group lines can change quantity. Checks and writes share one transaction. Migration moves existing holds, drops the unique index and slot status/heldUntil/order, and makes slots signed-in only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- app-public/src/lib/server/shop.ts | 3 +- packages/shared/src/server/shop.ts | 28 +- packages/shared/src/types.ts | 14 +- pb_schema.json | 18 +- pocketbase/pb_hooks/shop.pb.js | 12 + pocketbase/pb_hooks/shop/lib.js | 292 ++++++++++++++---- ...1792800100_slot_capacity_and_line_holds.js | 134 ++++++++ 7 files changed, 400 insertions(+), 101 deletions(-) create mode 100644 pocketbase/pb_migrations/1792800100_slot_capacity_and_line_holds.js diff --git a/app-public/src/lib/server/shop.ts b/app-public/src/lib/server/shop.ts index 2388562..245a58e 100644 --- a/app-public/src/lib/server/shop.ts +++ b/app-public/src/lib/server/shop.ts @@ -72,7 +72,8 @@ export function mapBasket(payload: BasketPayload): Basket | null { itemPrice: item?.price, itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined, slotStart: slot?.start, - slotEnd: slot?.end + slotEnd: slot?.end, + slotCapacity: slot?.capacity }; }); return { diff --git a/packages/shared/src/server/shop.ts b/packages/shared/src/server/shop.ts index e9beed0..9d8257a 100644 --- a/packages/shared/src/server/shop.ts +++ b/packages/shared/src/server/shop.ts @@ -3,20 +3,18 @@ import { getFileUrl } from '../pb'; import type { ItemRecord, SlotRecord } from '../types'; /** - * Active items and future available slots, shaped for the Shop/Checkout + * 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: the API rules expose active items, - * available slots and media publicly. Errors propagate. + * 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. */ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[]; slots: SlotRecord[] }> { - const [itemRecords, slotRecords] = await Promise.all([ + const [itemRecords, { slots }] = await Promise.all([ pb.collection('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }), - pb.collection('slots').getFullList({ - filter: pb.filter("status = 'available' && start >= {:now}", { now: new Date() }), - sort: 'start' - }) + pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null }) ]); const items = itemRecords.map((record): ItemRecord => { @@ -32,22 +30,10 @@ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[ stock: record.stock ?? null, duration: record.duration ?? null, bufferMinutes: record.bufferMinutes ?? null, + capacity: record.capacity ?? null, active: record.active }; }); - const slots = slotRecords.map( - (record): SlotRecord => ({ - id: record.id, - item: record.item, - start: record.start, - end: record.end || '', - status: record.status, - heldUntil: record.heldUntil || null, - order: record.order || null, - notes: record.notes || '' - }) - ); - return { items, slots }; } diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index bd51239..3d6e704 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -111,20 +111,21 @@ export type ItemRecord = { 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) active: boolean; }; -export type SlotStatus = 'available' | 'held' | 'booked'; - +/** + * A bookable slot as the shop lists it (GET /api/shop/slots): only slots + * with places left that no overlapping booking blocks. + */ export type SlotRecord = { id: string; item: string; // item id start: string; end: string; - status: SlotStatus; - heldUntil: string | null; - order: string | null; - notes: string; + capacity: number; // places in total + free: number; // places still bookable }; export type BasketStatus = 'active' | 'completed' | 'abandoned'; @@ -142,6 +143,7 @@ export type BasketLine = { itemImageUrl?: string; slotStart?: string; slotEnd?: string; + slotCapacity?: number; }; export type Basket = { diff --git a/pb_schema.json b/pb_schema.json index 9483ae2..9d4a987 100644 --- a/pb_schema.json +++ b/pb_schema.json @@ -332,6 +332,7 @@ { "id": "num_itemstock01", "name": "stock", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 0, "max": null } }, { "id": "num_itemdur0001", "name": "duration", "type": "number", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, { "id": "num_itembuffer1", "name": "bufferMinutes", "type": "number", "system": false, "required": false, "presentable": false, "min": 0, "max": null, "onlyInt": true }, + { "id": "num_itemcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true }, { "id": "bool_itemactive", "name": "active", "type": "bool", "system": false, "required": false, "presentable": false, "unique": false, "options": {} }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} @@ -345,8 +346,8 @@ "name": "slots", "type": "base", "system": false, - "listRule": "status = 'available' || @request.auth.id != ''", - "viewRule": "status = 'available' || @request.auth.id != ''", + "listRule": "@request.auth.id != ''", + "viewRule": "@request.auth.id != ''", "createRule": "@request.auth.id != ''", "updateRule": "@request.auth.id != ''", "deleteRule": "@request.auth.id != ''", @@ -355,16 +356,13 @@ { "id": "rel_slotitem001", "name": "item", "type": "relation", "system": false, "required": true, "presentable": false, "unique": false, "collectionId": "pbc_items00001", "cascadeDelete": true, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "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": "sel_slotstatus0", "name": "status", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["available", "held", "booked"] }, - { "id": "date_slotheldun0", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": "", "max": "" } }, - { "id": "rel_slotorder01", "name": "order", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_orders00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, + { "id": "num_slotcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true }, { "id": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ - "CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)", - "CREATE INDEX `idx_slots_status` ON `slots` (`status`)" + "CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)" ], "autodate": true, "options": {} @@ -412,12 +410,13 @@ { "id": "rel_blslot000001", "name": "slot", "type": "relation", "system": false, "required": false, "presentable": false, "unique": false, "collectionId": "pbc_slots00001", "cascadeDelete": false, "minSelect": 0, "maxSelect": 1, "displayFields": null }, { "id": "num_blquantity01", "name": "quantity", "type": "number", "system": false, "required": true, "presentable": false, "unique": false, "options": { "min": 1, "max": null } }, { "id": "sel_bllinetype01", "name": "lineType", "type": "select", "system": false, "required": true, "presentable": false, "unique": false, "maxSelect": 1, "values": ["item", "slot"] }, + { "id": "date_blheldunt1", "name": "heldUntil", "type": "date", "system": false, "required": false, "presentable": false, "hidden": false, "min": "", "max": "" }, {"id": "autodate_created", "name": "created", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": false}, {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ "CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)", - "CREATE UNIQUE INDEX `idx_basket_lines_slot_unique` ON `basket_lines` (`slot`) WHERE `slot` != ''" + "CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)" ], "autodate": true, "options": {} @@ -476,7 +475,8 @@ {"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true} ], "indexes": [ - "CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)" + "CREATE INDEX `idx_order_lines_order` ON `order_lines` (`order`)", + "CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)" ], "autodate": true, "options": {} diff --git a/pocketbase/pb_hooks/shop.pb.js b/pocketbase/pb_hooks/shop.pb.js index 936219e..724db81 100644 --- a/pocketbase/pb_hooks/shop.pb.js +++ b/pocketbase/pb_hooks/shop.pb.js @@ -3,6 +3,18 @@ /// treats its input as untrusted. The basket id acts as the customer's /// bearer token, exactly like the cookie it comes from. +// Slot availability (seats + cross-service blocking, see lib.js). Anyone +// gets the bookable future slots; a signed-in admin can ask for `detail`. +routerAdd('GET', '/api/shop/slots', (e) => { + const shop = require(`${__hooks}/shop/lib.js`); + const query = e.request.url.query(); + if (query.get('detail')) { + if (!e.auth) throw new UnauthorizedError('Sign in to see slot details'); + return e.json(200, { slots: shop.slotDetails($app, { from: query.get('from'), to: query.get('to'), item: query.get('item'), id: query.get('id') }) }); + } + return e.json(200, { slots: shop.bookableSlots($app) }); +}); + routerAdd('GET', '/api/shop/basket/{id}', (e) => { const shop = require(`${__hooks}/shop/lib.js`); shop.sweepExpiredHolds($app); diff --git a/pocketbase/pb_hooks/shop/lib.js b/pocketbase/pb_hooks/shop/lib.js index 3621bb9..f8509ed 100644 --- a/pocketbase/pb_hooks/shop/lib.js +++ b/pocketbase/pb_hooks/shop/lib.js @@ -55,30 +55,188 @@ function conflict(message) { return new ApiError(409, message); } +/** Epoch ms → PocketBase's stored datetime format, for comparing dates in filters. */ +function pbDate(ms) { + return new Date(ms).toISOString().replace('T', ' '); +} + +const DAY_MS = 24 * 60 * 60 * 1000; + +// ── Slot availability ─────────────────────────────────────────────────── +// +// Nothing about bookings is stored on a slot. Its seats are taken by paid +// order lines and by basket lines whose hold (`heldUntil`) hasn't lapsed; +// it has `capacity` seats (1 for a one-to-one massage, more for a group). +// +// One practitioner works all services, so a slot with any seat taken +// BLOCKS every other slot it overlaps — whatever the service — including +// each service's get-ready time after it. The client can offer three +// massages at 10:00; once one is booked (or in a basket), the others go. + +/** + * Occupancy and blocking for the slots starting in [rangeStart, rangeEnd) (epoch ms). + * `options.excludeLineId` leaves one basket line's seats out (used when + * changing that line's quantity). Must run inside a transaction when the + * result decides a write: PocketBase runs transactions one at a time, so + * the check and the write can't interleave with another customer's. + */ +function slotStates(app, rangeStart, rangeEnd, options) { + const opts = options || {}; + // Slots just outside the range can still block ones inside it. + const range = { from: pbDate(rangeStart - DAY_MS), to: pbDate(rangeEnd + DAY_MS) }; + const records = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start'); + if (!records.length) return []; + + const items = {}; + const byId = {}; + const states = records.map((record) => { + const itemId = record.getString('item'); + if (!(itemId in items)) items[itemId] = findOrNull(app, 'items', itemId); + const item = items[itemId]; + const start = toMs(record.getString('start')); + const storedEnd = toMs(record.getString('end')); + const end = Number.isNaN(storedEnd) ? start + (item ? item.getInt('duration') : 0) * 60000 : storedEnd; + const state = { + id: record.id, + item: itemId, + itemName: item ? item.getString('name') : '', + bookable: !!item && item.getBool('active') && item.getString('type') === 'item_with_time', + start, + end, + readyAt: end + Math.max(0, item ? item.getInt('bufferMinutes') : 0) * 60000, + capacity: Math.max(1, record.getInt('capacity')), + notes: record.getString('notes'), + booked: 0, + held: 0, + blockedBy: '' + }; + byId[record.id] = state; + return state; + }); + + const lineRange = 'slot.start >= {:from} && slot.start < {:to}'; + for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + lineRange, range)) { + const state = byId[line.getString('slot')]; + if (state) state.booked += line.getInt('quantity'); + } + const heldParams = Object.assign({ now: pbDate(Date.now()) }, range); + for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + lineRange, heldParams)) { + const state = byId[line.getString('slot')]; + if (state && line.id !== opts.excludeLineId) state.held += line.getInt('quantity'); + } + + const occupied = states.filter((s) => s.booked + s.held > 0); + for (const state of states) { + const blocker = occupied.find((o) => o.id !== state.id && state.start < o.readyAt && o.start < state.readyAt); + if (blocker) state.blockedBy = blocker.id; + } + return states.filter((s) => s.start >= rangeStart && s.start < rangeEnd); +} + +/** One slot's state (see slotStates), or null if it doesn't exist. */ +function slotState(app, slotId, options) { + const record = findOrNull(app, 'slots', slotId); + if (!record) return null; + const start = toMs(record.getString('start')); + return slotStates(app, start, start + 1, options).find((s) => s.id === slotId) || null; +} + +function freeSeats(state) { + return state.capacity - state.booked - state.held; +} + +/** Future slots a customer can book right now — the public shop listing. */ +function bookableSlots(app) { + const now = Date.now(); + return slotStates(app, now, now + 366 * DAY_MS) + .filter((s) => s.bookable && !s.blockedBy && freeSeats(s) > 0) + .map((s) => ({ + id: s.id, + item: s.item, + start: new Date(s.start).toISOString(), + end: new Date(s.end).toISOString(), + capacity: s.capacity, + free: freeSeats(s) + })); +} + +/** + * Every slot in a range (or one slot by id) with its seats and blocking — + * for the signed-in admin. `query`: from/to (ISO), optional item, or id. + */ +function slotDetails(app, query) { + let states; + if (query.id) { + const state = slotState(app, String(query.id)); + states = state ? [state] : []; + } else { + const from = toMs(query.from); + const to = toMs(query.to); + if (Number.isNaN(from) || Number.isNaN(to) || to <= from) throw new BadRequestError('from and to are required'); + if (to - from > 400 * DAY_MS) throw new BadRequestError('Range too long'); + states = slotStates(app, from, to); + if (query.item) states = states.filter((s) => s.item === query.item); + } + return states.map((s) => ({ + id: s.id, + item: s.item, + itemName: s.itemName, + start: new Date(s.start).toISOString(), + end: new Date(s.end).toISOString(), + capacity: s.capacity, + notes: s.notes, + booked: s.booked, + held: s.held, + blockedBy: s.blockedBy + })); +} + +/** + * Check a slot can take `seats` more seats; returns an ApiError to throw, + * or null. Call inside the transaction that then writes the hold. + */ +function seatProblem(state, seats) { + if (!state || !state.bookable) return new NotFoundError('Slot not found'); + if (state.start <= Date.now()) return conflict('This time has already passed — please pick another'); + if (state.blockedBy) return conflict('This time is no longer available — please pick another'); + const free = freeSeats(state); + if (seats > free) { + return conflict(free <= 0 ? 'This time is fully booked — please pick another' : `Only ${free} place${free === 1 ? '' : 's'} left at this time`); + } + return null; +} + +/** + * Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing + * is written) or nothing to commit. Unexpected failures become `fallback`. + */ +function guardedTransaction(app, fallback, fn) { + let refusal = null; + try { + app.runInTransaction((tx) => { + refusal = fn(tx) || null; + }); + } catch (e) { + console.error('[shop]', fallback, e); + throw conflict(fallback); + } + if (refusal) throw refusal; +} + // ── Holds and baskets ─────────────────────────────────────────────────── /** - * Release slots whose hold has lapsed (dropping the basket lines holding - * them) and abandon expired baskets. Runs every minute (cron) and before - * basket/checkout operations, so expiry is exact where it matters. + * Drop basket lines whose slot hold has lapsed (their seats are already + * free — availability only counts live holds — this is just tidying) and + * abandon expired baskets. Runs every minute (cron) and before + * basket/checkout operations. */ function sweepExpiredHolds(app) { - const now = Date.now(); - for (const slot of findAll(app, 'slots', "status = 'held'")) { - const until = toMs(slot.getString('heldUntil')); - // Still valid, or no parseable hold to judge by — leave it alone. - if (Number.isNaN(until) || until > now) continue; + for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil < {:now}", { now: pbDate(Date.now()) })) { try { - app.runInTransaction((tx) => { - for (const line of findAll(tx, 'basket_lines', 'slot = {:slot}', { slot: slot.id })) tx.delete(line); - const fresh = tx.findRecordById('slots', slot.id); - if (fresh.getString('status') !== 'held') return; - fresh.set('status', 'available'); - fresh.set('heldUntil', ''); - tx.save(fresh); - }); + app.delete(line); } catch (e) { - console.error('[shop] could not release slot', slot.id, e); + console.error('[shop] could not drop expired basket line', line.id, e); } } @@ -115,26 +273,32 @@ function createBasket(app) { return basket; } -function releaseSlotHold(app, slotId) { - const slot = findOrNull(app, 'slots', slotId); - if (!slot || slot.getString('status') !== 'held') return; - slot.set('status', 'available'); - slot.set('heldUntil', ''); - app.save(slot); -} - /** - * Renew the hold on every slot line in a basket whose slot is still `held` - * (nobody else can take a held slot, so renewing is safe). Used at checkout - * start (30 min) and after a failed payment (10 min, so the customer can retry). + * Renew the hold on every slot line in a basket. Used at checkout start + * (30 min) and after a failed payment (10 min, so the customer can retry). + * A live hold is simply extended (its seats are already counted). A lapsed + * one that hasn't been swept yet is rescued only if its seats are still + * free and nothing has blocked the time since — otherwise it's left for + * the sweep, and checkout tells the customer the slot expired. */ function extendBasketHolds(app, basketId, durationMs) { + const now = Date.now(); const until = isoIn(durationMs); for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) { - const slot = findOrNull(app, 'slots', line.getString('slot')); - if (slot && slot.getString('status') === 'held') { - slot.set('heldUntil', until); - app.save(slot); + if (toMs(line.getString('heldUntil')) > now) { + line.set('heldUntil', until); + app.save(line); + continue; + } + try { + app.runInTransaction((tx) => { + const fresh = tx.findRecordById('basket_lines', line.id); + if (seatProblem(slotState(tx, fresh.getString('slot')), fresh.getInt('quantity'))) return; + fresh.set('heldUntil', until); + tx.save(fresh); + }); + } catch (e) { + console.error('[shop] could not renew hold', line.id, e); } } } @@ -175,35 +339,38 @@ function basketAction(app, body) { } case 'add_slot': { + // Adding a slot that's already in the basket adds seats to that line. const slotId = String(body.slotId || ''); - if (lines.some((l) => l.getString('slot') === slotId)) throw conflict('Slot already in your basket'); - const slot = findOrNull(app, 'slots', slotId); - if (!slot) throw new NotFoundError('Slot not found'); - if (slot.getString('status') !== 'available') throw conflict('Slot is no longer available'); - - // Line + hold in one transaction. basket_lines.slot is UNIQUE, so of - // two concurrent requests for the same slot only one can succeed. - try { - app.runInTransaction((tx) => { - const fresh = tx.findRecordById('slots', slotId); - if (fresh.getString('status') !== 'available') throw new Error('taken'); - tx.save(newRecord(tx, 'basket_lines', { basket: basket.id, item: fresh.getString('item'), slot: slotId, quantity: 1, lineType: 'slot' })); - fresh.set('status', 'held'); - fresh.set('heldUntil', isoIn(SLOT_HOLD_MS)); - tx.save(fresh); - }); - } catch (_) { - throw conflict('Slot was just reserved by someone else'); - } + const seats = Math.max(1, Math.floor(Number(body.seats)) || 1); + guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => { + const problem = seatProblem(slotState(tx, slotId), seats); + if (problem) return problem; + const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0]; + const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' }); + line.set('quantity', line.getInt('quantity') + seats); + line.set('heldUntil', isoIn(SLOT_HOLD_MS)); + tx.save(line); + }); break; } case 'update_quantity': { const line = lines.find((l) => l.id === String(body.lineId || '')); if (!line) throw new NotFoundError('Line not found in your basket'); - if (line.getString('lineType') === 'slot') throw new BadRequestError('Slot lines have fixed quantity 1'); const quantity = Number(body.quantity); if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer'); + if (line.getString('lineType') === 'slot') { + // Seats for a group session: re-check capacity without this line's current seats. + guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => { + const fresh = tx.findRecordById('basket_lines', line.id); + const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity); + if (problem) return problem; + fresh.set('quantity', quantity); + fresh.set('heldUntil', isoIn(SLOT_HOLD_MS)); + tx.save(fresh); + }); + break; + } const item = findOrNull(app, 'items', line.getString('item')); const stock = item ? item.get('stock') : null; if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`); @@ -215,9 +382,7 @@ function basketAction(app, body) { case 'remove_line': { const line = lines.find((l) => l.id === String(body.lineId || '')); if (!line) throw new NotFoundError('Line not found in your basket'); - const slotId = line.getString('slot'); - app.delete(line); - if (slotId) releaseSlotHold(app, slotId); + app.delete(line); // a slot line's seats free up with it break; } @@ -303,8 +468,8 @@ function startCheckout(app, body) { if (!item || !item.getBool('active')) throw conflict('An item in your basket is no longer available'); const quantity = line.getInt('quantity'); if (line.getString('lineType') === 'slot') { - const slot = findOrNull(app, 'slots', line.getString('slot')); - if (!slot || slot.getString('status') !== 'held') { + // The sweep above dropped lapsed holds that couldn't be renewed. + if (!findOrNull(app, 'slots', line.getString('slot')) || !(toMs(line.getString('heldUntil')) > Date.now())) { throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`); } } else { @@ -426,7 +591,9 @@ function createOrderFromIntent(app, intent) { }); tx.save(order); - // Snapshot lines, book slots, decrement stock. + // Snapshot lines and decrement stock. A slot's seats move from the + // basket line (a hold) to the order line (a booking) in this same + // transaction, so availability never sees them free in between. for (const line of lines) { const item = findOrNull(tx, 'items', line.getString('item')); const slot = findOrNull(tx, 'slots', line.getString('slot')); @@ -442,12 +609,7 @@ function createOrderFromIntent(app, intent) { start: slot ? slot.getString('start') : '' }) ); - if (line.getString('lineType') === 'slot' && slot) { - slot.set('status', 'booked'); - slot.set('heldUntil', ''); - slot.set('order', order.id); - tx.save(slot); - } else if (item && item.get('stock') != null && item.get('stock') !== '') { + if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') { item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity'))); tx.save(item); } @@ -539,6 +701,8 @@ function recordEmailStatus(app, secretHeader, body) { } module.exports = { + bookableSlots, + slotDetails, sweepExpiredHolds, loadActiveBasket, basketPayload, diff --git a/pocketbase/pb_migrations/1792800100_slot_capacity_and_line_holds.js b/pocketbase/pb_migrations/1792800100_slot_capacity_and_line_holds.js new file mode 100644 index 0000000..cf9c5e5 --- /dev/null +++ b/pocketbase/pb_migrations/1792800100_slot_capacity_and_line_holds.js @@ -0,0 +1,134 @@ +/// + +// Slots get seats; bookings stop being stored on the slot. +// +// Before: a slot was one customer — `status` available|held|booked, +// `heldUntil`, `order`, and a UNIQUE index so only one basket line could +// point at a slot. After: a slot has `capacity` seats (items.capacity is +// the service's default), and the shop hooks derive everything else — +// seats taken = paid order lines + basket lines with a live `heldUntil`, +// plus blocking by overlapping slots (see pb_hooks/shop/lib.js). +// +// 1. items.capacity, slots.capacity (existing slots: 1). +// 2. basket_lines.heldUntil, copied from the slot each line was holding. +// 3. basket_lines.slot: unique index → plain index (many baskets may hold +// seats on one slot); index order_lines.slot for seat counting. +// 4. slots: drop status/heldUntil/order and the status index. Booked +// seats already live in order_lines (with the slot and a start snapshot). +// 5. slots: API rules signed-in only. The public shop lists slots through +// GET /api/shop/slots, which hides full and blocked ones. + +function find(app, name) { + try { + return app.findCollectionByNameOrId(name); + } catch (e) { + return null; // fresh install: pb_schema.json (already in this shape) is imported later + } +} + +const AUTH_ONLY = "@request.auth.id != ''"; + +migrate( + (app) => { + const items = find(app, 'items'); + const slots = find(app, 'slots'); + const basketLines = find(app, 'basket_lines'); + const orderLines = find(app, 'order_lines'); + + // 1. Capacity. + if (items && !items.fields.getByName('capacity')) { + items.fields.add(new NumberField({ id: 'num_itemcapacity', name: 'capacity', min: 1, onlyInt: true })); + app.save(items); + } + if (slots && !slots.fields.getByName('capacity')) { + slots.fields.add(new NumberField({ id: 'num_slotcapacity', name: 'capacity', min: 1, onlyInt: true })); + app.save(slots); + for (const slot of app.findAllRecords('slots')) { + slot.set('capacity', 1); + try { + app.saveNoValidate(slot); + } catch (e) { + console.log(`[migration] could not set capacity on slot ${slot.id}: ${e}`); + } + } + } + + // 2. Holds move to the basket line. + if (basketLines && !basketLines.fields.getByName('heldUntil')) { + basketLines.fields.add(new DateField({ id: 'date_blheldunt1', name: 'heldUntil' })); + app.save(basketLines); + if (slots && slots.fields.getByName('heldUntil')) { + for (const line of app.findRecordsByFilter('basket_lines', "slot != ''", '', 0, 0)) { + try { + const slot = app.findRecordById('slots', line.getString('slot')); + if (slot.getString('status') !== 'held') continue; // leaves heldUntil empty → swept + line.set('heldUntil', slot.getString('heldUntil')); + app.saveNoValidate(line); + } catch (e) { + console.log(`[migration] could not move the hold of basket line ${line.id}: ${e}`); + } + } + } + } + + // 3. Indexes. + if (basketLines) { + basketLines.indexes = basketLines.indexes + .filter((index) => !index.includes('idx_basket_lines_slot_unique')) + .concat(basketLines.indexes.some((index) => index.includes('idx_basket_lines_slot`')) ? [] : ['CREATE INDEX `idx_basket_lines_slot` ON `basket_lines` (`slot`)']); + app.save(basketLines); + } + if (orderLines && !orderLines.indexes.some((index) => index.includes('idx_order_lines_slot'))) { + orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_slot` ON `order_lines` (`slot`)']; + app.save(orderLines); + } + + // 4 + 5. Slot fields and rules. + if (slots) { + slots.indexes = slots.indexes.filter((index) => !index.includes('idx_slots_status')); + for (const name of ['status', 'heldUntil', 'order']) { + if (slots.fields.getByName(name)) slots.fields.removeByName(name); + } + slots.listRule = AUTH_ONLY; + slots.viewRule = AUTH_ONLY; + app.save(slots); + } + }, + (app) => { + // Revert the schema. Holds and bookings are NOT written back onto + // slots (every slot comes back `available`) — restore a backup if + // you need the old state exactly. + const slots = find(app, 'slots'); + if (slots) { + if (!slots.fields.getByName('status')) slots.fields.add(new SelectField({ id: 'sel_slotstatus0', name: 'status', values: ['available', 'held', 'booked'], maxSelect: 1 })); + if (!slots.fields.getByName('heldUntil')) slots.fields.add(new DateField({ id: 'date_slotheldun0', name: 'heldUntil' })); + const orders = find(app, 'orders'); + if (orders && !slots.fields.getByName('order')) slots.fields.add(new RelationField({ id: 'rel_slotorder01', name: 'order', collectionId: orders.id, maxSelect: 1 })); + if (slots.fields.getByName('capacity')) slots.fields.removeByName('capacity'); + slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_status')), 'CREATE INDEX `idx_slots_status` ON `slots` (`status`)']; + slots.listRule = "status = 'available' || @request.auth.id != ''"; + slots.viewRule = "status = 'available' || @request.auth.id != ''"; + app.save(slots); + for (const slot of app.findAllRecords('slots')) { + slot.set('status', 'available'); + app.saveNoValidate(slot); + } + } + const items = find(app, 'items'); + if (items && items.fields.getByName('capacity')) { + items.fields.removeByName('capacity'); + app.save(items); + } + const basketLines = find(app, 'basket_lines'); + if (basketLines) { + if (basketLines.fields.getByName('heldUntil')) basketLines.fields.removeByName('heldUntil'); + basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_slot`')); + app.save(basketLines); + } + const orderLines = find(app, 'order_lines'); + if (orderLines) { + orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_slot')); + app.save(orderLines); + } + } +); From 5c6dff9e1883c78763b350c85da4366f24926fdf Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 08:26:37 +0000 Subject: [PATCH 2/4] Shop block: places left for group sessions, refresh after booking Group times show places left and can be added again for another place; the listing reloads after adding, since one booking can block other times. Checkout gets a quantity stepper for group lines. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- .../shared/src/blocks/CheckoutBlock.svelte | 3 ++- packages/shared/src/blocks/ShopBlock.svelte | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/shared/src/blocks/CheckoutBlock.svelte b/packages/shared/src/blocks/CheckoutBlock.svelte index bd12b04..1cd7437 100644 --- a/packages/shared/src/blocks/CheckoutBlock.svelte +++ b/packages/shared/src/blocks/CheckoutBlock.svelte @@ -240,7 +240,8 @@

{currency.format(line.itemPrice ?? 0)}

- {#if line.lineType === 'item'} + + {#if line.lineType === 'item' || (line.slotCapacity ?? 1) > 1}
{/each}
From a22d9f234885e8cad94c53f84ec3dd6d47f9e51e Mon Sep 17 00:00:00 2001 From: agent Date: Sat, 24 Oct 2026 08:26:37 +0000 Subject: [PATCH 3/4] Admin slots: places, blocked/full states, edits limited once booked Calendar, day panel and list show available / in a basket / booked / full / blocked (with what blocks it) and places taken. Services, Generate and single slots take places (default from the service); Copy keeps them. Once any place is taken only places (not below taken) and notes can change. All reads go through the shop hook's slot details. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk --- .../lib/admin/slots/GenerateSlotsModal.svelte | 26 ++- app-admin/src/lib/server/slots.ts | 60 +++---- app-admin/src/routes/items/+page.server.ts | 4 + app-admin/src/routes/items/+page.svelte | 13 +- app-admin/src/routes/slots/+page.server.ts | 156 +++++++++--------- app-admin/src/routes/slots/+page.svelte | 110 +++++++----- packages/shared/src/slots.ts | 34 ++++ 7 files changed, 231 insertions(+), 172 deletions(-) diff --git a/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte b/app-admin/src/lib/admin/slots/GenerateSlotsModal.svelte index 40c6c73..fe78858 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 }; + type Service = { id: string; name: string; duration: number; bufferMinutes: number; capacity: number }; let { open = $bindable(false), @@ -23,6 +23,7 @@ weekdays: [1, 2, 3, 4, 5], windows: [{ from: '09:00', to: '17:00' }] as TimeWindow[], bufferMinutes: '', + capacity: '', notes: '' }); @@ -50,8 +51,10 @@ function selectService(id: string) { draft.item = id; - // 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); + // 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); } function addWindow() { @@ -109,11 +112,18 @@ - +
+ + +
{#if service}

diff --git a/app-admin/src/lib/server/slots.ts b/app-admin/src/lib/server/slots.ts index cfe9938..f3afb64 100644 --- a/app-admin/src/lib/server/slots.ts +++ b/app-admin/src/lib/server/slots.ts @@ -1,56 +1,34 @@ -// 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. +// Server helpers for the /slots page. Planning is pure and lives in +// $shared/slots; this file does the PocketBase reads/writes around it. -import { instantMs, type PlannedSlot } from '$lib/slots'; +import type { SlotDetail } 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. + */ +export async function loadSlotDetails(pb: Pb, query: { from: string; to: string; item?: string } | { id: string }) { + const { slots } = await pb.send<{ slots: SlotDetail[] }>('/api/shop/slots', { + query: { detail: 1, ...query }, + requestKey: null + }); + return slots; } -/** - * 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 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 || '') - }; - }); +/** 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 090672b..8b8a2ca 100644 --- a/app-admin/src/routes/items/+page.server.ts +++ b/app-admin/src/routes/items/+page.server.ts @@ -9,9 +9,11 @@ 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(), @@ -22,6 +24,7 @@ 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' }; } @@ -39,6 +42,7 @@ 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 fefdd41..3524857 100644 --- a/app-admin/src/routes/items/+page.svelte +++ b/app-admin/src/routes/items/+page.svelte @@ -22,6 +22,7 @@ stock: string; duration: string; bufferMinutes: string; + capacity: string; active: boolean; }; @@ -31,7 +32,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: '', active: true }; + return { id: '', name: '', description: '', price: 0, image: '', imageUrl: '', type: 'item', stock: '', duration: '', bufferMinutes: '', capacity: '', active: true }; } function createItem() { @@ -52,6 +53,7 @@ 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 = ''; @@ -109,7 +111,7 @@ {item.type === 'item_with_time' ? 'Service' : 'Product'} {money.format(item.price)} {item.type === 'item' ? (item.stock ?? '∞') : '—'} - {item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}` : '—'} + {item.type === 'item_with_time' ? `${item.duration ?? 0} min${item.bufferMinutes ? ` + ${item.bufferMinutes} get-ready` : ''}${(item.capacity ?? 1) > 1 ? ` · ${item.capacity} places` : ''}` : '—'} {item.active ? 'Active' : 'Inactive'} @@ -166,7 +168,12 @@ + {/if} diff --git a/app-admin/src/routes/slots/+page.server.ts b/app-admin/src/routes/slots/+page.server.ts index 070f00a..ab5508a 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 { isHoldActive, loadSlotsBetween, runInBatches, type ExistingSlot } from '$lib/server/slots'; +import { loadSlotDetail, loadSlotDetails, runInBatches, seatsTaken } from '$lib/server/slots'; import { MAX_BULK_SLOTS, addDaysToKey, @@ -18,17 +18,20 @@ 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; notes: string } } + | { payload: { item: string; start: string; end: string; capacity: number; 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. */ @@ -36,6 +39,19 @@ 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(); @@ -57,12 +73,15 @@ 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); - // 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 } }; + // 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 } }; } /** Validated `from`/`to` date keys from a bulk form, or an error message. */ @@ -75,6 +94,14 @@ function dateRange(data: FormData): { fromDate: string; toDate: string } | { err return { fromDate, toDate }; } +/** 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); @@ -84,14 +111,14 @@ async function bookableService(pb: Pb, itemId: string) { /** * Drop candidates that start in the past or overlap a slot of the same * service (existing, or accepted earlier in this run). Different services - * may overlap freely — there is no cross-service collision detection. + * may share a time: whichever is booked first blocks the others. */ -function filterCandidates(candidates: (PlannedSlot & { item: string })[], existing: ExistingSlot[]) { +function filterCandidates(candidates: Candidate[], existing: SlotDetail[]) { const now = Date.now(); const taken = new Map(); for (const slot of existing) taken.set(slot.item, [...(taken.get(slot.item) ?? []), slot]); - const accepted: typeof candidates = []; + const accepted: Candidate[] = []; let skippedPast = 0; let skippedOverlap = 0; for (const candidate of candidates) { @@ -117,13 +144,7 @@ function bulkResult(fields: Partial & Pick, - notesFor: (slot: PlannedSlot & { item: string }) => string -) { +async function previewOrCreate(pb: Pb, action: 'generate' | 'copy', intent: string, result: ReturnType) { 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.` }); @@ -138,7 +159,7 @@ async function previewOrCreate( 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, notes: notesFor(slot), status: 'available' }) + pb.collection('slots').create({ item: slot.item, start: slot.start, end: slot.end, capacity: slot.capacity, notes: slot.notes }) ); return bulkResult({ ...summary, intent: 'done', count: created, failed: accepted.length - created }); } @@ -156,36 +177,15 @@ export const load: PageServerLoad = async ({ locals, url }) => { id: record.id, name: String(record.name || ''), duration: Number(record.duration) || 0, - bufferMinutes: Number(record.bufferMinutes) || 0 + bufferMinutes: Number(record.bufferMinutes) || 0, + capacity: Math.max(1, Number(record.capacity) || 1) })); // Only the slots shown in the month grid (which spans whole weeks). const grid = monthGridKeys(month); - 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 || '') - })); + const slots = await slotsForDays(locals.pb, grid[0], grid[grid.length - 1]); - return { items, slots, month, today }; + return { items, slots: slots ?? [], slotsError: slots === null, month, today }; }; export const actions: Actions = { @@ -193,9 +193,7 @@ 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, status: 'available' }) - ); + const created = await attempt('Could not create the slot.', () => locals.pb.collection('slots').create(result.payload)); if (!created.ok) return created.failure; return { ok: true }; }, @@ -204,15 +202,20 @@ 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 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); + // 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?' }); if (!current) return fail(404, { message: 'This slot no longer exists.' }); - if (current.status === 'booked') return fail(400, { message: 'Booked slots cannot be edited.' }); - let patch: Record; - if (isHoldActive(current)) { - patch = { notes: String(data.get('notes') || '').trim() }; + 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() }; } else { const result = await slotPayload(data, locals.pb); if ('error' in result) return fail(400, { message: result.error }); @@ -226,9 +229,10 @@ 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 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 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 deleted = await attempt('Could not delete the slot.', () => locals.pb.collection('slots').delete(id)); if (!deleted.ok) return deleted.failure; return { ok: true }; @@ -245,6 +249,8 @@ 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.' }); @@ -267,17 +273,12 @@ 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 loadSlotsBetween( - locals.pb, - dayStartIso(range.fromDate), - dayStartIso(addDaysToKey(range.toDate, 1)), - item.id - ).catch(() => null); + 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 notes = String(data.get('notes') || '').trim(); - const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id })), existing); - return previewOrCreate(locals.pb, 'generate', intent, result, () => notes); + const result = filterCandidates(planned.map((slot) => ({ ...slot, item: item.id, capacity, notes })), existing); + return previewOrCreate(locals.pb, 'generate', intent, result); }, /** Repeat one week's slots (all services, or one) for the following weeks. */ @@ -290,33 +291,26 @@ export const actions: Actions = { if (!(weeks >= 1 && weeks <= MAX_COPY_WEEKS)) return fail(400, { message: `Copy to between 1 and ${MAX_COPY_WEEKS} weeks.` }); const itemId = String(data.get('item') || ''); - 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); + 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); 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.' }); - const notesByStart = new Map(); - const candidates: (PlannedSlot & { item: string })[] = []; + // Copies are new, empty slots: same service, places and notes. + const candidates: Candidate[] = []; 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 }); - notesByStart.set(`${slot.item}|${start}`, slot.notes); + candidates.push({ item: slot.item, start, end, capacity: slot.capacity, notes: slot.notes }); } } - const result = filterCandidates(candidates, existing); - return previewOrCreate(locals.pb, 'copy', intent, result, (slot) => notesByStart.get(`${slot.item}|${slot.start}`) ?? ''); + return previewOrCreate(locals.pb, 'copy', intent, filterCandidates(candidates, existing)); }, - /** Delete the free slots in a date range. Booked and currently-held slots stay. */ + /** Delete the slots in a date range that have no places taken. */ clear: async ({ request, locals }) => { const data = await request.formData(); const intent = String(data.get('intent') || 'preview'); @@ -324,10 +318,10 @@ export const actions: Actions = { if ('error' in range) return fail(400, { message: range.error }); const itemId = String(data.get('item') || ''); - const slots = await loadSlotsBetween(locals.pb, dayStartIso(range.fromDate), dayStartIso(addDaysToKey(range.toDate, 1)), itemId).catch(() => null); + const slots = await slotsForDays(locals.pb, range.fromDate, range.toDate, itemId); if (!slots) return fail(400, { message: 'Could not read slots — is the database reachable?' }); - const removable = slots.filter((slot) => slot.status !== 'booked' && !isHoldActive(slot)); + const removable = slots.filter((slot) => seatsTaken(slot) === 0); const summary = { action: 'clear' as const, kept: slots.length - removable.length, @@ -339,8 +333,8 @@ export const actions: Actions = { // Re-check each slot just before deleting it: a customer may have put // it in their basket since the list was read. const deleted = await runInBatches(removable, 'delete', async (slot) => { - const fresh = await locals.pb.collection('slots').getOne(slot.id); - if (fresh.status === 'booked' || isHoldActive(fresh)) throw new Error('taken since the preview'); + const fresh = await loadSlotDetail(locals.pb, slot.id); + if (fresh && seatsTaken(fresh) > 0) 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 65aafdf..20d97cc 100644 --- a/app-admin/src/routes/slots/+page.svelte +++ b/app-admin/src/routes/slots/+page.svelte @@ -7,14 +7,15 @@ 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 { WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys } from '$lib/slots'; - import type { BulkResult } from '$lib/slots'; + import { SLOT_STATE_LABELS, WEEKDAYS, addDaysToKey, addMonthsToKey, formatDateKey, mondayOfKey, monthGridKeys, slotState } from '$lib/slots'; + import type { BulkResult, SlotState } 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; @@ -47,14 +48,34 @@ 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 (booked or taken in the meantime)' : 'saved'}.` : ''; + const failed = result.failed ? ` ${n(result.failed)} could not be ${result.action === 'clear' ? 'deleted (places taken in the meantime)' : 'saved'}.` : ''; return `${verb} ${n(result.count)}.${failed}`; } - 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'; + 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 openDay(key: string) { @@ -79,15 +100,17 @@ id: string; item: string; start: string; - status: string; - heldUntil: string; + capacity: string; + booked: number; + held: number; notes: string; }; let draft = $state(emptyDraft()); let editorError = $state(''); let action = $derived(draft.id ? '?/update' : '?/create'); - let isHeld = $derived(draft.status === 'held'); + // Once any place is taken, the service and time are fixed (customers booked them). + let taken = $derived(draft.booked + draft.held); let selectedItem = $derived(items.find((item) => item.id === draft.item)); let endLabel = $derived.by(() => { if (!selectedItem || !draft.start) return ''; @@ -99,7 +122,7 @@ function emptyDraft(day = ''): SlotDraft { const start = day ? `${day}T09:00` : toZonedDatetimeInput(new Date().toISOString(), data.timezone); - return { id: '', item: serviceFilter, start, status: 'available', heldUntil: '', notes: '' }; + return { id: '', item: serviceFilter, start, capacity: '', booked: 0, held: 0, notes: '' }; } // Enhanced so the page keeps its ?month= after saving (a plain POST to @@ -129,8 +152,9 @@ id: slot.id, item: slot.item, start: toZonedDatetimeInput(slot.start, data.timezone), - status: slot.status, - heldUntil: slot.heldUntil, + capacity: String(slot.capacity), + booked: slot.booked, + held: slot.held, notes: slot.notes }; showDay = false; @@ -157,6 +181,7 @@ {#if form?.message}

{/if} {#if bulkDone}
{bulkMessage(bulkDone)}
{/if} {#if !items.length}
Add a bookable service under Services & products first.
{/if} + {#if data.slotsError}{/if}
@@ -189,9 +214,16 @@ >
{#each daySlotList.slice(0, MAX_CHIPS) as slot (slot.id)} - {/each} {#if daySlotList.length > MAX_CHIPS} @@ -203,9 +235,10 @@
- Available - In a basket - Booked + {#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.
@@ -214,23 +247,19 @@ All slots in {monthLabel} ({monthSlots.length})
- + {#each monthSlots as slot (slot.id)} + {@const state = slotState(slot)} - + {:else} @@ -250,19 +279,16 @@ {#if daySlots.length}
    {#each daySlots as slot (slot.id)} + {@const state = slotState(slot)}
  • {formatTime(slot.start, data.timezone)}{slot.end ? `–${formatTime(slot.end, data.timezone)}` : ''} - {slot.itemName} + {slot.itemName}{slot.capacity > 1 ? ` · ${slot.booked + slot.held}/${slot.capacity} places` : ''} + {#if state === 'blocked'}{blockedReason(slot)}{/if} {#if slot.notes}{slot.notes}{/if} - {slot.status} - + {SLOT_STATE_LABELS[state]} +
  • {/each}
@@ -284,15 +310,15 @@ {#if editorError}{/if} - {#if isHeld} + {#if taken}
- This slot is in a customer’s basket{draft.heldUntil ? ` until ${formatTime(draft.heldUntil, data.timezone)}` : ''} — only the notes can be changed. + {[draft.booked && `${draft.booked} booked`, draft.held && `${draft.held} in a customer’s basket`].filter(Boolean).join(', ')} — only the places and notes can be changed.
{/if}
ServiceDateDurationStatus
ServiceDatePlacesStatus
{slot.itemName} {formatDateTime(slot.start, data.timezone)}{slot.itemDuration ? `${slot.itemDuration} min` : '—'}{slot.booked + slot.held}/{slot.capacity} - {slot.status} + {SLOT_STATE_LABELS[state]} - +