Services with several lengths; slots become time windows #6
4 changed files with 1061 additions and 654 deletions
1031
pb_schema.json
1031
pb_schema.json
File diff suppressed because it is too large
Load diff
|
|
@ -3,16 +3,17 @@
|
||||||
/// 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
|
// Slot availability (windows, group sessions, blocking — see lib.js).
|
||||||
// gets the bookable future slots; a signed-in admin can ask for `detail`.
|
// Anyone gets the bookable times for one service and duration
|
||||||
|
// (?item=&minutes=&from=&to=); a signed-in admin can ask for `detail`.
|
||||||
routerAdd('GET', '/api/shop/slots', (e) => {
|
routerAdd('GET', '/api/shop/slots', (e) => {
|
||||||
const shop = require(`${__hooks}/shop/lib.js`);
|
const shop = require(`${__hooks}/shop/lib.js`);
|
||||||
const query = e.request.url.query();
|
const query = e.request.url.query();
|
||||||
if (query.get('detail')) {
|
if (query.get('detail')) {
|
||||||
if (!e.auth) throw new UnauthorizedError('Sign in to see slot details');
|
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, 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) });
|
return e.json(200, shop.bookableTimes($app, { item: query.get('item'), minutes: query.get('minutes'), from: query.get('from'), to: query.get('to') }));
|
||||||
});
|
});
|
||||||
|
|
||||||
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
routerAdd('GET', '/api/shop/basket/{id}', (e) => {
|
||||||
|
|
|
||||||
|
|
@ -62,150 +62,346 @@ function pbDate(ms) {
|
||||||
|
|
||||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
const MINUTE_MS = 60 * 1000;
|
||||||
|
/** Window start times in `grid` mode are this far apart, from the window's start. */
|
||||||
|
const GRID_MS = 30 * MINUTE_MS;
|
||||||
|
/** In `edges` mode, a free stretch that has already begun starts at the next quarter hour. */
|
||||||
|
const EDGE_ROUND_MS = 15 * MINUTE_MS;
|
||||||
|
|
||||||
|
/** A JSON field's value (PocketBase hands JSVM raw bytes), or `fallback`. */
|
||||||
|
function jsonValue(value, fallback) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(toString(value) || 'null');
|
||||||
|
return parsed == null ? fallback : parsed;
|
||||||
|
} catch (_) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Services: durations and prices ──────────────────────────────────────
|
||||||
|
|
||||||
|
function isService(item) {
|
||||||
|
return !!item && item.getString('type') === 'item_with_time';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A service's durations, `[{ minutes, price }]` by length; invalid entries are left out. */
|
||||||
|
function itemDurations(item) {
|
||||||
|
const list = jsonValue(item.get('durations'), []);
|
||||||
|
return (Array.isArray(list) ? list : [])
|
||||||
|
.map((d) => ({ minutes: Math.floor(Number(d && d.minutes)), price: Number(d && d.price) }))
|
||||||
|
.filter((d) => d.minutes > 0 && d.price >= 0 && Number.isFinite(d.price))
|
||||||
|
.sort((a, b) => a.minutes - b.minutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Price of one unit: a product's price, or a service's price for `minutes` (null when not offered). */
|
||||||
|
function unitPrice(item, minutes) {
|
||||||
|
if (!isService(item)) return item.getFloat('price');
|
||||||
|
const duration = itemDurations(item).find((d) => d.minutes === minutes);
|
||||||
|
return duration ? duration.price : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bookableService(item, minutes) {
|
||||||
|
return isService(item) && item.getBool('active') && unitPrice(item, minutes) !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bufferMs(item) {
|
||||||
|
return Math.max(0, item ? item.getInt('bufferMinutes') : 0) * MINUTE_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Items by id, read once per call. */
|
||||||
|
function itemLookup(app) {
|
||||||
|
const cache = {};
|
||||||
|
return (id) => {
|
||||||
|
if (!(id in cache)) cache[id] = findOrNull(app, 'items', id);
|
||||||
|
return cache[id];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// ── Slot availability ───────────────────────────────────────────────────
|
// ── Slot availability ───────────────────────────────────────────────────
|
||||||
//
|
//
|
||||||
// Nothing about bookings is stored on a slot. Its seats are taken by paid
|
// Nothing about bookings is stored on a slot. Bookings are paid order lines
|
||||||
// order lines and by basket lines whose hold (`heldUntil`) hasn't lapsed;
|
// and basket lines whose hold (`heldUntil`) hasn't lapsed; each has its own
|
||||||
// it has `capacity` seats (1 for a one-to-one massage, more for a group).
|
// `start` and `minutes`, and keeps the practitioner busy until its service's
|
||||||
|
// get-ready time is over (`readyAt`). One practitioner works every service,
|
||||||
|
// so any booking blocks every other one it overlaps.
|
||||||
//
|
//
|
||||||
// One practitioner works all services, so a slot with any seat taken
|
// A slot is either
|
||||||
// BLOCKS every other slot it overlaps — whatever the service — including
|
// - a `window` (09:00–12:00 with the services that can be booked in it):
|
||||||
// each service's get-ready time after it. The client can offer three
|
// a booking may start wherever its length plus get-ready time is free.
|
||||||
// massages at 10:00; once one is booked (or in a basket), the others go.
|
// `startTimes` = `grid`: every 30 minutes from the window's start;
|
||||||
|
// `edges`: only right at the start or end of a free stretch, so the
|
||||||
|
// window shrinks from either end and no unusable gaps are left. A
|
||||||
|
// booking must end inside the window; its get-ready time may run past.
|
||||||
|
// - a `session`: one service at a fixed time with `capacity` places (a
|
||||||
|
// group class). Any place taken makes its whole time busy; it can't be
|
||||||
|
// booked while something else overlaps it.
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Occupancy and blocking for the slots starting in [rangeStart, rangeEnd) (epoch ms).
|
* Bookings starting in [rangeStart - 1 day, rangeEnd + 1 day), sorted by
|
||||||
* `options.excludeLineId` leaves one basket line's seats out (used when
|
* start: `{ lineId, slot, item, itemName, start, end, readyAt, quantity,
|
||||||
* changing that line's quantity). Must run inside a transaction when the
|
* status: 'booked' | 'held' }`. `options.excludeLineId` leaves one basket
|
||||||
* result decides a write: PocketBase runs transactions one at a time, so
|
* line out (when re-checking that line itself).
|
||||||
* the check and the write can't interleave with another customer's.
|
|
||||||
*/
|
*/
|
||||||
function slotStates(app, rangeStart, rangeEnd, options) {
|
function busyTimes(app, rangeStart, rangeEnd, item, options) {
|
||||||
const opts = 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 range = { from: pbDate(rangeStart - DAY_MS), to: pbDate(rangeEnd + DAY_MS) };
|
||||||
const records = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start');
|
const busy = [];
|
||||||
if (!records.length) return [];
|
const add = (line, status) => {
|
||||||
|
const start = toMs(line.getString('start'));
|
||||||
const items = {};
|
if (Number.isNaN(start)) return;
|
||||||
const byId = {};
|
const service = item(line.getString('item'));
|
||||||
const states = records.map((record) => {
|
const end = start + line.getInt('minutes') * MINUTE_MS;
|
||||||
const itemId = record.getString('item');
|
busy.push({
|
||||||
if (!(itemId in items)) items[itemId] = findOrNull(app, 'items', itemId);
|
lineId: line.id,
|
||||||
const item = items[itemId];
|
slot: line.getString('slot'),
|
||||||
const start = toMs(record.getString('start'));
|
item: line.getString('item'),
|
||||||
const storedEnd = toMs(record.getString('end'));
|
itemName: service ? service.getString('name') : '',
|
||||||
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,
|
start,
|
||||||
end,
|
end,
|
||||||
readyAt: end + Math.max(0, item ? item.getInt('bufferMinutes') : 0) * 60000,
|
readyAt: end + bufferMs(service),
|
||||||
capacity: Math.max(1, record.getInt('capacity')),
|
quantity: line.getInt('quantity'),
|
||||||
notes: record.getString('notes'),
|
status
|
||||||
booked: 0,
|
});
|
||||||
held: 0,
|
};
|
||||||
blockedBy: ''
|
const inRange = 'start >= {:from} && start < {:to}';
|
||||||
};
|
for (const line of findAll(app, 'order_lines', "lineType = 'slot' && order.status != 'refunded' && " + inRange, range)) add(line, 'booked');
|
||||||
byId[record.id] = state;
|
const held = Object.assign({ now: pbDate(Date.now()) }, range);
|
||||||
return state;
|
for (const line of findAll(app, 'basket_lines', "lineType = 'slot' && heldUntil > {:now} && " + inRange, held)) {
|
||||||
});
|
if (line.id !== opts.excludeLineId) add(line, 'held');
|
||||||
|
|
||||||
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);
|
return busy.sort((a, b) => a.start - b.start);
|
||||||
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 overlapsBusy(busy, start, until) {
|
||||||
function slotState(app, slotId, options) {
|
return busy.find((b) => b.start < until && start < b.readyAt) || null;
|
||||||
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 —
|
* Slots starting in [rangeStart, rangeEnd) (epoch ms) with what's booked
|
||||||
* for the signed-in admin. `query`: from/to (ISO), optional item, or id.
|
* in and around them. Returns `{ slots, busy }`. 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 availability(app, rangeStart, rangeEnd, options) {
|
||||||
|
const item = itemLookup(app);
|
||||||
|
const busy = busyTimes(app, rangeStart, rangeEnd, item, options);
|
||||||
|
const range = { from: pbDate(rangeStart), to: pbDate(rangeEnd) };
|
||||||
|
const slots = findAll(app, 'slots', 'start >= {:from} && start < {:to}', range, 'start').map((record) => {
|
||||||
|
const items = record.getStringSlice('items');
|
||||||
|
const start = toMs(record.getString('start'));
|
||||||
|
const end = toMs(record.getString('end'));
|
||||||
|
const slot = {
|
||||||
|
id: record.id,
|
||||||
|
kind: record.getString('kind') === 'session' ? 'session' : 'window',
|
||||||
|
items,
|
||||||
|
itemNames: items.map((id) => (item(id) ? item(id).getString('name') : '')),
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
notes: record.getString('notes')
|
||||||
|
};
|
||||||
|
const own = busy.filter((b) => b.slot === record.id);
|
||||||
|
const count = (status) => own.filter((b) => b.status === status).reduce((sum, b) => sum + b.quantity, 0);
|
||||||
|
slot.booked = count('booked');
|
||||||
|
slot.held = count('held');
|
||||||
|
if (slot.kind === 'window') {
|
||||||
|
slot.startTimes = record.getString('startTimes') === 'edges' ? 'edges' : 'grid';
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
const service = item(items[0]);
|
||||||
|
slot.minutes = Math.round((end - start) / MINUTE_MS);
|
||||||
|
slot.readyAt = end + bufferMs(service);
|
||||||
|
slot.capacity = Math.max(1, record.getInt('capacity'));
|
||||||
|
slot.bookable = bookableService(service, slot.minutes);
|
||||||
|
slot.blockedBy = overlapsBusy(busy.filter((b) => b.slot !== record.id), start, slot.readyAt);
|
||||||
|
return slot;
|
||||||
|
});
|
||||||
|
return { slots, busy };
|
||||||
|
}
|
||||||
|
|
||||||
|
function freeSeats(session) {
|
||||||
|
return session.capacity - session.booked - session.held;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The free stretches of a window, `[{ start, end }]`: its time minus every booking's time and get-ready time. */
|
||||||
|
function freeTimes(window, busy) {
|
||||||
|
const free = [];
|
||||||
|
let cursor = window.start;
|
||||||
|
for (const b of busy) {
|
||||||
|
if (b.readyAt <= window.start || b.start >= window.end) continue;
|
||||||
|
if (b.start > cursor) free.push({ start: cursor, end: b.start });
|
||||||
|
cursor = Math.max(cursor, b.readyAt);
|
||||||
|
}
|
||||||
|
if (cursor < window.end) free.push({ start: cursor, end: window.end });
|
||||||
|
return free;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where `item` for `minutes` can start in `window` now (epoch ms, ascending). */
|
||||||
|
function windowStartTimes(window, item, minutes, busy, now) {
|
||||||
|
if (!item || window.items.indexOf(item.id) < 0 || !bookableService(item, minutes)) return [];
|
||||||
|
const length = minutes * MINUTE_MS;
|
||||||
|
const until = length + bufferMs(item);
|
||||||
|
const fits = (start) => start > now && start >= window.start && start + length <= window.end && !overlapsBusy(busy, start, start + until);
|
||||||
|
|
||||||
|
const candidates = [];
|
||||||
|
if (window.startTimes === 'edges') {
|
||||||
|
for (const stretch of freeTimes(window, busy)) {
|
||||||
|
// The latest start keeps this booking's get-ready time clear of the next booking.
|
||||||
|
const next = busy.find((b) => b.start >= stretch.end);
|
||||||
|
candidates.push(Math.max(stretch.start, Math.ceil(now / EDGE_ROUND_MS) * EDGE_ROUND_MS));
|
||||||
|
candidates.push(Math.min(window.end - length, (next ? next.start : Infinity) - until));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (let start = window.start; start + length <= window.end; start += GRID_MS) candidates.push(start);
|
||||||
|
}
|
||||||
|
return candidates.filter((start, i) => candidates.indexOf(start) === i && fits(start)).sort((a, b) => a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bookable times for one service and duration starting in [from, to):
|
||||||
|
* window start times and group sessions with places left.
|
||||||
|
*/
|
||||||
|
function timesFor(app, item, minutes, from, to) {
|
||||||
|
const now = Date.now();
|
||||||
|
const { slots, busy } = availability(app, from, to);
|
||||||
|
const times = [];
|
||||||
|
for (const slot of slots) {
|
||||||
|
if (slot.kind === 'window') {
|
||||||
|
for (const start of windowStartTimes(slot, item, minutes, busy, now)) {
|
||||||
|
times.push({ slot: slot.id, kind: 'window', start, end: start + minutes * MINUTE_MS, capacity: 1, free: 1 });
|
||||||
|
}
|
||||||
|
} else if (slot.items[0] === item.id && slot.minutes === minutes && slot.bookable && !slot.blockedBy && slot.start > now && freeSeats(slot) > 0) {
|
||||||
|
times.push({ slot: slot.id, kind: 'session', start: slot.start, end: slot.end, capacity: slot.capacity, free: freeSeats(slot) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return times.sort((a, b) => a.start - b.start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The public shop listing (GET /api/shop/slots): times a customer can book
|
||||||
|
* now for `item` at `minutes`, starting in [from, to). When there are none,
|
||||||
|
* `next` is the first bookable time after `to` (within a year), so the shop
|
||||||
|
* can point to it.
|
||||||
|
*/
|
||||||
|
function bookableTimes(app, query) {
|
||||||
|
const empty = { times: [], next: null };
|
||||||
|
const item = findOrNull(app, 'items', String(query.item || ''));
|
||||||
|
const minutes = Math.floor(Number(query.minutes));
|
||||||
|
if (!bookableService(item, minutes)) return empty;
|
||||||
|
const now = Date.now();
|
||||||
|
const from = Math.max(now, toMs(query.from));
|
||||||
|
const to = toMs(query.to);
|
||||||
|
if (Number.isNaN(from) || Number.isNaN(to)) throw new BadRequestError('from and to are required');
|
||||||
|
if (to - from > 100 * DAY_MS) throw new BadRequestError('Range too long');
|
||||||
|
|
||||||
|
const iso = (ms) => new Date(ms).toISOString();
|
||||||
|
const listed = (t) => ({ slot: t.slot, kind: t.kind, start: iso(t.start), end: iso(t.end), capacity: t.capacity, free: t.free });
|
||||||
|
const times = to > from ? timesFor(app, item, minutes, from, to) : [];
|
||||||
|
if (times.length) return { times: times.map(listed), next: null };
|
||||||
|
for (let start = Math.max(from, to); start < now + 366 * DAY_MS; start += 31 * DAY_MS) {
|
||||||
|
const later = timesFor(app, item, minutes, start, start + 31 * DAY_MS);
|
||||||
|
if (later.length) return { times: [], next: iso(later[0].start) };
|
||||||
|
}
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every slot in a range (or one slot by id) with its bookings — for the
|
||||||
|
* signed-in admin. `query`: from/to (ISO), optional item, or id.
|
||||||
*/
|
*/
|
||||||
function slotDetails(app, query) {
|
function slotDetails(app, query) {
|
||||||
let states;
|
let slots;
|
||||||
|
let busy;
|
||||||
|
let from;
|
||||||
|
let to;
|
||||||
if (query.id) {
|
if (query.id) {
|
||||||
const state = slotState(app, String(query.id));
|
const record = findOrNull(app, 'slots', String(query.id));
|
||||||
states = state ? [state] : [];
|
if (!record) return { slots: [], bookings: [] };
|
||||||
|
from = toMs(record.getString('start'));
|
||||||
|
to = from + 1;
|
||||||
|
({ slots, busy } = availability(app, from, to));
|
||||||
} else {
|
} else {
|
||||||
const from = toMs(query.from);
|
from = toMs(query.from);
|
||||||
const to = toMs(query.to);
|
to = toMs(query.to);
|
||||||
if (Number.isNaN(from) || Number.isNaN(to) || to <= from) throw new BadRequestError('from and to are required');
|
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');
|
if (to - from > 400 * DAY_MS) throw new BadRequestError('Range too long');
|
||||||
states = slotStates(app, from, to);
|
({ slots, busy } = availability(app, from, to));
|
||||||
if (query.item) states = states.filter((s) => s.item === query.item);
|
if (query.item) slots = slots.filter((s) => s.items.indexOf(String(query.item)) >= 0);
|
||||||
}
|
}
|
||||||
return states.map((s) => ({
|
const iso = (ms) => new Date(ms).toISOString();
|
||||||
id: s.id,
|
const booking = (b) => ({ slot: b.slot, item: b.item, itemName: b.itemName, start: iso(b.start), end: iso(b.end), readyAt: iso(b.readyAt), quantity: b.quantity, status: b.status });
|
||||||
item: s.item,
|
return {
|
||||||
itemName: s.itemName,
|
slots: slots.map((s) => {
|
||||||
start: new Date(s.start).toISOString(),
|
const detail = { id: s.id, kind: s.kind, items: s.items, itemNames: s.itemNames, start: iso(s.start), end: iso(s.end), notes: s.notes, booked: s.booked, held: s.held };
|
||||||
end: new Date(s.end).toISOString(),
|
if (s.kind === 'window') {
|
||||||
capacity: s.capacity,
|
detail.startTimes = s.startTimes;
|
||||||
notes: s.notes,
|
detail.free = freeTimes(s, busy).map((f) => ({ start: iso(f.start), end: iso(f.end) }));
|
||||||
booked: s.booked,
|
} else {
|
||||||
held: s.held,
|
detail.minutes = s.minutes;
|
||||||
blockedBy: s.blockedBy
|
detail.capacity = s.capacity;
|
||||||
}));
|
detail.blockedBy = s.blockedBy ? booking(s.blockedBy) : null;
|
||||||
|
}
|
||||||
|
return detail;
|
||||||
|
}),
|
||||||
|
bookings: busy.filter((b) => b.start >= from && b.start < to).map(booking)
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Check a session can take `seats` more places; returns an ApiError to throw, or null. */
|
||||||
* Check a slot can take `seats` more seats; returns an ApiError to throw,
|
function seatProblem(session, seats) {
|
||||||
* or null. Call inside the transaction that then writes the hold.
|
if (!session.bookable) return new NotFoundError('This session is no longer offered');
|
||||||
*/
|
if (session.start <= Date.now()) return conflict('This time has already passed — please pick another');
|
||||||
function seatProblem(state, seats) {
|
if (session.blockedBy) return conflict('This time is no longer available — please pick another');
|
||||||
if (!state || !state.bookable) return new NotFoundError('Slot not found');
|
const free = freeSeats(session);
|
||||||
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) {
|
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 conflict(free <= 0 ? 'This time is fully booked — please pick another' : `Only ${free} place${free === 1 ? '' : 's'} left at this time`);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check a booking request — `{ slotId, itemId, minutes, start (ms), seats }`
|
||||||
|
* — against availability. Returns `{ error }` (an ApiError to throw) or
|
||||||
|
* `{ booking: { slot, kind, item, start, minutes } }` (for a session, its
|
||||||
|
* own service and time; itemId/minutes/start are ignored). Call inside the
|
||||||
|
* transaction that then writes the hold.
|
||||||
|
*/
|
||||||
|
function checkBooking(app, request, options) {
|
||||||
|
const record = findOrNull(app, 'slots', String(request.slotId || ''));
|
||||||
|
if (!record) return { error: new NotFoundError('This time is no longer offered — please pick another') };
|
||||||
|
const slotStart = toMs(record.getString('start'));
|
||||||
|
const { slots, busy } = availability(app, slotStart, slotStart + 1, options);
|
||||||
|
const slot = slots.find((s) => s.id === record.id);
|
||||||
|
if (!slot) return { error: new NotFoundError('This time is no longer offered — please pick another') };
|
||||||
|
|
||||||
|
if (slot.kind === 'session') {
|
||||||
|
const problem = seatProblem(slot, request.seats);
|
||||||
|
if (problem) return { error: problem };
|
||||||
|
return { booking: { slot: slot.id, kind: 'session', item: slot.items[0], start: slot.start, minutes: slot.minutes } };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const item = findOrNull(app, 'items', String(request.itemId || ''));
|
||||||
|
const minutes = Math.floor(Number(request.minutes));
|
||||||
|
if (!bookableService(item, minutes)) return { error: new NotFoundError('This service is not offered at this length any more') };
|
||||||
|
if (!(request.start > now)) return { error: conflict('This time has already passed — please pick another') };
|
||||||
|
if (windowStartTimes(slot, item, minutes, busy, now).indexOf(request.start) < 0) {
|
||||||
|
return { error: conflict('This time is no longer available — please pick another') };
|
||||||
|
}
|
||||||
|
return { booking: { slot: slot.id, kind: 'window', item: item.id, start: request.start, minutes } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a basket line asks for, in checkBooking's terms. */
|
||||||
|
function lineRequest(line) {
|
||||||
|
return {
|
||||||
|
slotId: line.getString('slot'),
|
||||||
|
itemId: line.getString('item'),
|
||||||
|
minutes: line.getInt('minutes'),
|
||||||
|
start: toMs(line.getString('start')),
|
||||||
|
seats: line.getInt('quantity')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing
|
* Run `fn(tx)` in a transaction; `fn` returns an ApiError to refuse (nothing
|
||||||
* is written) or nothing to commit. Unexpected failures become `fallback`.
|
* is written) or nothing to commit. Unexpected failures become `fallback`.
|
||||||
|
|
@ -259,12 +455,26 @@ function basketLines(app, basketId) {
|
||||||
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: basketId });
|
return findAll(app, 'basket_lines', 'basket = {:basket}', { basket: basketId });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The basket as returned to the public app, which maps it to the `Basket` type. */
|
/**
|
||||||
|
* The basket as returned to the public app, which maps it to the `Basket`
|
||||||
|
* type. Each line also gets `unitPrice` (null: the service is no longer
|
||||||
|
* offered at that length) and, for a booking, `end`.
|
||||||
|
*/
|
||||||
function basketPayload(app, basket) {
|
function basketPayload(app, basket) {
|
||||||
if (!basket) return null;
|
if (!basket) return null;
|
||||||
const lines = basketLines(app, basket.id);
|
const lines = basketLines(app, basket.id);
|
||||||
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
|
for (const line of lines) app.expandRecord(line, ['item', 'slot', 'item.image'], null);
|
||||||
return { record: plain(basket), lines: lines.map(plain) };
|
return {
|
||||||
|
record: plain(basket),
|
||||||
|
lines: lines.map((line) => {
|
||||||
|
const json = plain(line);
|
||||||
|
const item = line.expandedOne('item');
|
||||||
|
json.unitPrice = item ? unitPrice(item, line.getInt('minutes')) : null;
|
||||||
|
const start = toMs(line.getString('start'));
|
||||||
|
if (!Number.isNaN(start)) json.end = new Date(start + line.getInt('minutes') * MINUTE_MS).toISOString();
|
||||||
|
return json;
|
||||||
|
})
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function createBasket(app) {
|
function createBasket(app) {
|
||||||
|
|
@ -277,10 +487,10 @@ function createBasket(app) {
|
||||||
* Renew the hold on every slot line in a basket. Used at checkout start
|
* Renew the hold on every slot line in a basket. Used at checkout start
|
||||||
* (30 min), after a failed payment (10 min, so the customer can retry) and
|
* (30 min), after a failed payment (10 min, so the customer can retry) and
|
||||||
* when the customer asks for more time (`renew_holds`, 10 min). A live hold
|
* when the customer asks for more time (`renew_holds`, 10 min). A live hold
|
||||||
* is extended, never shortened (its seats are already counted). A lapsed
|
* is extended, never shortened (it's already counted). A lapsed one that
|
||||||
* one that hasn't been swept yet is rescued only if its seats are still
|
* hasn't been swept yet is rescued only if its time could still be booked
|
||||||
* free and nothing has blocked the time since — otherwise it's left for
|
* now — otherwise it's left for the sweep, and checkout tells the customer
|
||||||
* the sweep, and checkout tells the customer the slot expired.
|
* the time expired.
|
||||||
*/
|
*/
|
||||||
function extendBasketHolds(app, basketId, durationMs) {
|
function extendBasketHolds(app, basketId, durationMs) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
@ -297,7 +507,7 @@ function extendBasketHolds(app, basketId, durationMs) {
|
||||||
try {
|
try {
|
||||||
app.runInTransaction((tx) => {
|
app.runInTransaction((tx) => {
|
||||||
const fresh = tx.findRecordById('basket_lines', line.id);
|
const fresh = tx.findRecordById('basket_lines', line.id);
|
||||||
if (seatProblem(slotState(tx, fresh.getString('slot')), fresh.getInt('quantity'))) return;
|
if (checkBooking(tx, lineRequest(fresh), { excludeLineId: fresh.id }).error) return;
|
||||||
fresh.set('heldUntil', until);
|
fresh.set('heldUntil', until);
|
||||||
tx.save(fresh);
|
tx.save(fresh);
|
||||||
});
|
});
|
||||||
|
|
@ -343,15 +553,35 @@ function basketAction(app, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'add_slot': {
|
case 'add_slot': {
|
||||||
// Adding a slot that's already in the basket adds seats to that line.
|
// A window booking: `slotId` (the window), `itemId`, `minutes` and
|
||||||
const slotId = String(body.slotId || '');
|
// `start` (one of the listed times). A group session: `slotId` and
|
||||||
const seats = Math.max(1, Math.floor(Number(body.seats)) || 1);
|
// `seats`; adding a session already in the basket adds places to
|
||||||
|
// that line.
|
||||||
|
const request = {
|
||||||
|
slotId: String(body.slotId || ''),
|
||||||
|
itemId: String(body.itemId || ''),
|
||||||
|
minutes: Math.floor(Number(body.minutes)),
|
||||||
|
start: toMs(body.start),
|
||||||
|
seats: Math.max(1, Math.floor(Number(body.seats)) || 1)
|
||||||
|
};
|
||||||
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
|
guardedTransaction(app, 'Could not reserve this time — please try again', (tx) => {
|
||||||
const problem = seatProblem(slotState(tx, slotId), seats);
|
const check = checkBooking(tx, request);
|
||||||
if (problem) return problem;
|
if (check.error) return check.error;
|
||||||
const existing = findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: slotId })[0];
|
const booking = check.booking;
|
||||||
const line = existing || newRecord(tx, 'basket_lines', { basket: basket.id, item: tx.findRecordById('slots', slotId).getString('item'), slot: slotId, quantity: 0, lineType: 'slot' });
|
const existing =
|
||||||
line.set('quantity', line.getInt('quantity') + seats);
|
booking.kind === 'session' ? findAll(tx, 'basket_lines', 'basket = {:basket} && slot = {:slot}', { basket: basket.id, slot: booking.slot })[0] : null;
|
||||||
|
const line =
|
||||||
|
existing ||
|
||||||
|
newRecord(tx, 'basket_lines', {
|
||||||
|
basket: basket.id,
|
||||||
|
item: booking.item,
|
||||||
|
slot: booking.slot,
|
||||||
|
start: new Date(booking.start).toISOString(),
|
||||||
|
minutes: booking.minutes,
|
||||||
|
quantity: 0,
|
||||||
|
lineType: 'slot'
|
||||||
|
});
|
||||||
|
line.set('quantity', line.getInt('quantity') + (booking.kind === 'session' ? request.seats : 1));
|
||||||
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
line.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||||
tx.save(line);
|
tx.save(line);
|
||||||
});
|
});
|
||||||
|
|
@ -364,11 +594,13 @@ function basketAction(app, body) {
|
||||||
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') {
|
if (line.getString('lineType') === 'slot') {
|
||||||
// Seats for a group session: re-check capacity without this line's current seats.
|
// Places in a group session: re-check capacity without this line's current places.
|
||||||
guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => {
|
guardedTransaction(app, 'Could not change the number of places — please try again', (tx) => {
|
||||||
const fresh = tx.findRecordById('basket_lines', line.id);
|
const fresh = tx.findRecordById('basket_lines', line.id);
|
||||||
const problem = seatProblem(slotState(tx, fresh.getString('slot'), { excludeLineId: fresh.id }), quantity);
|
const slot = findOrNull(tx, 'slots', fresh.getString('slot'));
|
||||||
if (problem) return problem;
|
if (!slot || slot.getString('kind') !== 'session') return new BadRequestError('Only group sessions have more than one place');
|
||||||
|
const check = checkBooking(tx, Object.assign(lineRequest(fresh), { seats: quantity }), { excludeLineId: fresh.id });
|
||||||
|
if (check.error) return check.error;
|
||||||
fresh.set('quantity', quantity);
|
fresh.set('quantity', quantity);
|
||||||
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
fresh.set('heldUntil', isoIn(SLOT_HOLD_MS));
|
||||||
tx.save(fresh);
|
tx.save(fresh);
|
||||||
|
|
@ -489,7 +721,9 @@ function startCheckout(app, body) {
|
||||||
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
|
throw conflict(`Only ${item.getInt('stock')} of "${item.getString('name')}" left in stock`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
totalCents += Math.round(item.getFloat('price') * 100) * quantity;
|
const price = unitPrice(item, line.getInt('minutes'));
|
||||||
|
if (price === null) throw conflict(`"${item.getString('name')}" is no longer offered for ${line.getInt('minutes')} minutes — please pick it again`);
|
||||||
|
totalCents += Math.round(price * 100) * quantity;
|
||||||
summary.push(`${quantity}× ${item.getString('name')}`);
|
summary.push(`${quantity}× ${item.getString('name')}`);
|
||||||
}
|
}
|
||||||
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
|
if (totalCents <= 0) throw new BadRequestError('Basket total must be positive');
|
||||||
|
|
@ -602,12 +836,11 @@ function createOrderFromIntent(app, intent) {
|
||||||
});
|
});
|
||||||
tx.save(order);
|
tx.save(order);
|
||||||
|
|
||||||
// Snapshot lines and decrement stock. A slot's seats move from the
|
// Snapshot lines and decrement stock. A booked time moves from the
|
||||||
// basket line (a hold) to the order line (a booking) in this same
|
// basket line (a hold) to the order line (a booking) in this same
|
||||||
// transaction, so availability never sees them free in between.
|
// transaction, so availability never sees it 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'));
|
|
||||||
tx.save(
|
tx.save(
|
||||||
newRecord(tx, 'order_lines', {
|
newRecord(tx, 'order_lines', {
|
||||||
order: order.id,
|
order: order.id,
|
||||||
|
|
@ -616,8 +849,9 @@ function createOrderFromIntent(app, intent) {
|
||||||
quantity: line.getInt('quantity'),
|
quantity: line.getInt('quantity'),
|
||||||
lineType: line.getString('lineType'),
|
lineType: line.getString('lineType'),
|
||||||
name: item ? item.getString('name') : 'Unknown item',
|
name: item ? item.getString('name') : 'Unknown item',
|
||||||
price: item ? item.getFloat('price') : 0,
|
price: (item && unitPrice(item, line.getInt('minutes'))) || 0,
|
||||||
start: slot ? slot.getString('start') : ''
|
start: line.getString('start'),
|
||||||
|
minutes: line.getInt('minutes')
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
|
if (line.getString('lineType') === 'item' && item && item.get('stock') != null && item.get('stock') !== '') {
|
||||||
|
|
@ -715,7 +949,7 @@ function recordEmailStatus(app, secretHeader, body) {
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
bookableSlots,
|
bookableTimes,
|
||||||
slotDetails,
|
slotDetails,
|
||||||
sweepExpiredHolds,
|
sweepExpiredHolds,
|
||||||
loadActiveBasket,
|
loadActiveBasket,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,165 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
// Services get several durations; slots become availability windows.
|
||||||
|
//
|
||||||
|
// Before: a service had one `duration` and `price`, and a slot was one
|
||||||
|
// service at one fixed time. After:
|
||||||
|
//
|
||||||
|
// - items.durations: [{ minutes, price }] — a service can be booked for any
|
||||||
|
// of these (items.price stays: the product price, and for a service the
|
||||||
|
// lowest duration price, kept in sync by the admin). items.duration goes.
|
||||||
|
// - slots.kind: `window` — a stretch of time (09:00–12:00) in which any of
|
||||||
|
// its `items` can be booked, for any of their durations; each booking
|
||||||
|
// takes its time plus get-ready time out of the window. `startTimes`
|
||||||
|
// says where bookings may start: `grid` (every 30 min) or `edges` (only
|
||||||
|
// right at the start or end of the free time, so no gaps are left).
|
||||||
|
// `session` — a fixed time for one service with `capacity` places (a
|
||||||
|
// group class), as slots were before.
|
||||||
|
// - basket_lines / order_lines: `start` and `minutes` — the booked time
|
||||||
|
// (order_lines already had `start`). A booking no longer needs its slot
|
||||||
|
// to count: availability reads these.
|
||||||
|
//
|
||||||
|
// Existing slots are deleted (agreed: start fresh). Before that, every
|
||||||
|
// order line gets `minutes` from its slot, so paid bookings keep blocking
|
||||||
|
// their time; basket holds on slots are dropped (customers pick again).
|
||||||
|
// Past orders keep their own name/price/start snapshot.
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function minutesBetween(start, end) {
|
||||||
|
const ms = Date.parse(String(end).replace(' ', 'T')) - Date.parse(String(start).replace(' ', 'T'));
|
||||||
|
return ms > 0 ? Math.round(ms / 60000) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
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. Durations (one per service from its old duration + price).
|
||||||
|
if (items && !items.fields.getByName('durations')) {
|
||||||
|
items.fields.add(new JSONField({ id: 'json_itemdurations', name: 'durations', maxSize: 20000 }));
|
||||||
|
app.save(items);
|
||||||
|
for (const item of app.findAllRecords('items')) {
|
||||||
|
if (item.getString('type') !== 'item_with_time') continue;
|
||||||
|
item.set('durations', [{ minutes: item.getInt('duration') || 60, price: item.getFloat('price') }]);
|
||||||
|
try {
|
||||||
|
app.saveNoValidate(item);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`[migration] could not set durations on item ${item.id}: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (items && items.fields.getByName('duration')) {
|
||||||
|
items.fields.removeByName('duration');
|
||||||
|
app.save(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Booked times on the lines.
|
||||||
|
if (basketLines && !basketLines.fields.getByName('minutes')) {
|
||||||
|
basketLines.fields.add(new DateField({ id: 'date_blstart0001', name: 'start' }));
|
||||||
|
basketLines.fields.add(new NumberField({ id: 'num_blminutes001', name: 'minutes', min: 0, onlyInt: true }));
|
||||||
|
basketLines.indexes = [...basketLines.indexes, 'CREATE INDEX `idx_basket_lines_start` ON `basket_lines` (`start`)'];
|
||||||
|
app.save(basketLines);
|
||||||
|
}
|
||||||
|
if (orderLines && !orderLines.fields.getByName('minutes')) {
|
||||||
|
orderLines.fields.add(new NumberField({ id: 'num_olminutes001', name: 'minutes', min: 0, onlyInt: true }));
|
||||||
|
orderLines.indexes = [...orderLines.indexes, 'CREATE INDEX `idx_order_lines_start` ON `order_lines` (`start`)'];
|
||||||
|
app.save(orderLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Start fresh: keep what paid bookings need, then drop the old slots.
|
||||||
|
if (slots && slots.fields.getByName('item')) {
|
||||||
|
if (orderLines) {
|
||||||
|
for (const line of app.findRecordsByFilter('order_lines', "slot != ''", '', 0, 0)) {
|
||||||
|
try {
|
||||||
|
const slot = app.findRecordById('slots', line.getString('slot'));
|
||||||
|
if (!line.getString('start')) line.set('start', slot.getString('start'));
|
||||||
|
line.set('minutes', minutesBetween(slot.getString('start'), slot.getString('end')));
|
||||||
|
line.set('slot', '');
|
||||||
|
app.saveNoValidate(line);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`[migration] could not keep the booked time of order line ${line.id}: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (basketLines) {
|
||||||
|
for (const line of app.findRecordsByFilter('basket_lines', "lineType = 'slot'", '', 0, 0)) {
|
||||||
|
try {
|
||||||
|
app.delete(line);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`[migration] could not drop basket line ${line.id}: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const slot of app.findAllRecords('slots')) {
|
||||||
|
try {
|
||||||
|
app.delete(slot);
|
||||||
|
} catch (e) {
|
||||||
|
console.log(`[migration] could not delete slot ${slot.id}: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_item_start')), 'CREATE INDEX `idx_slots_start` ON `slots` (`start`)'];
|
||||||
|
slots.fields.removeByName('item');
|
||||||
|
slots.fields.add(new SelectField({ id: 'sel_slotkind001', name: 'kind', values: ['window', 'session'], maxSelect: 1, required: true }));
|
||||||
|
slots.fields.add(new RelationField({ id: 'rel_slotitems01', name: 'items', collectionId: items ? items.id : 'pbc_items00001', maxSelect: 50, cascadeDelete: false }));
|
||||||
|
slots.fields.add(new SelectField({ id: 'sel_slotstarts1', name: 'startTimes', values: ['grid', 'edges'], maxSelect: 1 }));
|
||||||
|
app.save(slots);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(app) => {
|
||||||
|
// Revert the schema only. Windows can't become one-service slots, so
|
||||||
|
// slots are deleted again; restore a backup to get the old ones back.
|
||||||
|
const items = find(app, 'items');
|
||||||
|
const slots = find(app, 'slots');
|
||||||
|
if (items && !items.fields.getByName('duration')) {
|
||||||
|
items.fields.add(new NumberField({ id: 'num_itemdur0001', name: 'duration', min: 1 }));
|
||||||
|
app.save(items);
|
||||||
|
for (const item of app.findAllRecords('items')) {
|
||||||
|
let durations = [];
|
||||||
|
try {
|
||||||
|
durations = JSON.parse(toString(item.get('durations')) || '[]') || [];
|
||||||
|
} catch (_) {}
|
||||||
|
if (!durations.length) continue;
|
||||||
|
item.set('duration', durations[0].minutes);
|
||||||
|
app.saveNoValidate(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (items && items.fields.getByName('durations')) {
|
||||||
|
items.fields.removeByName('durations');
|
||||||
|
app.save(items);
|
||||||
|
}
|
||||||
|
if (slots && !slots.fields.getByName('item')) {
|
||||||
|
for (const line of app.findRecordsByFilter('basket_lines', "lineType = 'slot'", '', 0, 0)) app.delete(line);
|
||||||
|
for (const slot of app.findAllRecords('slots')) app.delete(slot);
|
||||||
|
for (const name of ['kind', 'items', 'startTimes']) {
|
||||||
|
if (slots.fields.getByName(name)) slots.fields.removeByName(name);
|
||||||
|
}
|
||||||
|
slots.fields.add(new RelationField({ id: 'rel_slotitem001', name: 'item', required: true, collectionId: items ? items.id : 'pbc_items00001', maxSelect: 1, cascadeDelete: true }));
|
||||||
|
slots.indexes = [...slots.indexes.filter((index) => !index.includes('idx_slots_start')), 'CREATE INDEX `idx_slots_item_start` ON `slots` (`item`, `start`)'];
|
||||||
|
app.save(slots);
|
||||||
|
}
|
||||||
|
const basketLines = find(app, 'basket_lines');
|
||||||
|
if (basketLines && basketLines.fields.getByName('minutes')) {
|
||||||
|
basketLines.fields.removeByName('start');
|
||||||
|
basketLines.fields.removeByName('minutes');
|
||||||
|
basketLines.indexes = basketLines.indexes.filter((index) => !index.includes('idx_basket_lines_start'));
|
||||||
|
app.save(basketLines);
|
||||||
|
}
|
||||||
|
const orderLines = find(app, 'order_lines');
|
||||||
|
if (orderLines && orderLines.fields.getByName('minutes')) {
|
||||||
|
orderLines.fields.removeByName('minutes');
|
||||||
|
orderLines.indexes = orderLines.indexes.filter((index) => !index.includes('idx_order_lines_start'));
|
||||||
|
app.save(orderLines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
Loading…
Add table
Add a link
Reference in a new issue