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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VaXE9U7AmW3dfD2w6cbLfk
This commit is contained in:
parent
b52da79ec8
commit
d7765fe605
7 changed files with 400 additions and 101 deletions
|
|
@ -72,7 +72,8 @@ export function mapBasket(payload: BasketPayload): Basket | null {
|
||||||
itemPrice: item?.price,
|
itemPrice: item?.price,
|
||||||
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
itemImageUrl: media ? getFileUrl('media', media.id, media.file) : undefined,
|
||||||
slotStart: slot?.start,
|
slotStart: slot?.start,
|
||||||
slotEnd: slot?.end
|
slotEnd: slot?.end,
|
||||||
|
slotCapacity: slot?.capacity
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -3,20 +3,18 @@ import { getFileUrl } from '../pb';
|
||||||
import type { ItemRecord, SlotRecord } from '../types';
|
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
|
* blocks. Used by the public layout and the admin draft preview so both
|
||||||
* render the same shop.
|
* render the same shop.
|
||||||
*
|
*
|
||||||
* Works with an anonymous client: the API rules expose active items,
|
* Works with an anonymous client: active items and media are public, and
|
||||||
* available slots and media publicly. Errors propagate.
|
* 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[] }> {
|
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('items').getFullList({ filter: 'active = true', sort: 'name', expand: 'image' }),
|
||||||
pb.collection('slots').getFullList({
|
pb.send<{ slots: SlotRecord[] }>('/api/shop/slots', { requestKey: null })
|
||||||
filter: pb.filter("status = 'available' && start >= {:now}", { now: new Date() }),
|
|
||||||
sort: 'start'
|
|
||||||
})
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const items = itemRecords.map((record): ItemRecord => {
|
const items = itemRecords.map((record): ItemRecord => {
|
||||||
|
|
@ -32,22 +30,10 @@ export async function loadShopData(pb: PocketBase): Promise<{ items: ItemRecord[
|
||||||
stock: record.stock ?? null,
|
stock: record.stock ?? null,
|
||||||
duration: record.duration ?? null,
|
duration: record.duration ?? null,
|
||||||
bufferMinutes: record.bufferMinutes ?? null,
|
bufferMinutes: record.bufferMinutes ?? null,
|
||||||
|
capacity: record.capacity ?? null,
|
||||||
active: record.active
|
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 };
|
return { items, slots };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -111,20 +111,21 @@ export type ItemRecord = {
|
||||||
stock: number | null;
|
stock: number | null;
|
||||||
duration: number | null; // minutes, for item_with_time
|
duration: number | null; // minutes, for item_with_time
|
||||||
bufferMinutes: number | null; // get-ready time after each appointment; default gap when generating slots
|
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;
|
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 = {
|
export type SlotRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
item: string; // item id
|
item: string; // item id
|
||||||
start: string;
|
start: string;
|
||||||
end: string;
|
end: string;
|
||||||
status: SlotStatus;
|
capacity: number; // places in total
|
||||||
heldUntil: string | null;
|
free: number; // places still bookable
|
||||||
order: string | null;
|
|
||||||
notes: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
export type BasketStatus = 'active' | 'completed' | 'abandoned';
|
||||||
|
|
@ -142,6 +143,7 @@ export type BasketLine = {
|
||||||
itemImageUrl?: string;
|
itemImageUrl?: string;
|
||||||
slotStart?: string;
|
slotStart?: string;
|
||||||
slotEnd?: string;
|
slotEnd?: string;
|
||||||
|
slotCapacity?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type Basket = {
|
export type Basket = {
|
||||||
|
|
|
||||||
|
|
@ -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_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_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_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": "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_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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
|
|
@ -345,8 +346,8 @@
|
||||||
"name": "slots",
|
"name": "slots",
|
||||||
"type": "base",
|
"type": "base",
|
||||||
"system": false,
|
"system": false,
|
||||||
"listRule": "status = 'available' || @request.auth.id != ''",
|
"listRule": "@request.auth.id != ''",
|
||||||
"viewRule": "status = 'available' || @request.auth.id != ''",
|
"viewRule": "@request.auth.id != ''",
|
||||||
"createRule": "@request.auth.id != ''",
|
"createRule": "@request.auth.id != ''",
|
||||||
"updateRule": "@request.auth.id != ''",
|
"updateRule": "@request.auth.id != ''",
|
||||||
"deleteRule": "@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": "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_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": "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": "num_slotcapacity", "name": "capacity", "type": "number", "system": false, "required": false, "presentable": false, "min": 1, "max": null, "onlyInt": true },
|
||||||
{ "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": "text_slotnotes0", "name": "notes", "type": "text", "system": false, "required": false, "presentable": false, "unique": false, "options": { "min": null, "max": 500, "pattern": "" } },
|
{ "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_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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)",
|
"CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)"
|
||||||
"CREATE INDEX `idx_slots_status` ON `slots` (`status`)"
|
|
||||||
],
|
],
|
||||||
"autodate": true,
|
"autodate": true,
|
||||||
"options": {}
|
"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": "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": "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": "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_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}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"indexes": [
|
||||||
"CREATE INDEX `idx_basket_lines_basket` ON `basket_lines` (`basket`)",
|
"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,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
|
@ -476,7 +475,8 @@
|
||||||
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
{"id": "autodate_updated", "name": "updated", "type": "autodate", "system": false, "hidden": false, "presentable": false, "onCreate": true, "onUpdate": true}
|
||||||
],
|
],
|
||||||
"indexes": [
|
"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,
|
"autodate": true,
|
||||||
"options": {}
|
"options": {}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,18 @@
|
||||||
/// treats its input as untrusted. The basket id acts as the customer's
|
/// treats its input as untrusted. The basket id acts as the customer's
|
||||||
/// bearer token, exactly like the cookie it comes from.
|
/// 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) => {
|
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
||||||
const shop = require(`${__hooks}/shop/lib.js`);
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
shop.sweepExpiredHolds($app);
|
shop.sweepExpiredHolds($app);
|
||||||
|
|
|
||||||
|
|
@ -55,30 +55,188 @@ function conflict(message) {
|
||||||
return new ApiError(409, 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 ───────────────────────────────────────────────────
|
// ── Holds and baskets ───────────────────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Release slots whose hold has lapsed (dropping the basket lines holding
|
* Drop basket lines whose slot hold has lapsed (their seats are already
|
||||||
* them) and abandon expired baskets. Runs every minute (cron) and before
|
* free — availability only counts live holds — this is just tidying) and
|
||||||
* basket/checkout operations, so expiry is exact where it matters.
|
* abandon expired baskets. Runs every minute (cron) and before
|
||||||
|
* basket/checkout operations.
|
||||||
*/
|
*/
|
||||||
function sweepExpiredHolds(app) {
|
function sweepExpiredHolds(app) {
|
||||||
const now = Date.now();
|
for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil < {:now}", { now: pbDate(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;
|
|
||||||
try {
|
try {
|
||||||
app.runInTransaction((tx) => {
|
app.delete(line);
|
||||||
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);
|
|
||||||
});
|
|
||||||
} catch (e) {
|
} 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;
|
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`
|
* Renew the hold on every slot line in a basket. Used at checkout start
|
||||||
* (nobody else can take a held slot, so renewing is safe). Used at checkout
|
* (30 min) and after a failed payment (10 min, so the customer can retry).
|
||||||
* 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) {
|
function extendBasketHolds(app, basketId, durationMs) {
|
||||||
|
const now = Date.now();
|
||||||
const until = isoIn(durationMs);
|
const until = isoIn(durationMs);
|
||||||
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
|
for (const line of findAll(app, 'basket_lines', "basket = {:basket} && lineType = 'slot'", { basket: basketId })) {
|
||||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
if (toMs(line.getString('heldUntil')) > now) {
|
||||||
if (slot && slot.getString('status') === 'held') {
|
line.set('heldUntil', until);
|
||||||
slot.set('heldUntil', until);
|
app.save(line);
|
||||||
app.save(slot);
|
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': {
|
case 'add_slot': {
|
||||||
|
// Adding a slot that's already in the basket adds seats to that line.
|
||||||
const slotId = String(body.slotId || '');
|
const slotId = String(body.slotId || '');
|
||||||
if (lines.some((l) => l.getString('slot') === slotId)) throw conflict('Slot already in your basket');
|
const seats = Math.max(1, Math.floor(Number(body.seats)) || 1);
|
||||||
const slot = findOrNull(app, 'slots', slotId);
|
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
|
||||||
if (!slot) throw new NotFoundError('Slot not found');
|
const problem = seatProblem(slotState(tx, slotId), seats);
|
||||||
if (slot.getString('status') !== 'available') throw conflict('Slot is no longer available');
|
if (problem) return problem;
|
||||||
|
const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0];
|
||||||
// Line + hold in one transaction. basket_lines.slot is UNIQUE, so of
|
const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' });
|
||||||
// two concurrent requests for the same slot only one can succeed.
|
line.set('quantity', line.getInt('quantity') + seats);
|
||||||
try {
|
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||||
app.runInTransaction((tx) => {
|
tx.save(line);
|
||||||
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');
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'update_quantity': {
|
case 'update_quantity': {
|
||||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
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);
|
const quantity = Number(body.quantity);
|
||||||
if (!Number.isInteger(quantity) || quantity < 1) throw new BadRequestError('Quantity must be a positive integer');
|
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 item = findOrNull(app, 'items', line.getString('item'));
|
||||||
const stock = item ? item.get('stock') : null;
|
const stock = item ? item.get('stock') : null;
|
||||||
if (stock != null && stock !== '' && quantity > item.getInt('stock')) throw conflict(`Only ${item.getInt('stock')} in stock`);
|
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': {
|
case 'remove_line': {
|
||||||
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
const line = lines.find((l) => l.id === String(body.lineId || ''));
|
||||||
if (!line) throw new NotFoundError('Line not found in your basket');
|
if (!line) throw new NotFoundError('Line not found in your basket');
|
||||||
const slotId = line.getString('slot');
|
app.delete(line); // a slot line's seats free up with it
|
||||||
app.delete(line);
|
|
||||||
if (slotId) releaseSlotHold(app, slotId);
|
|
||||||
break;
|
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');
|
if (!item || !item.getBool('active')) throw conflict('An item in your basket is no longer available');
|
||||||
const quantity = line.getInt('quantity');
|
const quantity = line.getInt('quantity');
|
||||||
if (line.getString('lineType') === 'slot') {
|
if (line.getString('lineType') === 'slot') {
|
||||||
const slot = findOrNull(app, 'slots', line.getString('slot'));
|
// The sweep above dropped lapsed holds that couldn't be renewed.
|
||||||
if (!slot || slot.getString('status') !== 'held') {
|
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`);
|
throw conflict(`Your time slot for "${item.getString('name')}" has expired — please pick it again`);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -426,7 +591,9 @@ function createOrderFromIntent(app, intent) {
|
||||||
});
|
});
|
||||||
tx.save(order);
|
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) {
|
for (const line of lines) {
|
||||||
const item = findOrNull(tx, 'items', line.getString('item'));
|
const item = findOrNull(tx, 'items', line.getString('item'));
|
||||||
const slot = findOrNull(tx, 'slots', line.getString('slot'));
|
const slot = findOrNull(tx, 'slots', line.getString('slot'));
|
||||||
|
|
@ -442,12 +609,7 @@ function createOrderFromIntent(app, intent) {
|
||||||
start: slot ? slot.getString('start') : ''
|
start: slot ? slot.getString('start') : ''
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
if (line.getString('lineType') === 'slot' && slot) {
|
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
|
||||||
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') !== '') {
|
|
||||||
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
|
item.set('stock', Math.max(0, item.getInt('stock') - line.getInt('quantity')));
|
||||||
tx.save(item);
|
tx.save(item);
|
||||||
}
|
}
|
||||||
|
|
@ -539,6 +701,8 @@ function recordEmailStatus(app, secretHeader, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
|
bookableSlots,
|
||||||
|
slotDetails,
|
||||||
sweepExpiredHolds,
|
sweepExpiredHolds,
|
||||||
loadActiveBasket,
|
loadActiveBasket,
|
||||||
basketPayload,
|
basketPayload,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,134 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue